API Key Management – In Content or Header?

api

Working on an API at the moment and just wanted to gather opinions on where the best place to transmit the API key should be. I know that is shouldn't go in the URL, this leaves the request header or the message body.

If I put it in the header I can come up with a generic method for pulling it out that can be used across all services, however the spec I've been handed wants it in the body (ie in a JSON string included as part of the serialized object in the POST body).

Best Answer

In HTTP, there is a Authorization header for that.

While it is usually used to provide users' credentials, in a case of an API, it can contain the ID of the client and the corresponding API key.

There are several benefits:

  • Support from different frameworks. Many frameworks will expect Authorization header in order to do authentication. Not using it will force to write additional code to feed those frameworks with custom values.

  • Support from different tools. For instance CURL.

  • Less “WTF where do I find/put this API key?!” from new developers joining the team (or developers designing new clients for your API).

  • You can then use HTTP status code definitions such as 401 Unauthorized, for which:

    The response MUST include a WWW-Authenticate header field [...] The client MAY repeat the request with a suitable Authorization header field.

Moving it to the body of the request can become quickly painful. Most frameworks and tools don't make it very straightforward to add a body to a request, which may make your API more difficult than it needs to be.

Related Topic