Query string

When should we use the query string?

If we know the parameters we want to add don't belong in a default header field and aren't sensitive, we can then check if the query string is a good place for it.

So the main use-case that fits the usage of the query string is filtering and two special cases of filtering: searching and pagination.

Parameters that stay the same on all endpoints are better suited for headers. For example authentication tokens get send on every request. Parameters that are highly dynamic, especially when they are only valid for a few or one endpoint should go in the query string. For example filter parameters are different for every endpoint.

When shouldn't we use the query string?

We shouldn't put sensitive data like passwords into the query string.

The developer experience suffers greatly if we don't take URL design and length seriously.

Sometimes it can make sense to use a POST endpoint for heavy parameter usage. This lets us send all the data in the body to the API.

What to do about array parameters inside the query string?

  1. Use square brackets. But the HTTP specification states:

    A host identified by an Internet Protocol literal address, version 6[RFC3513] or later, is distinguished by enclosing the IP literal within square brackets ("[" and "]"). This is the only place where square bracket characters are allowed in the URI syntax.

    /authors?name[]=kay&name[]=xing
  2. Use one parameter name multiple times

    /authors?name=kay&name=xing
  3. Separate the values with ,-characters

    /authors?name=kay,xing
  4. For map-like data-structures, we can use the .-character

    /articles?age.gt=21&age.lt=40

More about it: https://dev.to/moesif/rest-api-design-best-practices-for-parameters-and-query-string-usage-31l6

Last updated

Was this helpful?