API Keys
Some APIs use API keys for authorization. An API key is a special token that the client needs to provide when making API calls. The key is usually sent as a request header:
1GET /something HTTP/1.12X-API-Key: abcdef12345
or as a query parameter:
1GET /something?api_key=abcdef12345
API keys are supposed to be a secret that only the client and server know. But, as well as Basic authentication, API key-based authentication is not considered secure unless used together with other security mechanisms such as HTTPS/SSL.
To define API key-based security:
- Add an entry with
type: apiKey
in the globalsecurityDefinitions
section. The entry name can be arbitrary (such as APIKeyHeader in the example below) and is used to refer to this security definition from other parts of the spec. - Specify whether the API key will be passed
in: header
orin: query
. - Specify a
name
for that parameter or header.
1securityDefinitions:2 # X-API-Key: abcdef123453 APIKeyHeader:4 type: apiKey5 in: header6 name: X-API-Key7 # /path?api_key=abcdef123458 APIKeyQueryParam:9 type: apiKey10 in: query11 name: api_key
Then, use the security
section on the root level or operation level to apply API keys to the whole API or specific operations.
1# Global security (applies to all operations):2security:3 - APIKeyHeader: []4paths:5 /something:6 get:7 # Operation-specific security:8 security:9 - APIKeyQueryParam: []10 responses:11 200:12 description: OK (successfully authenticated)
Note that it is possible to support multiple authorization types in an API. See Using Multiple Authentication Types.
Pair of 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:
1securityDefinitions:2 apiKey:3 type: apiKey4 in: header5 name: X-API-KEY6 appId:7 type: apiKey8 in: header9 name: X-APP-ID10security:11 - apiKey: []12 appId: []
Note the difference from:
1security:2 - apiKey: []3 - appId: []
which means either key can be used (as in logical OR). For more examples, see Using Multiple Authentication Types.
401 Response
You can also 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 responses
section and referenced from multiple operations.
1paths:2 /something:3 get:4 ...5 responses:6 ...7 401:8 $ref: '#/responses/UnauthorizedError'9 post:10 ...11 responses:12 ...13 401:14 $ref: '#/responses/UnauthorizedError'15responses:16 UnauthorizedError:17 description: API key is missing or invalid18 headers:19 WWW_Authenticate:20 type: string
Did not find what you were looking for? Ask the community
Found a mistake? Let us know