REST API Best practices: Where to put parameters?

Kalle Gustafsson picture Kalle Gustafsson · Oct 26, 2010 · Viewed 805.6k times · Source

A REST API can have parameters in at least two ways:

  1. As part of the URL-path (i.e. /api/resource/parametervalue )
  2. As a query argument (i.e. /api/resource?parameter=value )

What is the best practice here? Are there any general guidelines when to use 1 and when to use 2?

Real world example: Twitter uses query parameters for specifying intervals. (http://api.twitter.com/1/statuses/home_timeline.json?since_id=12345&max_id=54321)

Would it be considered better design to put these parameters in the URL path?

Answer

Darrel Miller picture Darrel Miller · Oct 27, 2010

If there are documented best practices, I have not found them yet. However, here are a few guidelines I use when determining where to put parameters in an url:

Optional parameters tend to be easier to put in the query string.

If you want to return a 404 error when the parameter value does not correspond to an existing resource then I would tend towards a path segment parameter. e.g. /customer/232 where 232 is not a valid customer id.

If however you want to return an empty list then when the parameter is not found then I suggest using query string parameters. e.g. /contacts?name=dave

If a parameter affects an entire subtree of your URI space then use a path segment. e.g. a language parameter /en/document/foo.txt versus /document/foo.txt?language=en

I prefer unique identifiers to be in a path segment rather than a query parameter.

The official rules for URIs are found in this RFC spec here. There is also another very useful RFC spec here that defines rules for parameterizing URIs.