Defining the use of API Key in OpenAPI Specification
To be able to use API Keys for authentication, you first need to define in the API's OpenAPI Specification that the API Key authentication should be used.
The use of API Keys is defined in OpenAPI Specifications with the Security Scheme Object (securitySchemes).
Example:
components: securitySchemes: ApiKeyAuth: type: apiKey name: x-api-key in: header
This is a very typical way to setup API Key authentication. With this configuration, the API Key's name is x-api-key and it needs to be sent in the HTTP headers by the API client.
For details on API Key configuration options and further examples, see the Security Schemes Object documentation.
Defining with which API operations the configured API Key is used
In addition to having the Security Schemes Object for API Key authentication defined, you also need to specify which API operations the defined security scheme should be applied to.
In this example, we have added the Security Requirement Object (security) object after the Components object and defined the ApiKeyAuth security scheme to apply to all API operations defined in this OpenAPI Specification.
The added Security Requirement Object (security) is marked with bold font:
components: securitySchemes: ApiKeyAuth: type: apiKey name: x-api-key in: header security: - ApiKeyAuth: [ ]
For more information and examples, see the Security Requirement Object documentation.
Complete OpenAPI example of simple API with API Key authentication configured globally for all API operations
openapi: 3.0.1 info: title: Weather API description: API providing weather information version: 1.0.0 servers: - url: /api/weather/v1 paths: /weathernow: get: parameters: - name: city in: query description: City for which you want to get weather information required: true schema: type: string responses: '200': description: ok content: application/text: schema: type: string components: securitySchemes: ApiKeyAuth: type: apiKey name: x-api-key in: header security: - ApiKeyAuth: [ ]
The next article is Example on Typical API use case scenario