# OpenAPI 3 contract with OAuth 2.0 Client Credentials and API Key

A Bitflow Solutions guide. Web version: https://bitflow-solutions.com/en/guias-tecnicas/openapi-3-contract-oauth-client-credentials-api-key/

## 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 `components` and `$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

### Document structure

| Field | What it’s for |
|---|---|
| openapi | Version (3.0.3 or 3.1.0). Required |
| info | Title, version, description and contact. Required |
| servers | Base URL of each environment |
| paths | Paths and operations |
| components | Reusable schemas, parameters, responses and security |
| security | Default security |
| tags | Grouping in the documentation |

### Security schemes

```yaml
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)
```

### Requiring the security (AND versus OR)

```yaml
# 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: []
```

```yaml
# 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: []
```

### Client Credentials: requesting the token

```http
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
```

```json
{
  "access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "Bearer",
  "expires_in": 3600
}
```

### Calling the API

```http
GET /orders/v1/orders HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...
X-API-Key: 3f9c1e...
```

From PowerShell:

```powershell
$env:CLIENT_ID     = "your-client-id"
$env:CLIENT_SECRET = "your-client-secret"
$env:API_KEY       = "your-api-key"

# 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
}
```

### 401 and 403 errors

- 401: the token or the API Key is missing or not valid
- 403: the token is valid but does not have the required scope

### Complete contract (openapi.yaml)

```yaml
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'
```

### Validating the contract

```bash
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-jwt` policy.
- 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.version` and the `/v1` path) and don’t publish breaking changes in the same version.
