All guides
  1. Home
  2. Technical guides
  3. APIs

APIsIntermediate level

OpenAPI 3 contract with OAuth 2.0 Client Credentials and API Key

9 min read

All guides

OpenAPI 3 contract with OAuth 2.0 Client Credentials and API Key

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

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

FieldWhat it’s for
openapiVersion of the specification: 3.0.3 or 3.1.0. Required.
infoTitle, API version, description and contact. Required.
serversBase URL of each environment (production, pre-production…).
pathsThe paths and their operations (GET, POST…), with parameters, body and responses.
componentsReusable pieces: data schemas, parameters, responses and security schemes.
securityThe security applied by default to every operation.
tagsGroup 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:

  1. The application requests a token from the tokenUrl with its Client ID, its Client Secret and the scopes it needs.
  2. The authorisation server checks the credentials and returns an access token with an expiry (for example, one hour).
  3. The application calls the API with the token in Authorization: Bearer ….
  4. The API Gateway validates the token (signature, expiry, audience and scopes) before letting the request through.
  5. 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

CodeMeaningExample
401 UnauthorizedThe 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 ForbiddenThe 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-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.

Share

More guides on

See all guides

Other technical guides

See all guides

APIsIntermediate

Basic structure of an API in IBM API Connect 10

How an API is structured in IBM API Connect 10: OpenAPI contract with x-ibm-configuration, Client ID and Client Secret, product with plans and limits, and validation and publishing with the apic CLI.

Read the guide 7 min read

IntegrationIntermediate

TIBCO ActiveSpaces 5.2: basic administration commands

The day-to-day commands in TIBCO ActiveSpaces 5.2: realm service on FTL servers, tibdg, grid definition, tables, starting processes, status, scaling with copysets, checkpoints and logs.

Read the guide 8 min read

DevOpsBasic

Basic CI/CD structure with GitHub Actions

A complete pipeline with GitHub Actions: tests on every push and pull request, a Docker image in GitHub Container Registry and deployment to a protected environment, with a workflow ready to copy.

Read the guide 6 min read

DevelopmentBasic

Java Spring Boot development best practices

The practices that make the biggest difference in a Spring Boot service: structure, constructor injection, DTOs, validation, errors, configuration, transactions, logs, comments, tests and automated quality.

Read the guide 7 min read

Contact

Build your next competitive advantage today

Let’s talk about how we can help you. We will reply with a clear technical proposal, with no obligation.

Request information

Fields marked with are required.