DEV Community

Cover image for REST API Design Best Practices for Parameters and Query String Usage

REST API Design Best Practices for Parameters and Query String Usage

K on May 06, 2019

Cover image by Edwin Young, on Flickr. When we are designing APIs the goal is to give our users some amount of power over the service we provide. ...
Collapse
 
connor4312 profile image
Connor Peet • Edited

If such a parameter should go into a custom header or the query string is mostly a question of developer experience.

I tend to favor query strings for a few reasons. Aside from the theological beliefs, a few of the reasons are concrete or footgun-avoidance :)

  • If your API is or can be called cross-domain, adding a custom header will require browsers to do a CORS preflight check where they might have been able to omit it before--making requests to your API slower!
  • Also, if you're cross-origin, you need to remember to add the header to your Access-Control-Allow-Headers as appropriate.
  • If you want your endpoint to be cached, you also need to remember to add the new header in the Vary headers in your response.
  • Query strings generally show up better by default in your logging and analytic tools.
Collapse
 
mert profile image
Mert Yazıcıoğlu

If your API is or can be called cross-domain, adding a custom header will require browsers to do a CORS preflight check where they might have been able to omit it before--making requests to your API slower!

Although that’s technically true, you’ll most likely trigger the CORS preflight check anyway due to the Content-Type as it’s quite unlikely you’ll be using one of the plain-text or form data types.

Collapse
 
conaltuohy profile image
Conal Tuohy

I don't really see the point of your criticism of the practice of having multiple URI parameters with the same name. You point out that some developers might add parameters to an overly simplistic data structure like a map, before encoding the map as URI parameters, and that they might lose data that way unless they used a more complex procedure to build the URI. That's certainly true, but it would be a silly mistake to make, and the alternative you suggest, of encoding multiple parameter values as a comma-separated string, is no less complex.

Collapse
 
kayis profile image
K • Edited

I just had a common JavaScript data structure in mind.

const filters = {
  limit: 25,
  afterDate: Date.now(),
  names: ["Kay", "Xing", "Derric"]
}

But you are probably right, doing filters.names.join(",") isn't much simpler than filters.names.map(n => "name=" + n).join("&").