Query Parameters
Introduction
Not every API request is used to retrieve one exact resource. In many real projects, clients need to filter data, search records, sort results, paginate large datasets, select specific fields, apply date ranges, choose language preferences, or request a particular view of a collection. Creating a separate endpoint for every possible variation would make the API difficult to maintain. Query parameters solve this problem by letting clients customize a request without changing the main resource path.
For example, suppose an API contains thousands of products. A poorly designed API might create endpoints such as /productsByCategory, /productsByPrice, /productsByBrand, and /productsByColor. This style grows quickly and becomes messy as more filters are added. A cleaner REST design keeps the resource path stable as /products and uses query parameters such as /products?category=Laptop or /products?brand=Dell&sort=price.
Query parameters are key-value pairs added after the question mark in a URL. They usually do not identify one specific resource. Instead, they refine how a collection is returned or how the request should be interpreted. They are commonly optional, although some APIs may require certain query parameters for specific search endpoints or reporting endpoints.
For API testers, query parameters are important because they multiply the number of meaningful test combinations. A collection endpoint may work correctly without filters but fail when filters are combined. Pagination may work on the first page but duplicate records on the second page. Sorting may work alone but fail with search. Invalid query values may cause server errors. A strong API tester understands how to validate query parameters across functional, boundary, security, performance, and authorization scenarios.
What Are Query Parameters?
A query parameter is a key-value pair appended to the end of a URL to modify, filter, search, sort, paginate, or customize the response. Query parameters appear after the ? character in the URL. If there are multiple query parameters, they are separated using the & character.
For example, in /users?country=USA, the resource path is /users, the query parameter name is country, and the value is USA. The request still targets the users collection, but it asks the API to return users that match the country filter.
A simple definition is this: query parameters are key-value pairs added after the question mark in a URL to filter, search, sort, paginate, or customize the response. They are one of the most common tools for making REST collection endpoints flexible.
Query parameters are part of the URL, so they must be encoded correctly when values contain spaces or reserved characters. They should also be validated by the server. A value appearing in the URL should never be trusted simply because it came through a query string.
Query Parameter Syntax
The general syntax for a query parameter is /resource?parameter=value. The question mark marks the beginning of the query string. The parameter name appears before the equals sign, and the parameter value appears after it. A basic example is /users?country=USA.
Multiple query parameters are separated with an ampersand. For example, /users?country=USA&city=Chicago contains two parameters. The first is country=USA, and the second is city=Chicago. The API should interpret both parameters according to its documented rules.
Single query parameter:
GET /users?country=USA
Multiple query parameters:
GET /users?country=USA&city=Chicago
In automation, tools usually handle query parameter construction safely. REST Assured has queryParam. Postman has a Params tab. Karate has the param keyword. Using tool-supported parameter APIs is usually better than manually concatenating strings because the tool can help with encoding and formatting.
URL Structure
Consider the URL https://api.example.com/v1/users?country=USA&page=2. The protocol is https. The host is api.example.com. The Base Path is /v1. The resource path is /users. The query parameters are country=USA and page=2.
| Component | Value | Purpose |
|---|---|---|
| Protocol | https |
Defines secure communication |
| Host | api.example.com |
Identifies the API server or gateway |
| Base Path | /v1 |
Identifies the API version or common route |
| Resource | /users |
Identifies the collection being queried |
| Query parameter | country=USA |
Filters users by country |
| Query parameter | page=2 |
Requests the second page of results |
Breaking the URL into parts helps testers debug failures. If the wrong records are returned, the issue may be in the filter parameter. If pagination fails, the page or size parameter may be wrong. If the request returns 404, the resource path or Base Path may be wrong rather than the query string.
Why Query Parameters Are Needed
Query parameters prevent endpoint explosion. Without them, an API might create many separate endpoints for different filters, such as /usersByCountry, /usersByCity, /usersByAge, and /usersByDepartment. As soon as the client needs users by country and city together, another endpoint would be required. This design does not scale.
With query parameters, one collection endpoint can support many use cases. /users?country=USA filters by country. /users?city=Chicago filters by city. /users?age=25 filters by age. /users?department=QA filters by department. Combined parameters can express richer requests without creating many new routes.
Query parameters also keep APIs more predictable. The resource remains /users, and the query string describes how the client wants to narrow, order, or page that collection. This is easier for consumers than memorizing dozens of specialized endpoint names.
For testers, this means one endpoint may require broad combination testing. The route is stable, but the behavior changes based on query values. Good coverage should include common combinations, invalid combinations, defaults, boundary values, and security cases.
Filtering
Filtering is one of the most common uses of query parameters. A filter narrows a collection to records that match a condition. For example, GET /products?category=Laptop returns laptop products, and GET /employees?department=QA returns employees in the QA department.
Filters can be simple or complex. A simple filter checks one field. A combined filter may check category, brand, price range, availability, and rating. For example, /products?category=Laptop&brand=Dell&available=true asks for Dell laptop products that are currently available.
Testing filters requires more than checking that a response is not empty. Testers should verify that every returned record matches the filter condition. If a country filter is used, all returned users should have that country. If a status filter is used, all returned orders should have that status. If no records match, the API should return a documented empty result response, not an unrelated success payload.
Authorization must still apply. A filter should not allow a caller to access records outside their permitted scope. If a user changes customerId, tenantId, or accountId in the query string, the API must enforce access rules.
Searching
Searching allows clients to find records based on a search term. A simple example is GET /users?name=John. The API may return users whose name exactly matches John, starts with John, or contains John depending on the documented behavior. Search behavior must be defined clearly because different users may expect different matching rules.
Search parameters often raise questions about case sensitivity, partial matching, whitespace handling, special characters, language support, and performance. Should john match John? Should John D match John Doe? Should leading and trailing spaces be ignored? Should accents and localized characters be supported? These rules should be documented and tested.
Search also requires security testing. Search terms are sometimes passed into database queries, search engines, or downstream services. Injection-style values should be handled safely. A search for ' OR 1=1-- should not bypass filters, expose data, or create server errors.
Sorting
Sorting query parameters control the order of returned records. A simple request may be GET /products?sort=price. A descending request may be GET /products?sort=price&order=desc. Some APIs use a compact style such as ?sort=-price to indicate descending order.
Sorting should be documented clearly. The API should specify supported sort fields, default sort order, handling of null values, case sensitivity for text sorting, and behavior when an unsupported sort field is requested. Without clear rules, clients may see unstable ordering between requests.
Testing sorting means verifying actual order, not only status code. If the response is sorted by price ascending, every item should be less than or equal to the next item by price. If sorted by date descending, newer records should appear first. Sorting should also work with pagination because inconsistent sorting can cause records to repeat or disappear across pages.
Pagination
Pagination is essential for large collections. Returning thousands or millions of records in one response is slow, expensive, and risky. Query parameters such as page and size allow clients to request manageable chunks. For example, GET /users?page=2&size=20 requests page 2 with 20 records per page.
Some APIs use offset and limit, such as ?offset=40&limit=20. Others use cursor-based pagination, where the response includes a token for the next page. Cursor pagination is often better for large or frequently changing datasets because it can avoid problems caused by records being inserted or deleted between page requests.
Pagination testing should cover first page, middle page, last page, empty page, page size limits, default page size, invalid page numbers, negative values, zero values, very large values, and combined filtering and sorting. Testers should verify record count, ordering, no duplicates across pages, and correct metadata or next-page links when provided.
Pagination also has performance implications. The API should enforce maximum page size. A request such as ?size=1000000 should not be allowed to overload the server. Tests should verify that limits are enforced and that error responses are clear.
Date Range Parameters
Date range parameters are common in transaction, order, reporting, billing, and audit APIs. A request such as GET /orders?from=2025-01-01&to=2025-12-31 asks for orders within a date range. The parameter names may vary, using startDate, endDate, from, to, createdAfter, or createdBefore.
Date range behavior should be precise. The API should define date format, timezone handling, inclusive or exclusive boundaries, invalid ranges, future dates, and default values. If from and to are dates without times, the API should clarify whether the full day is included. Timezone ambiguity can create difficult defects in global systems.
Testers should validate valid ranges, missing start date, missing end date, start date after end date, invalid date formats, leap years, month boundaries, timezone-sensitive values, and empty result ranges. Date parameters are easy to underestimate, but they often reveal production issues.
Field Selection
Some APIs allow clients to request only selected fields through a query parameter such as fields. For example, GET /users?fields=id,name,email may return only ID, name, and email. This can reduce payload size and avoid over-fetching when clients need limited data.
Field selection must be controlled. Clients should not be able to request sensitive internal fields simply by naming them. If a user asks for passwordHash, secretKey, or internalToken, the API must reject or ignore those fields according to the contract. Field-level authorization may also be required when different roles can see different fields.
Tests should verify valid field selections, unknown fields, duplicate fields, empty fields, sensitive fields, role-restricted fields, and combinations with filters or pagination. The response should include only allowed requested fields plus any mandatory metadata defined by the API.
Localization Parameters
Localization query parameters allow clients to request language, region, currency, or formatting preferences. Examples include GET /products?language=en, GET /products?currency=USD, or GET /content?locale=en-US. These parameters are common in e-commerce, learning platforms, travel, finance, and content systems.
Localization testing should verify supported values, unsupported values, defaults, fallback behavior, currency formatting, translated text, number formats, date formats, and regional availability. If the API returns prices, testers should verify that currency conversion or currency display follows the product rules. If the API returns content, language fallback should be predictable.
Query Parameters vs Path Parameters
Query parameters and path parameters serve different purposes. A path parameter identifies a specific resource. A query parameter filters or customizes the result. /users/101 points to one specific user. /users?country=USA points to the users collection filtered by country.
| Concept | Path Parameter | Query Parameter |
|---|---|---|
| Purpose | Identifies a specific resource | Filters, sorts, searches, paginates, or customizes |
| Required | Usually required for the route | Usually optional |
| Location | Inside the URL path | After the question mark |
| Example | /users/101 |
/users?country=USA |
A practical rule is this: use a path parameter when the value identifies the resource itself. Use a query parameter when the value changes how a resource collection is returned. Misusing query parameters for resource identity can make endpoint design less clear.
Multiple Query Parameters
Multiple query parameters allow clients to combine filters and request controls. For example, GET /products?category=Laptop&brand=Dell&sort=price&page=1 means the client wants Dell laptop products, sorted by price, from the first page of results. This is more flexible than creating a separate endpoint for every combination.
Combination testing is important because parameters may interact. Category may work alone, brand may work alone, and sorting may work alone, but category plus brand plus sorting plus pagination may reveal defects. The API should apply filters consistently and in a documented way.
Duplicate parameters should also be tested. A request such as /users?country=USA&country=Canada may be interpreted as multiple values, the first value, the last value, or an invalid request depending on the framework and API contract. The behavior should be documented and tested because different platforms handle duplicates differently.
REST Assured Example
REST Assured supports query parameters through queryParam. This is cleaner than manually building query strings. For example:
given()
.queryParam("country", "USA")
.queryParam("page", 2)
.when()
.get("/users")
.then()
.statusCode(200);
The actual request becomes GET /users?country=USA&page=2. REST Assured handles parameter placement and encoding more safely than string concatenation in most cases.
In reusable frameworks, query parameters can be built from maps or request objects. This is useful when filters are optional. A helper can add only parameters that are present, preventing empty or null values from being sent unintentionally. Tests should still verify empty values deliberately where that behavior matters.
Postman Example
In Postman, query parameters can be entered in the Params tab. A request URL may be {{baseUrl}}/users, and the Params tab may contain country=USA and page=2. Postman builds the final URL as GET /users?country=USA&page=2.
This is easier to maintain than typing the full query string manually. It also makes parameters visible as separate rows, which helps testers enable, disable, and modify values during exploratory testing. Variables can be used for parameter values, such as {{country}} or {{pageNumber}}.
When exporting Postman collections or running them with Newman, query parameters remain part of the request definition. Environment variables can make the same collection reusable across QA, staging, and production-like environments.
Karate Example
Karate supports query parameters using the param keyword. A simple test may look like this:
Given path 'users'
And param country = 'USA'
And param page = 2
When method GET
Then status 200
The actual request becomes GET /users?country=USA&page=2. Karate keeps the path and parameters separate, which improves readability and reduces mistakes with question marks and ampersands.
Karate also supports dynamic values and data-driven tests. This makes it useful for testing multiple filter combinations, pagination boundaries, invalid values, and search scenarios with readable feature files.
Query Parameters in API Testing
API testers should validate query parameters across positive and negative scenarios. A valid request such as GET /users?country=USA should return only users from the USA. If the API returns users from other countries, the filter is not applied correctly. The test should verify the actual content, not only that the status code is 200.
Invalid parameter values should be tested. GET /users?country=INVALID may return an empty result set with 200 OK, or it may return 400 Bad Request if the API validates country against an allowed list. Both approaches can be valid if documented. What matters is consistency and clarity.
Missing optional parameters should verify default behavior. GET /users may return all users, a default page, active users only, or a permission-filtered collection depending on the API contract. Testers should know the default and validate it explicitly.
Empty parameters should be tested separately. /users?country= is not always the same as omitting country. The API may treat it as invalid, empty filter, or default behavior. Ambiguous handling can create defects, especially when frontend forms submit blank values.
URL Encoding
Query parameter values must be URL-encoded when they contain spaces or reserved characters. For example, /users?name=John Doe should be encoded as /users?name=John%20Doe or built through a tool that encodes values safely. Reserved characters such as spaces, ampersands, equals signs, slashes, question marks, and percent symbols can change the meaning of the query string if not encoded.
Encoding bugs are common in search, names, addresses, product titles, and free-text fields. A value such as R&D can be misread as a new parameter if the ampersand is not encoded. A value containing = can confuse parsing if handled manually. Tools generally help, but test data should include real-world special characters.
Testers should validate encoded spaces, ampersands, plus signs, percent signs, Unicode characters where supported, and reserved characters. They should also verify that the server decodes values correctly and applies the intended filter or search behavior.
Authorization and Security
Query parameters can affect authorization and security. A user may try to change customerId, accountId, tenantId, role, or department parameters to access data they should not see. The API must enforce authorization regardless of the query string.
Security testing should include injection-style values such as SQL fragments, script-like input, very long strings, encoded payloads, and unexpected characters. The API should reject or safely handle malicious input without returning server errors, stack traces, SQL messages, or unauthorized data.
Pagination and size parameters also have security and performance impact. A very large page size can overload the server if not limited. Search parameters can trigger expensive queries. Sorting by unsupported internal fields can reveal implementation details or create slow queries. Good APIs validate query parameters before using them.
Query Parameter Validation Checklist
A practical query parameter checklist includes valid values, invalid values, missing parameters, empty values, default behavior, multiple parameters, duplicate parameters, URL encoding, boundary values, pagination, sorting, filtering, searching, authorization, and security against injection attacks. High-risk endpoints should receive broad coverage because query combinations can hide subtle defects.
Boundary tests are especially important for numeric parameters. Page numbers, page sizes, min and max prices, ages, limits, offsets, and date ranges should be tested around their boundaries. Negative values, zero, extremely large values, decimals where integers are expected, and non-numeric strings should be handled safely.
Combination tests should focus on business-relevant combinations rather than every possible permutation. For example, category plus brand plus price range plus sort may be important for products. Status plus date range plus pagination may be important for transactions. The goal is meaningful coverage, not brute-force noise.
Common Mistakes
A common mistake is using query parameters to identify one exact resource. /users?id=101 can work technically, but /users/101 is usually clearer for retrieving a specific user in REST. Query parameters are better suited for collection refinement, such as /users?city=Chicago.
Another mistake is creating separate endpoints for every filter. Paths such as /usersByCountry, /usersByCity, and /usersByAge lead to endpoint explosion. A better design is /users?country=USA, /users?city=Chicago, and /users?age=25.
Poor parameter names also create confusion. A query such as /users?a=USA is less readable than /users?country=USA. Parameter names should express business meaning. Short names may save characters, but they cost readability and increase documentation burden.
Ignoring URL encoding is another common issue. Spaces and reserved characters must be encoded properly. Manual string concatenation often causes subtle bugs. Framework-supported query parameter APIs are safer and clearer.
Best Practices
Use query parameters for filtering, searching, sorting, pagination, field selection, date ranges, localization, and other optional request customizations. Keep the resource path stable and let query parameters refine the result. This makes APIs more flexible and easier to maintain.
Use meaningful parameter names such as country, status, page, size, sort, from, to, fields, and locale. Avoid vague names unless they are widely understood within the API contract. Document supported values, default behavior, data types, allowed ranges, and error responses.
Validate all parameter values on the server. Do not trust query strings. Enforce maximum page sizes, allowed sort fields, valid date formats, supported filters, and authorization rules. Return clear error messages for invalid input. Avoid leaking implementation details in error responses.
Use URL encoding for special characters and rely on framework-supported parameter builders where possible. In automation, avoid manually concatenating long query strings unless there is a specific reason. Clear parameter construction improves test readability and reduces failures caused by formatting mistakes.
Real-World Examples
An e-commerce API may use GET /products?category=Laptop&brand=Dell to return Dell laptops. A banking API may use GET /transactions?from=2025-01-01&to=2025-12-31 to retrieve transactions within a date range. A streaming platform may use GET /movies?genre=Comedy&language=English to filter movies by genre and language.
A code hosting API may use GET /repositories?language=Java&sort=stars to return popular Java repositories. A learning platform may use GET /courses?level=beginner&sort=popularity. A ticketing system may use GET /tickets?status=open&priority=high&page=1.
These examples show why query parameters are so common. They allow one collection endpoint to serve many practical client needs without creating separate routes for every variation.
Interview Questions
A common interview question is: what are query parameters? A strong answer is that query parameters are key-value pairs added after the question mark in a URL to filter, search, sort, paginate, or customize the response. In /users?country=USA&page=2, country and page are query parameters.
Another common question is when query parameters should be used. They should be used for filtering, searching, sorting, pagination, field selection, date ranges, localization, and similar optional request customizations. They should generally not be used to identify one specific resource when a path parameter would be clearer.
Interviewers may ask the difference between path parameters and query parameters. Path parameters identify specific resources and are part of the URL path. Query parameters refine or customize the result and appear after the question mark.
A testing-focused answer should mention valid values, invalid values, missing values, empty values, duplicate parameters, URL encoding, boundaries, sorting, pagination, authorization, and injection attacks.
Interview-Ready Explanation
Query parameters are optional key-value pairs appended to the end of a URL after the ? character. They are used to modify or customize a request by filtering, searching, sorting, paginating, selecting fields, applying date ranges, or specifying localization options. Multiple query parameters are separated using the & character.
Unlike path parameters, which identify a specific resource, query parameters refine how a collection of resources is returned. For example, GET /users/101 uses a path parameter to identify one user, while GET /users?country=USA&page=2 uses query parameters to retrieve the second page of users from the USA.
In API testing, query parameters should be validated for correct filtering, searching, sorting, pagination, default behavior, invalid input, empty values, duplicate parameters, URL encoding, boundary values, authorization rules, and security attacks. Good query parameter design makes APIs flexible without creating too many endpoints, while good testing ensures those flexible combinations behave safely and predictably.
Key Takeaway
Query parameters are the flexible part of REST collection endpoints. They let clients ask for filtered, searched, sorted, paginated, localized, or reduced data without changing the main resource path. They prevent endpoint explosion and make APIs easier to grow.
The practical rule is simple: use query parameters to refine collections and path parameters to identify specific resources. Keep parameter names meaningful, document behavior clearly, validate values on the server, encode special characters, enforce authorization, and test realistic parameter combinations. Strong query parameter testing turns a simple endpoint check into real API quality assurance.