API Design and Integration Contracts

APIs as contracts between systems: the payment notification API, ACCEPTED versus RECONCILED, failure responses, versioning, anti-corruption layers and contract testing.

  • Intermediate to advanced
  • About 25 minutes
  • Includes an exercise and a knowledge check

The concept An API is a contract, not just an endpoint

When Apex integrates with a payment provider, both sides must agree on the details: what is sent and what is required, what a successful response means, how errors look, whether the sender may retry, how duplicates are identified, how the call is authenticated and how the contract will change over time. Poor API design creates integration problems that often appear only after deployment.

Design it The payment notification API

The provider calls this endpoint each time it processes a payment: POST /api/v1/payment-notifications/provider-a (the frozen contract below explains the provider in the path). Each provider sends its own field names, and its adapter maps them to Apex's canonical payment. A simplified request from Provider A looks like this:

jsonPayment notification request from Provider A (fictional)

{
  "payment_ref": "PAY-77821",
  "loan": "LN-10042",
  "paid_amount": "425.50",
  "currency": "USD",
  "paid_at": "2026-11-18T14:30:00Z"
}

This is a teaching example, not a complete financial contract. A production contract also defines field formats and limits, the money representation, time-zone and timestamp meaning, required identifiers, allowed status values, signature verification, retention and privacy rules, and schema versioning.

Freeze it before coding The payment notification contract, version 1

Module 07 builds against this table, so nothing in it may change silently during implementation. Any change goes through a contract decision, agreed with both providers, and a new version if it breaks callers:

ElementVersion 1
EndpointPOST /api/v1/payment-notifications/{provider}, where provider is provider-a or provider-b. Decision CD-01: the provider is in the path so the right adapter and signing key are chosen before the body is parsed
AuthenticationHeaders X-Apex-Timestamp (UTC, ISO 8601) and X-Apex-Signature (hex HMAC-SHA256 of the timestamp, a dot and the raw body bytes), with one key per provider from the secret store
Replay protectionRequests outside a five-minute window are refused, and so is a signature already seen. Every provider retry is signed again with a new timestamp
Request bodyEach provider's own documented schema, mapped by its adapter to the canonical payment. Amounts are decimal strings with at most two decimals, or integer cents; never binary floating point
Canonical fieldsproviderTransactionId (1 to 64 characters), loanAccountId (1 to 32), amount in minor units (greater than 0), currency (USD only in v1), paymentStatus (SUCCESS, FAILED or REVERSED), transactionTimestamp (an instant, stored in UTC), providerReference (optional, up to 64). paymentStatus and providerReference are still to be confirmed with the providers
Responses202 ACCEPTED with ingestionId for a new payment; 200 with the same ingestionId for an exact repeat; 409 DUPLICATE_CONFLICT for the same ID with different content
Errors400 INVALID_PAYMENT_REQUEST, 401 AUTHENTICATION_FAILED, 413 PAYLOAD_TOO_LARGE, 429 RATE_LIMITED, 503 TEMPORARILY_UNAVAILABLE. Every error body is errorCode, message and correlationId, never a stack trace
VersioningWithin v1, only new optional fields. A breaking change becomes /api/v2, and both run side by side for an agreed overlap, such as six months

A table can be frozen by agreement. A machine-readable contract can be frozen by tooling. Here is the same version 1 written as an OpenAPI 3.1 document. Contract tests, mock servers and provider documentation can all be generated from it, and a change to the file is a change to the contract that a reviewer can see.

yamlpayment-notifications-v1.yaml (fictional)

openapi: 3.1.0
info:
  title: Apex payment notification API (fictional)
  version: 1.0.0
  description: >-
    Version 1 is frozen. Within v1 only new optional fields may be added; a
    breaking change becomes /api/v2, and both run side by side for an agreed
    overlap. Each provider has its own path (decision CD-01), so the right
    adapter and signing key are chosen before the body is parsed.
