OpenAPI: API Key Header Authentication

Document API key authentication using a custom header (X-API-Key). Includes security scheme definition, key validation responses, and usage examples.

Authentication

Detailed Explanation

Documenting API Key Authentication in OpenAPI

API key authentication is simpler than JWT or OAuth2 and is commonly used for server-to-server communication, public APIs with rate limiting, and developer portals.

Security Scheme Definition

components:
  securitySchemes:
    ApiKeyAuth:
      type: apiKey
      in: header
      name: X-API-Key
      description: API key provided by the developer portal

OpenAPI supports three locations for API keys: header, query, and cookie. Header-based is the most secure as it avoids keys appearing in URLs and server logs.

Applying API Key Security

security:
  - ApiKeyAuth: []

paths:
  /data/export:
    get:
      summary: Export data
      security:
        - ApiKeyAuth: []
      responses:
        '200':
          description: Data exported successfully
        '401':
          description: Missing or invalid API key
        '403':
          description: API key does not have permission
        '429':
          description: Rate limit exceeded

Error Responses for API Key Auth

Document the specific error responses clients will encounter:

Status When
401 API key header is missing or the key is invalid/expired
403 Key is valid but lacks permission for the requested resource
429 Key has exceeded its rate limit allocation

Key Rotation Considerations

In your API description, document whether keys can be regenerated, whether old keys have a grace period, and how clients should handle key expiration. This information helps consumers integrate correctly even though it is not formally part of the OpenAPI spec.

Multiple Authentication Options

You can offer both API key and Bearer token auth by listing them as alternatives in the security array. This lets internal services use API keys while user-facing clients use JWT tokens.

Use Case

Building a public API or developer platform where external developers register for API keys through a portal and use them to access rate-limited endpoints. Common in SaaS platforms, data providers, and payment gateways.

Try It — API Documentation Generator

Open full tool