A knowledge guide: what parts an OpenAPI 3 contract has and how to declare in it a very common type of security in enterprise APIs: an OAuth 2.0 Client Credentials token obtained with a Client ID and Client Secret, plus an API Key that identifies the consumer’s subscription. The complete contract and the commands are also in the README.md on the left.
What you’ll learn
- What parts an OpenAPI 3 contract has and what each one is for.
- How to reuse models, parameters and responses with
componentsand$ref. - How security is declared: defining the schemes and requiring them, and the difference between AND and OR.
- How OAuth 2.0 Client Credentials works with a Client ID and Client Secret.
- What an API Key adds and why it is combined with the token rather than replacing it.
- How a consumer requests the token and calls the API, and how to validate the contract.
Prerequisites
- Know the basics of HTTP and REST: methods, headers, status codes and JSON.
- An editor with YAML support, for example Visual Studio Code with an OpenAPI extension.
- Node.js, only to validate the contract in the last step (optional).
- To test it for real: access to an authorisation server (for example, Microsoft Entra ID) with a registered application (optional).
Step by step
1. Understand what a contract is and why to write it first
OpenAPI is the standard for describing a REST API in a YAML or JSON file: what paths it has, what each one receives and returns, what errors it gives and how it authenticates. That file is the contract between whoever publishes the API and whoever consumes it.
Writing it before the code (contract first) lets frontend, backend and partners work in parallel, generate documentation and clients automatically, validate requests at the API Gateway and detect breaking changes before they are published.
2. Set up the skeleton of the document
| Field | What it’s for |
|---|---|
openapi | Version of the specification: 3.0.3 or 3.1.0. Required. |
info | Title, API version, description and contact. Required. |
servers | Base URL of each environment (production, pre-production…). |
paths | The paths and their operations (GET, POST…), with parameters, body and responses. |
components | Reusable pieces: data schemas, parameters, responses and security schemes. |
security | The security applied by default to every operation. |
tags | Group the operations in the documentation. |
The minimum skeleton of a valid contract:
openapi: 3.0.3
info:
title: Orders API
version: 1.0.0
servers:
- url: https://api.example.com/orders/v1
paths: {}
components: {}
3. Describe the paths and operations
Each path in paths has its operations (get, post…). Give each one a unique operationId (code generators use it as the method name) and document all its responses:
paths:
/orders:
get:
tags: [Orders]
operationId: listOrders
summary: Lists the orders
responses:
'200':
description: List of orders
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Order'
4. Reuse components
Anything that repeats is defined once in components and referenced with $ref. If the order model changes, it changes in every operation at once.
schemas: the data models (an order, an error), with types, required fields, formats and examples.parameters: common parameters, such as pagination.responses: repeated responses, such as the 401 and 403 errors.securitySchemes: the security mechanisms the API uses.
5. Define the security schemes
First you define the mechanisms in components.securitySchemes: here, OAuth 2.0 with the Client Credentials flow (with the token URL and the available scopes) and an API Key in a header.
components:
securitySchemes:
oauth2:
type: oauth2
description: OAuth 2.0 Client Credentials (application to application)
flows:
clientCredentials:
tokenUrl: https://login.example.com/oauth2/token
scopes:
orders.read: Read orders
orders.write: Create orders
apiKey:
type: apiKey
in: header
name: X-API-Key
description: Identifies the consumer's subscription (quotas and analytics)
6. Require the security: AND versus OR
Then you require them with security: at the root of the document, for every operation, or in a specific operation, which then replaces the root one.
# At the root: every operation requires a token AND an API Key
security:
- oauth2: [orders.read]
apiKey: []
paths:
/orders:
post:
# In an operation: replaces the root one (the API Key must be repeated)
security:
- oauth2: [orders.write]
apiKey: []
How you write it decides whether both mechanisms are needed or one is enough:
# AND: token AND API Key (both in the same list item)
security:
- oauth2: [orders.read]
apiKey: []
# OR: token OR API Key (each in its own list item)
security:
- oauth2: [orders.read]
- apiKey: []
7. Understand the Client Credentials flow
It is the flow for communication between applications, with no user involved: a backend, a batch process or a partner’s platform. Each consuming application is registered with the authorisation server and receives two values:
- Client ID: identifies the application. It is not secret.
- Client Secret: proves that the application is who it claims to be. It is a password: it never goes in the code, in the contract or in the browser; it is kept in a secrets manager (Azure Key Vault, for example) or in environment variables.
How it works:
- The application requests a token from the
tokenUrlwith its Client ID, its Client Secret and the scopes it needs. - The authorisation server checks the credentials and returns an access token with an expiry (for example, one hour).
- The application calls the API with the token in
Authorization: Bearer …. - The API Gateway validates the token (signature, expiry, audience and scopes) before letting the request through.
- When the token expires, the application requests another one: this flow has no refresh token.
The token request and its response:
POST /oauth2/token HTTP/1.1
Host: login.example.com
Authorization: Basic base64(client_id:client_secret)
Content-Type: application/x-www-form-urlencoded
grant_type=client_credentials&scope=orders.read
{
"access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...",
"token_type": "Bearer",
"expires_in": 3600
}
With Microsoft Entra ID, for example, the tokenUrl is https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token and the scope is requested as api://{api-id}/.default.
8. Understand what the API Key adds
The API Key identifies the consumer’s subscription: it is used to apply quotas and rate limits, for usage analytics and to revoke a specific consumer’s access without touching the authorisation server. In Azure API Management, for example, it is the subscription key, which by default travels in the Ocp-Apim-Subscription-Key header.
What it doesn’t provide is strong authentication: it is a fixed value, it doesn’t expire on its own and it carries no scopes. That is why it is combined with the token and doesn’t replace it: the token says who the caller is and what it can do; the API Key, which subscription it comes in through and with what quota.
9. Document the 401 and 403 errors
| Code | Meaning | Example |
|---|---|---|
| 401 Unauthorized | The caller is unknown, or its credentials are not valid. | The token or the API Key is missing, the token has expired or the signature is not valid. |
| 403 Forbidden | The caller is known, but doesn’t have permission for that operation. | The token only has orders.read and tries to create an order. |
Documenting them in components.responses, with the same error schema, helps the consumer know whether to request a new token (401) or ask for more permissions (403).
10. Review the complete contract
An orders API that requires a token and an API Key on every operation, with a read scope by default and a write scope for creating orders. You also have it in the README.md on the left:
openapi: 3.0.3
info:
title: Orders API
version: 1.0.0
description: >
Retrieval and creation of orders. Every request needs an OAuth 2.0 token
(Client Credentials) and the API Key of the consumer's subscription.
contact:
name: Integration team
email: integration@example.com
servers:
- url: https://api.example.com/orders/v1
description: Production
- url: https://api-pre.example.com/orders/v1
description: Pre-production
tags:
- name: Orders
security:
- oauth2: [orders.read]
apiKey: []
paths:
/orders:
get:
tags: [Orders]
operationId: listOrders
summary: Lists the orders
parameters:
- $ref: '#/components/parameters/Page'
responses:
'200':
description: List of orders
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Order'
'401':
$ref: '#/components/responses/Unauthenticated'
'403':
$ref: '#/components/responses/Forbidden'
post:
tags: [Orders]
operationId: createOrder
summary: Creates an order
security:
- oauth2: [orders.write]
apiKey: []
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/NewOrder'
responses:
'201':
description: Order created
content:
application/json:
schema:
$ref: '#/components/schemas/Order'
'400':
$ref: '#/components/responses/Invalid'
'401':
$ref: '#/components/responses/Unauthenticated'
'403':
$ref: '#/components/responses/Forbidden'
/orders/{orderId}:
get:
tags: [Orders]
operationId: getOrder
summary: Retrieves an order
parameters:
- name: orderId
in: path
required: true
schema:
type: string
responses:
'200':
description: The order
content:
application/json:
schema:
$ref: '#/components/schemas/Order'
'401':
$ref: '#/components/responses/Unauthenticated'
'404':
description: No order exists with that identifier
components:
securitySchemes:
oauth2:
type: oauth2
flows:
clientCredentials:
tokenUrl: https://login.example.com/oauth2/token
scopes:
orders.read: Read orders
orders.write: Create orders
apiKey:
type: apiKey
in: header
name: X-API-Key
parameters:
Page:
name: page
in: query
schema:
type: integer
minimum: 1
default: 1
schemas:
NewOrder:
type: object
required: [customer, amount]
properties:
customer:
type: string
example: CUS-0042
amount:
type: number
format: double
minimum: 0
example: 129.90
Order:
allOf:
- $ref: '#/components/schemas/NewOrder'
- type: object
required: [id, status]
properties:
id:
type: string
example: ORD-2026-0001
status:
type: string
enum: [pending, shipped, delivered]
Error:
type: object
required: [code, message]
properties:
code:
type: string
message:
type: string
responses:
Invalid:
description: The request does not comply with the contract
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
Unauthenticated:
description: The token or the API Key is missing or not valid
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
Forbidden:
description: The token is valid but does not have the required scope
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
11. Call the API as a consumer would
Every call carries both headers:
GET /orders/v1/orders HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...
X-API-Key: 3f9c1e...
From PowerShell, on Windows, first store the credentials in environment variables (never in the script):
$env:CLIENT_ID = "your-client-id"
$env:CLIENT_SECRET = "your-client-secret"
$env:API_KEY = "your-api-key"
Then request the token and call the API:
# 1. Request the token with the Client ID and the Client Secret
$token = Invoke-RestMethod -Method Post -Uri "https://login.example.com/oauth2/token" `
-ContentType "application/x-www-form-urlencoded" `
-Body @{
grant_type = "client_credentials"
client_id = $env:CLIENT_ID
client_secret = $env:CLIENT_SECRET
scope = "orders.read"
}
# 2. Call the API with the token and the API Key
Invoke-RestMethod -Uri "https://api.example.com/orders/v1/orders" -Headers @{
Authorization = "Bearer $($token.access_token)"
"X-API-Key" = $env:API_KEY
}
12. Validate the contract
Save the contract as openapi.yaml and validate it with Redocly CLI (it needs Node.js). You can also paste it into editor.swagger.io to see it as interactive documentation.
npx @redocly/cli lint openapi.yaml
Common errors
One mechanism is required when you wanted both (or the other way round)
In security, two schemes in the same list item mean AND; in different items, OR. Check the hyphens in step 6.
An operation stops requiring the API Key
An operation’s security completely replaces the root one. If you only put oauth2 in the operation, the API Key is no longer required: repeat both schemes.
The API is left open by mistake
security: [] in an operation removes all security. Use it only on purpose, for example on a health endpoint.
Secrets inside the contract
The contract is shared and published: it never contains a Client Secret or real API Keys, only the tokenUrl and the scopes.
A scope is requested that is not declared
Every scope used in security has to exist in flows.clientCredentials.scopes; otherwise, validators report an error and the gateway may reject the token.
Error when requesting the token from Microsoft Entra ID
In Client Credentials, Entra ID only accepts scopes of the form api://{api-id}/.default: specific permissions are granted to the application as roles, not requested one by one.
A token is requested on every call
It overloads the authorisation server and adds latency. Store the token and reuse it until shortly before it expires (expires_in).
The API Key travels in the URL
As a query parameter (?api_key=…) it ends up in proxy and server logs. Always send it in a header.
401 and 403 are confused
If a valid token without the required scope returns 401, the consumer will request a new token again and again without solving anything. Lack of permission is 403.
Next steps
- Import the contract into the API Gateway (for example, Azure API Management) and validate the token with its
validate-jwtpolicy. - Generate clients and server stubs from the contract with OpenAPI Generator.
- Spin up a mock server with Prism so that consumers can test before the backend exists.
- Add contract validation and breaking-change detection to the CI/CD pipeline.
- Version the contract (
info.versionand the/v1path) and don’t publish breaking changes in the same version.