paths:
  /api/v1/payment-notifications/provider-a:
    post:
      operationId: notifyPaymentProviderA
      summary: Provider A reports one processed payment.
      security:
        - providerSignature: []
      parameters:
        - $ref: '#/components/parameters/Timestamp'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ProviderANotification'
      responses:
        '202':
          $ref: '#/components/responses/Accepted'
        '200':
          $ref: '#/components/responses/Repeat'
        '400':
          $ref: '#/components/responses/Error'
        '401':
          $ref: '#/components/responses/Error'
        '409':
          $ref: '#/components/responses/Error'
        '413':
          $ref: '#/components/responses/Error'
        '429':
          $ref: '#/components/responses/Error'
        '503':
          $ref: '#/components/responses/Error'
  /api/v1/payment-notifications/provider-b:
    post:
      operationId: notifyPaymentProviderB
      summary: Provider B reports one processed payment.
      security:
        - providerSignature: []
      parameters:
        - $ref: '#/components/parameters/Timestamp'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ProviderBNotification'
      responses:
        '202':
          $ref: '#/components/responses/Accepted'
        '200':
          $ref: '#/components/responses/Repeat'
        '400':
          $ref: '#/components/responses/Error'
        '401':
          $ref: '#/components/responses/Error'
        '409':
          $ref: '#/components/responses/Error'
        '413':
          $ref: '#/components/responses/Error'
        '429':
          $ref: '#/components/responses/Error'
        '503':
          $ref: '#/components/responses/Error'
components:
  securitySchemes:
    providerSignature:
      type: apiKey
      in: header
      name: X-Apex-Signature
      description: >-
        Hex HMAC-SHA256 of the timestamp, a dot and the raw body bytes, with one
        key per provider from the secret store. A signature already seen is
        refused.
  parameters:
    Timestamp:
      name: X-Apex-Timestamp
      in: header
      required: true
      description: >-
        When the provider signed the request, in UTC (ISO 8601). Requests outside
        a five-minute window are refused. Every retry is signed again.
      schema:
        type: string
        format: date-time
  responses:
    Accepted:
      description: A new payment was accepted for processing. Accepted is not reconciled.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Acknowledgement'
    Repeat:
      description: An exact repeat of an accepted payment; the same ingestionId is returned.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Acknowledgement'
    Error:
      description: >-
        400 INVALID_PAYMENT_REQUEST, 401 AUTHENTICATION_FAILED, 409
        DUPLICATE_CONFLICT (same ID, different content), 413 PAYLOAD_TOO_LARGE,
        429 RATE_LIMITED, 503 TEMPORARILY_UNAVAILABLE.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
  schemas:
    ProviderANotification:
      type: object
      description: Provider A's documented body. Unknown fields are ignored.
      required: [payment_ref, loan, paid_amount, currency, paid_at]
      properties:
        payment_ref:
          type: string
          minLength: 1
          maxLength: 64
          x-apex-source: Confirmed. Provider A documentation; enforced by ProviderAAdapter (Module 07).
        loan:
          type: string
          minLength: 1
          maxLength: 32
          x-apex-source: Confirmed. Provider A documentation; enforced by ProviderAAdapter.
        paid_amount:
          type: string
          description: >-
            A decimal string greater than zero with at most two decimals and at most 16 whole digits,
            so the amount in cents always fits a 64-bit integer. Never a binary floating-point number.
          pattern: '^(?!0+(\.0+)?$)[0-9]{1,16}(\.[0-9]{1,2})?$'
          x-apex-source: Confirmed. Provider A documentation; enforced by ProviderAAdapter.
        currency:
          type: string
          enum: [USD]
          x-apex-source: Confirmed. USD only in v1.
        paid_at:
          type: string
          format: date-time
          description: An instant in UTC.
          x-apex-source: Confirmed. Provider A documentation; enforced by ProviderAAdapter.
    ProviderBNotification:
      type: object
      description: Provider B's documented body. Unknown fields are ignored.
      required: [transactionId, loanAccount, amountInCents, currency, timestamp]
      properties:
        transactionId:
          type: string
          minLength: 1
          maxLength: 64
          x-apex-source: Confirmed. Provider B documentation; enforced by ProviderBAdapter (Module 07).
        loanAccount:
          type: string
          minLength: 1
          maxLength: 32
          x-apex-source: Confirmed. Provider B documentation; enforced by ProviderBAdapter.
        amountInCents:
          type: integer
          minimum: 1
          description: Already in cents.
          x-apex-source: Confirmed. Provider B documentation; enforced by ProviderBAdapter.
        currency:
          type: string
          enum: [USD]
          x-apex-source: Confirmed. USD only in v1.
        timestamp:
          type: string
          format: date-time
          description: Local time with a UTC offset, such as 2026-11-18T08:30:00-06:00.
          x-apex-source: Confirmed. Provider B documentation; enforced by ProviderBAdapter.
    CanonicalPayment:
      type: object
      description: What every adapter produces. The rest of Apex sees only this shape.
      required: [provider, providerTransactionId, loanAccountId, amountMinorUnits, currency, transactionTimestamp]
      properties:
        provider:
          enum: [PROVIDER_A, PROVIDER_B]
        providerTransactionId:
          type: string
          maxLength: 64
        loanAccountId:
          type: string
          maxLength: 32
        amountMinorUnits:
          type: integer
          minimum: 1
        currency:
          const: USD
        transactionTimestamp:
          type: string
          format: date-time
        paymentStatus:
          enum: [SUCCESS, FAILED, REVERSED]
          x-apex-source: >-
            Assumed. In the frozen v1 table, but neither provider's documented body
            carries a status yet. Confirm the field and its values with each
            provider before Module 07 depends on it.
        providerReference:
          type: string
          maxLength: 64
          x-apex-source: Assumed. Optional in the v1 table; not yet in either provider's documented body.
    Acknowledgement:
      type: object
      required: [ingestionId, status, receivedAt]
      properties:
        ingestionId:
          type: string
        status:
          const: ACCEPTED
        receivedAt:
          type: string
          format: date-time
    ErrorResponse:
      type: object
      description: Never a stack trace.
      additionalProperties: false
      required: [errorCode, message, correlationId]
      properties:
        errorCode:
          type: string
          enum:
            - INVALID_PAYMENT_REQUEST
            - AUTHENTICATION_FAILED
            - DUPLICATE_CONFLICT
            - PAYLOAD_TOO_LARGE
            - RATE_LIMITED
            - TEMPORARILY_UNAVAILABLE
        message:
          type: string
        correlationId:
          type: string

