Skip to content

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:

1
GET /something HTTP/1.1
2
X-API-Key: abcdef12345

or as a query parameter:

1
GET /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 global securityDefinitions 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 or in: query.
  • Specify a name for that parameter or header.
1
securityDefinitions:
2
# X-API-Key: abcdef12345
3
APIKeyHeader:
4
type: apiKey
5
in: header
6
name: X-API-Key
7
# /path?api_key=abcdef12345
8
APIKeyQueryParam:
9
type: apiKey
10
in: query
11
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):
2
security:
3
- APIKeyHeader: []
4
paths:
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:

1
securityDefinitions:
2
apiKey:
3
type: apiKey
4
in: header
5
name: X-API-KEY
6
appId:
7
type: apiKey
8
in: header
9
name: X-APP-ID
10
security:
11
- apiKey: []
12
appId: []

Note the difference from:

1
security:
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.

1
paths:
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'
15
responses:
16
UnauthorizedError:
17
description: API key is missing or invalid
18
headers:
19
WWW_Authenticate:
20
type: string

Did not find what you were looking for? Ask the community
Found a mistake? Let us know