How to Pass an Array in Query Parameters
Pass an array in query parameters by repeating the parameter name, such as /users?id=3&id=4&id=5, unless the API requires a different format. URLs carry text rather than native arrays, so the client and server must agree on how multiple values are serialized and parsed. The examples below cover the default OpenAPI format, JavaScript and Python handling, and the bracketed or delimited formats some APIs expect.
How Arrays Work in a Query String
An array in a query string is a serialization agreement, not a built-in URL data type.
A query string starts after ?, and ordinary query parameters are separated by &. Repeating a name lets you send several values under that name, but the receiving code must retrieve all of them.
For example, an API might interpret repeated id parameters as a list of user IDs. Another endpoint might expect a single comma-separated value instead. Both are possible; neither makes the server automatically understand the other.
There are also two separate operations to account for:
- Serialization: Turning the array into query-string text and encoding special characters.
- Parsing and validation: Recovering the individual values, checking them, and converting them to the types the application expects.
Even when you send numeric IDs, query-string parsing initially produces strings. An API schema can declare integers, but the server or framework must still perform that conversion.
How to Send and Parse a Query Array
Choose the format matching the endpoint’s OpenAPI style and explode fields.
| Format | style |
explode |
Example URL | ||
|---|---|---|---|---|---|
| Repeated names | form |
true |
/users?id=3&id=4&id=5 |
||
| Comma-separated values | form |
false |
/users?id=3,4,5 |
||
| Space-separated values | spaceDelimited |
false |
/users?id=3%204%205 |
||
| Pipe-separated values | pipeDelimited |
false |
`/users?id=3\ | 4\ | 5` |
Step 1: Match the Endpoint’s Array Definition
- Find the parameter’s name, item type, and serialization settings in the endpoint documentation.
- Use the documented format rather than assuming your HTTP client’s default matches it.
- If you control the API, declare the format explicitly so generated clients and server code can agree.
OpenAPI 3 query arrays default to style: form and explode: true, producing repeated parameter names, per Swagger’s parameter serialization documentation.
Here is an OpenAPI parameter definition for that format:
parameters:
- in: query
name: id
required: false
style: form
explode: true
schema:
type: array
items:
type: integer
minimum: 0
This example accepts non-negative integer IDs. The item constraint is an application choice, not a requirement for all query arrays.
For a delimited endpoint, confirm the exact style and explode combination rather than substituting commas, spaces, or pipes yourself. The pipe example in the table shows the separator readably; its percent-encoded form is %7C.
Step 2: Build the URL With a Query Serializer
- Create a URL for the endpoint.
- Append each item separately.
- Give the serializer unencoded values and let it handle URL encoding.
In JavaScript, URL and URLSearchParams provide the necessary behavior:
const ids = [3, 4, 5];
const url = new URL("https://api.example.com/users");
for (const id of ids) {
url.searchParams.append("id", String(id));
}
console.log(url.href);
Replace the example origin with your API’s origin before sending the request. Appending parameters also avoids manually deciding whether to add ? or & when a URL already has a query string.
For OpenAPI parameters, the default allowReserved: false means reserved characters in values are percent-encoded. A slash inside a value, for instance, becomes %2F or %2f.
This JavaScript example keeps an ampersand and a slash inside their respective values:
const params = new URLSearchParams();
params.append("tag", "R&D");
params.append("tag", "a/b");
console.log(params.toString());
// tag=R%26D&tag=a%2Fb
The encoded ampersand is data, not a separator introducing another parameter.
Do not run values through encodeURIComponent() before adding them to URLSearchParams. The serializer would encode the percent signs again, turning an already encoded %2F into %252F. Likewise, encoding an entire assembled URL is not a substitute for encoding its individual parameter values.
Step 3: Retrieve Every Value and Validate the Items
- Read the parameter using an API that preserves repeated names.
- Validate each item before using it.
- Convert values to the application’s expected type only after validation.
For JavaScript, getAll() retrieves all values associated with a name:
function readIds(requestUrl) {
const params = new URL(
requestUrl,
"https://api.example.com"
).searchParams;
return params.getAll("id").map((value) => {
if (!/^[0-9]+$/.test(value)) {
throw new Error("Each id must be a non-negative integer");
}
const id = Number(value);
if (!Number.isSafeInteger(id)) {
throw new Error("Each id must be a safe JavaScript integer");
}
return id;
});
}
Pass the incoming request URL to this function in your server handler. The base URL lets it accept a relative request target as well as an absolute URL.
In the handler, catch validation failures and return an appropriate client-error response, such as 400 Bad Request, rather than allowing them to become unhandled server errors. An omitted id parameter produces an empty array in this implementation; an explicitly empty value fails validation.
Use a different validator for other item types. For opaque identifiers, preserving strings is often preferable to numeric conversion, particularly when leading zeros or very large identifiers matter.
Step 4: Check the Round Trip and Send the Request
- Verify locally that serialization and parsing preserve the intended array.
- Send the URL to your actual endpoint.
- Inspect the server’s parsed values as well as the response.
Check that readIds(url.href) recovers the original ids array: const parsedIds = readIds(url.href); if (JSON.stringify(parsedIds) !== JSON.stringify(ids)) { throw new Error(“Array query round trip failed”); } console.log(parsedIds); // [3, 4, 5]
const parsedIds = readIds(url.href);
if (JSON.stringify(parsedIds) !== JSON.stringify(ids)) {
throw new Error("Array query round trip failed");
}
console.log(parsedIds);
// [3, 4, 5]
Then send the request. In a JavaScript module or a browser console supporting top-level await:
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
console.log(await response.json());
This response-handling example assumes the endpoint returns JSON. Adapt it if your API returns another representation.
A successful HTTP response alone does not prove the array worked. Confirm that the endpoint processed every supplied item, rather than silently accepting only one.
Other Array Formats and Server Parsers
Bracketed, indexed, delimiter-based, and repeated query formats require endpoint documentation and parser support.
Bracketed and Indexed Parameter Names
Some APIs expect empty brackets in the parameter name:
?my_array[]=value1&my_array[]=value2&my_array[]=value3
Others expect explicit indexes:
?my_array[0]=value1&my_array[1]=value2&my_array[2]=value3
Use these conventions only when the endpoint documentation and server-side query parser support them. They are not interchangeable with an unbracketed parameter name.
For example, PHP’s standard query parsing recognizes bracketed array notation. A parser without that convention may instead treat my_array[] as a literal name or treat each indexed name as a separate parameter.
Build bracketed names with your serializer just as you would any other name:
const params = new URLSearchParams();
for (const value of ["value1", "value2", "value3"]) {
params.append("my_array[]", value);
}
const values = params.getAll("my_array[]");
console.log(values);
// ["value1", "value2", "value3"]
The serialized brackets may appear as %5B%5D. That is normal percent-encoding; the server’s query decoder recovers the bracket characters before its parser applies any array convention.
Delimiter-Based Arrays
Delimiter-based formats work when the endpoint explicitly defines how to join and split values. They are straightforward for values such as integer IDs, but require more care with unrestricted strings.
For example, if one item is Smith, Jane, splitting a decoded parameter on every comma will incorrectly turn that item into two values. Percent-encoding the comma does not necessarily solve this: many server parsers decode the parameter before application code splits it.
Repeated names avoid delimiter ambiguity because each array item has its own parameter value.
If an existing API requires a delimiter, follow its rules for embedded delimiters. When designing a new endpoint, repeated names are usually the simpler choice for arbitrary strings.
Python Query Parsers
Use the collection-reading method provided by your framework rather than converting the query parameters to an ordinary dictionary.
Inside a Flask request handler:
ids = request.args.getlist("id")
Inside a Django view:
ids = request.GET.getlist("id")
Both retrieve a list of strings. Apply the endpoint’s item validation before using those strings in queries or application logic.
For standalone parsing with Python’s standard library:
from urllib.parse import parse_qs, urlsplit
url = "https://api.example.com/users?id=3&id=4&id=5"
query = parse_qs(
urlsplit(url).query,
keep_blank_values=True,
)
ids = query.get("id", [])
assert ids == ["3", "4", "5"]
Setting keep_blank_values=True preserves explicit empty values so your validation can distinguish them from a missing parameter. If the API uses a bracketed name, request that exact name from a parser that treats brackets literally.
Swagger and OpenAPI 2 Arrays
In Swagger/OpenAPI 2, query arrays can contain only primitive item types, such as strings, integers, or booleans; query objects are not supported, per Swagger’s parameter documentation.
To describe repeated query names in that version, use collectionFormat: multi:
parameters:
- in: query
name: id
type: array
items:
type: integer
collectionFormat: multi
An array of object-shaped filters cannot be modeled as primitive query-array items in Swagger 2. Do not describe those items as objects and expect tooling to invent a compatible serialization.
Empty Arrays, Nested Data, and Large Requests
Empty arrays, nested data, and large requests require explicit contracts, supported serialization, validation, and application-specific limits.
Missing Parameters and Empty Values
A missing parameter and an empty value are different inputs:
/users
/users?id=
The first contains no id entry. The second contains one id entry whose value is an empty string.
Repeated-name serialization has no separate, universal marker for an empty array. A common contract omits the parameter when the array is empty, but omission might also mean “apply the default filter” or “return all results.”
Define these cases deliberately:
- Whether omission means an empty list, no filtering, or an error.
- Whether empty string items are valid.
- Whether duplicate items are retained or rejected.
- Whether item order affects the result.
Avoid treating an empty array as “match nothing” on the client if the server interprets an omitted parameter as “match everything.”
Nested Arrays and Objects
OpenAPI’s deepObject style is intended for simple, non-nested objects. Its behavior for nested objects and arrays is undefined, so it does not provide a portable solution for arbitrary structured query data.
If an endpoint explicitly accepts JSON in a query parameter, serialize and encode it as a single value:
const filters = [
{ field: "status", values: ["active", "pending"] }
];
const params = new URLSearchParams();
params.set("filters", JSON.stringify(filters));
const decoded = JSON.parse(params.get("filters"));
console.log(decoded);
This demonstrates the serialization round trip, not a format every server understands. The receiving endpoint must explicitly JSON-parse the decoded value and validate its structure.
For a new API with complex filters, a documented request body is often easier to implement consistently than nested query conventions.
Large or Sensitive Arrays
There is no universal maximum query-string length that applies across browsers, HTTP servers, proxies, and gateways. The effective limit belongs to the complete request path, so a blanket URL-length recommendation cannot guarantee compatibility.
For large arrays, consider an endpoint designed to accept a JSON request body, often a POST-based search or batch operation. Do not silently move an existing GET endpoint’s parameters into a body and assume it will read them.
Query values can also appear in browser history, server logs, monitoring systems, and copied links. Avoid placing secrets in them. Set application-specific limits on item count and item size, and reject input that exceeds the endpoint’s documented contract.
How to Verify and Troubleshoot Query Arrays
Inspect the outgoing request URL first, then the server’s parsed representation. This identifies whether values were lost during serialization, request handling, or application-level parsing.
| Symptom | Likely Cause | Fix |
|---|---|---|
| The URL has repeated values, but JavaScript reads only the first | Using get() |
Use getAll() for the array parameter |
| The outgoing URL contains only the last item | Calling set() repeatedly |
Call append() once per item |
| The server receives one comma-containing string unexpectedly | Passing an array as a URLSearchParams object-property value |
Append the items individually |
The last issue is easy to miss because this looks like array serialization:
const params = new URLSearchParams({
id: [3, 4, 5]
});
console.log(params.toString());
// id=3%2C4%2C5
In JavaScript, that array is coerced to a single comma-separated string. It does not produce repeated parameters.
Before considering the implementation finished, test:
- An omitted array and an explicitly empty value.
- A single item and multiple items.
- Values containing commas, spaces, ampersands, slashes, and literal plus signs.
- Duplicate items and any order-sensitive behavior.
- Invalid item types and inputs exceeding your application’s limits.
Test through the deployed proxy or gateway as well as directly against the application. Add these cases as integration tests that assert the parsed values and resulting behavior, not just the HTTP status.
Frequently Asked Questions
Is an Array Different From a List in a Query String?
“Array” and “list” usually describe the same collection of values at the API boundary. Their differences matter inside programming languages, but query-string serialization does not choose a language-specific data structure. Use the API’s declared item types and ordering rules regardless of what your language calls the collection.
What Does %20 Mean in a Query String?
%20 is the percent-encoded representation of a space; a plain 20 is simply text representing those digits. Form-style query encoding can also represent a space with +. If a value contains a literal plus sign, encode it as %2B so a form-style decoder does not mistake it for a space.
How Do I Send an Array in Postman?
For an API expecting repeated names, open the request’s Params tab and add a separate enabled row for each value, using the same key each time. For example, enter tag with red in one row and tag with blue in another. Send the request and confirm the server receives both items; use a bracketed or delimited format instead only when the endpoint requires it.