Validating the document, then the Module 07 adapter inputs against it

payment-notifications-v1.yaml: valid OpenAPI 3.1

Provider A: PAY-77821                  accepted
  no loan                              rejected: 'loan' is a required property
  paid_amount 99.999                   rejected: '99.999' does not match '^(?!0+(\\.0+)?$)[0-9]{1,16}(\\.[0-9]{1,2})?$'
  paid_amount 4x5.50                   rejected: '4x5.50' does not match '^(?!0+(\\.0+)?$)[0-9]{1,16}(\\.[0-9]{1,2})?$'
  paid_amount 99999999999999999.99     rejected: '99999999999999999.99' does not match '^(?!0+(\\.0+)?$)[0-9]{1,16}(\\.[0-9]{1,2})?$'
  paid_amount as a number              rejected: 425.5 is not of type 'string'
  currency EUR                         rejected: 'EUR' is not one of ['USD']
Provider B: TXN-5531                   accepted
  timestamp without an offset          rejected: '2026-11-18 08:30' is not a 'date-time'
  amountInCents 0                      rejected: 0 is less than the minimum of 1

Still assumed, to confirm with the providers: CanonicalPayment.paymentStatus, CanonicalPayment.providerReference

Real output from openapi-spec-validator 0.7.1 and jsonschema 4.23.0 running tools/fde/m06/validate.py, November 22, 2026.

Notice what the document adds to the table. Each provider has its own path and its own body, written from its documentation: Provider A sends a decimal string, Provider B sends cents with a local time and an offset. The inputs above are the same ones Module 07's adapters are tested with, and the contract accepts and refuses exactly the same ones. Every field says where it is confirmed, and two canonical fields are still assumed: no provider document carries a payment status or a reference yet. When you write the contract tests in Module 07, point them at this file, so the code and the contract cannot drift apart quietly.

