API Keys
Some APIs use API keys for authorization. An API key is a token that a client provides when making API calls. The key can be sent in the query string:
or as a request header:
or as a cookie:
API keys are supposed to be a secret that only the client and server know. Like Basic authentication, API key-based authentication is only considered secure if used together with other security mechanisms such as HTTPS/SSL.
Describing API Keys
In OpenAPI 3.0, API keys are described as follows:
This example defines an API key named X-API-Key
sent as a request header X-API-Key: <key>
. The key name ApiKeyAuth is an arbitrary name for the security scheme (not to be confused with the API key name, which is specified by the name
key). The name ApiKeyAuth is used again in the security
section to apply this security scheme to the API. Note: The securitySchemes
section alone is not enough; you must also use security
for the API key to have effect. security
can also be set on the operation level instead of globally. This is useful if just a subset of the operations need the API key:
Note that it is possible to support multiple authorization types in an API. See Using Multiple Authentication Types.
Multiple API Keys
Some APIs use a pair of security keys, say, API Key and App ID. To specify that the keys are used together (as in logical AND), list them in the same array item in the security
array:
Note the difference from:
which means either key can be used (as in logical OR). For more examples, see Using Multiple Authentication Types.
401 Response
You can define the 401 “Unauthorized” response returned for requests with missing or invalid API key. This response includes the WWW-Authenticate
header, which you may want to mention. As with other common responses, the 401 response can be defined in the global components/responses
section and referenced elsewhere via $ref
.
To learn more about describing responses, see Describing Responses.
Did not find what you were looking for? Ask the community
Found a mistake? Let us know