API Key Authentication in OpenAPI
Document API key authentication in OpenAPI 3.0 specs. Learn to define API keys in headers, query parameters, or cookies with security schemes and per-operation overrides.
Detailed Explanation
API Key Authentication in OpenAPI
API key authentication is a simple, widely used method where clients include a secret key in each request. OpenAPI supports documenting API keys sent via headers, query parameters, or cookies.
Header-Based API Key
The most common pattern — a custom header:
components:
securitySchemes:
apiKeyHeader:
type: apiKey
in: header
name: X-API-Key
description: API key provided during registration
Client usage: X-API-Key: sk_live_abc123...
Query Parameter API Key
Less secure but sometimes used for simplicity:
components:
securitySchemes:
apiKeyQuery:
type: apiKey
in: query
name: api_key
Client usage: GET /data?api_key=sk_live_abc123
Cookie-Based API Key
Used in browser-based applications:
components:
securitySchemes:
apiKeyCookie:
type: apiKey
in: cookie
name: session_token
Applying API Key Security
Apply globally or per-endpoint:
# Global — all endpoints require API key
security:
- apiKeyHeader: []
paths:
/public/health:
get:
security: [] # Override: no auth needed
summary: Health check
/data:
get:
summary: Get data (uses global security)
Combining API Key with Other Auth
Support multiple authentication options:
components:
securitySchemes:
apiKey:
type: apiKey
in: header
name: X-API-Key
bearerAuth:
type: http
scheme: bearer
# Client can use EITHER method
security:
- apiKey: []
- bearerAuth: []
Rate Limiting Documentation
While OpenAPI does not have built-in rate limiting syntax, you can document it in the description:
components:
securitySchemes:
apiKey:
type: apiKey
in: header
name: X-API-Key
description: |
API key for authentication.
Rate limits: 100 requests/minute for free tier,
1000 requests/minute for pro tier.
Rate limit headers: X-RateLimit-Remaining,
X-RateLimit-Reset
Security Best Practices
- Always use HTTPS (document
serverswithhttps://) - Prefer header-based keys over query parameters (URLs are logged)
- Include API key rotation guidance in the description
- Document different key types (test/live) if applicable
Use Case
API key authentication is the standard for public APIs, SaaS platforms, and developer-facing services. Companies like Stripe, Twilio, and SendGrid use API keys as their primary authentication method. Documenting the key location (header vs. query), naming convention, and rate limits in the OpenAPI spec enables accurate SDK generation and clear developer documentation.