The response ACCEPTED does not mean RECONCILED

jsonSuccessful response

{
  "ingestionId": "ING-90012",
  "status": "ACCEPTED",
  "receivedAt": "2026-11-18T14:30:01Z"
}
A timeline in three lanes. At 14:30:00 UTC Payment Provider A posts to /api/v1/payment-notifications/provider-a. At 14:30:01 the Apex API has validated and stored the notification and answers with ingestionId ING-90012 and status ACCEPTED, and the provider stops waiting. Afterwards, in the background, the record is normalized, waits for settlement, and becomes MATCHED when the bank record arrives, minutes or hours later.
The provider gets a fast, honest answer. Reconciliation finishes later, on its own schedule.

ACCEPTED means the system has taken the information for processing. Reconciliation may happen asynchronously, seconds or hours later. Do not make the provider wait for the whole workflow.

When it fails Failure responses

SituationExample response
Invalid request400 Bad Request
Missing authentication401 Unauthorized
Authenticated but not permitted403 Forbidden
Duplicate requestThe documented duplicate behavior, such as returning the stored result
Same ID, different content409 Conflict, with an alert to the integration owner
Bad signature, old timestamp or replay401 Unauthorized, and a security log entry
Rate limit exceeded429 Too Many Requests
Temporary dependency failure503 Service Unavailable

The contract must say what happens when the first request was stored but its response was lost, because the provider will retry. That question leads straight to idempotency in Lesson 05.

Contracts change Versioning and the anti-corruption layer

Provider A sends a field called payment_ref today and renames it paymentRef next year. You cannot assume every provider changes at the same time. Use versioned endpoints, backward-compatible optional fields, schema evolution rules and adapters per provider. The internal model must not be tied to any one provider’s naming.

On the left, a photo of two travel plug adapters on a wooden table. On the right, Provider A sends payment_ref PAY-1001 and paid_amount as the text 425.50; Provider B sends transactionId PAY-1001 and amountInCents 42550. Each passes through its own adapter and comes out as one internal model: sourceSystem PROVIDER_A, sourceTransactionId PAY-1001, amountMinorUnits 42550, currency USD. Money is kept in integer minor units to avoid floating-point rounding. When a provider renames a field, only its adapter changes.
An anti-corruption layer works like a plug adapter: the outside can differ, the inside stays the same.

This is an anti-corruption layer: it protects the internal system from depending on external models. Provider differences are absorbed once, at the edge.

Prove it Contract testing

A contract test checks that the consumer and the provider agree on the request and response structure. Cover required, invalid and unknown fields, version compatibility, error responses, authentication failures and duplicate delivery. Contract tests catch a provider change before it breaks production.

Practice Write the integration contracts

Practical exercise

Exercise 03: the API contract document

Specify four APIs: payment provider notification, settlement record ingestion, finance user transaction lookup, and exception resolution.

  1. For each: method and path, authentication, request and response schemas.
  2. For each: validation, error behavior, idempotency requirements.
  3. For each: the versioning strategy.
Show a sample entry
  • Exception resolution: POST /api/v1/exceptions/{exceptionId}/resolution-requests.
  • Authentication: finance user token from the identity provider; role finance analyst.
  • Request: resolution code, reason, evidence references, and an idempotency key.
  • Response: request ID and status PENDING_APPROVAL; the change is applied only after a supervisor approves.
  • Errors: 403 if the user is not assigned the case; 409 if the case is already resolved.
  • Versioning: URL version v1; new optional fields are backward compatible.

3 questions

Check your understanding

1. What does ACCEPTED mean in an asynchronous workflow?
2. Why separate external API contracts from the internal data model?
3. Which is the safest way to represent $425.50 in the internal model?
Answer every question to submit.

What you can do now

  • Design an API as a contract with success, failure and retry behavior.
  • Explain why ACCEPTED is not RECONCILED.
  • Version contracts and isolate them with an anti-corruption layer.
  • Plan contract tests for an external integration.