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.