Search code examples
c#restasp.net-web-apiroutesapi-design

Commonly used Web API parameters - route vs header?


I'm looking for best way of passing a common parameter between pretty much all of my web API methods. The parameter in this case is a repository identifier as there is a choice on login into the SPA over which database is to be used to read and write data from/to. This choice is then stored in the app and used in all future API calls.

The choices I'm considering are:

  1. Route value - this means adding a route parameter to all of the routes and ensuring it's sent for each call the SPA makes: [Route("api/{repo}/{user}/{id}")]. The advantage here is it's maybe more explicit.
  2. Custom header value which is applied blindly by the app on every API request and used by the API whenever required. It is therefore a requirement that this header is passed. The advantage here is there's a separation of concern - the part of the SPA managing the users screen doesn't need to know which repo it's working with.

Are there any best practise guidelines for parameters that are commonly used in an API? Where's the distinction over when parameters should be passed FromUri and FromBody over using custom header values?


Solution

  • It depends on the situation but if you have made APIs in which every time you need to pass certain parameter then better you send this parameter in header. HTTP header meant to send extra information about request context, but be aware of adding too much header key-value.

    Through header and querystring (through URL) you can only send data in key-value pair whereas through HTTP body you can send different types of payload (data) i.e. JSON, XML, txt, FileStream etc.

    There are certain limitations on the data size based on which methods choose to send data. Through header you can pass data up to 8KB size for each key-value pair, in querystring you can add up to 2048 chars and through body we can send as much as 0 to >= 2 MB of data (Size may vary from server to server).

    For more detail please refer RFC 7231