Skip to content
Tutorials Center
My learning

Topics

Lesson 82 of 147 ยท PHP and the Web

API Versioning and OpenAPI Documents

Version a PHP REST API without breaking clients - URL, header and date strategies, deprecation headers, and describing endpoints with an OpenAPI 3.1 document.

Once other people's code depends on your API, you cannot change it freely. Renaming a field, changing a type or removing an endpoint can break mobile apps that users have not updated for months. API versioning is the discipline of evolving an API while old clients keep working. OpenAPI is the widely used format for describing an API in a machine-readable document, so that documentation, client libraries, mock servers and validators can all be generated from one source of truth.

This lesson builds on REST APIs and Routing. You will learn which changes are breaking, three common versioning strategies, how to announce deprecations with HTTP headers, and how to produce a valid OpenAPI 3.1 document from PHP.

Breaking and non-breaking changes

You do not need a new version for every change. Most changes are additive and safe:

Change Breaking?
Add a new endpoint No
Add an optional request field No
Add a new field to a response No (clients must ignore unknown fields)
Remove or rename a response field Yes
Change a field's type ("id": 5 to "id": "5") Yes
Make an optional request field required Yes
Change the meaning of a status code or value Yes
Tighten validation (shorter max length) Usually yes

The first design rule is therefore be conservative in what you change and tell clients to be liberal in what they accept. The second is to document it: write down in the API guide that new response fields can appear at any time.

Three versioning strategies

flowchart LR
    R["Request"] --> U["URL: /v2/users/5"]
    R --> H["Header: Accept: application/vnd.shop.v2+json"]
    R --> D["Date header: Api-Version: 2026-03-01"]
    U --> C["Route to v2 controller"]
    H --> C
    D --> C

All three strategies end in the same place: the router picks the handler that matches the version the client asked for.

1. URL path versioning (/v1/users, /v2/users). The easiest to understand, cache, test with a browser and route. It makes versions very visible, and it is what most public APIs choose. The downside: the URL of a resource changes, even though it is "the same" resource.

2. Header (media type) versioning. The URL stays /users/5; the client sends Accept: application/vnd.shop.v2+json. It is purist-friendly but harder to test by hand and easy to get wrong in caches (remember Vary: Accept).

3. Date-based versioning. Clients pin a date (Api-Version: 2026-03-01), and the server applies all behavior as of that date. Stripe popularized this. Each account stays on its date until it opts in to a newer one. It scales to many small changes but needs careful engineering on the server.

For most projects, start with URL versions, bump the major version rarely, and keep the number of live versions small.

Routing by version

The cleanest pattern is to keep versioned code in separate namespaces or classes and have a thin resolver pick one. This example supports both a URL prefix and a header, with a default:

PHP Choosing a handler by version

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

An unsupported version (/v9/...) falls back to the default here, but for a public API it is usually better to answer 400 Bad Request or 404 Not Found with a clear message, because silently serving a different version surprises clients.

Announcing deprecation and sunset

When an old version is going away, tell clients in the responses themselves. Three HTTP headers do the job:

  • Deprecation: true (or a date) marks the endpoint as deprecated.
  • Sunset: Wed, 01 Jul 2026 00:00:00 GMT gives the date it stops working.
  • Link: <https://api.example.com/docs/migrate-v2>; rel="deprecation" points at the migration guide.
PHP Deprecation and Sunset headers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

In a real PHP app you would send these with header('Deprecation: true') (see HTTP Headers and Redirects). Log which clients still call deprecated versions so you can contact them before the sunset date.

Describing an API with OpenAPI

The OpenAPI Specification (OAS) is a JSON or YAML document describing your API: paths, operations, parameters, request bodies, responses and shared schemas. Tools turn it into interactive docs (Swagger UI, Redoc, Scalar), generate client SDKs in many languages, validate requests and responses, and drive contract tests. Version 3.1 aligns schemas with JSON Schema 2020-12.

A minimal document has this skeleton:

classDiagram
    class OpenAPIDocument {
        openapi: "3.1.0"
        info
        servers
        paths
        components
    }
    class PathItem {
        get
        post
        parameters
    }
    class Operation {
        operationId
        parameters
        requestBody
        responses
    }
    class Components {
        schemas
        securitySchemes
    }
    OpenAPIDocument --> PathItem : paths
    PathItem --> Operation
    OpenAPIDocument --> Components
    Operation ..> Components : "$ref"

Operations describe behavior; reusable pieces such as schemas live in components and are referenced with $ref.

Because OpenAPI is just JSON, PHP arrays and json_encode() are enough to generate it. Here we describe a versioned GET /v2/users/{id} and then check the result:

PHP Generating an OpenAPI 3.1 document

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Writing large documents by hand is tedious, so teams pick a workflow:

  • Design first. Write the OpenAPI file (YAML is friendlier), review it with the client teams, then implement the server and generate clients.
  • Code first. Put PHP attributes (see Attributes) or docblocks on controllers and generate the document. Libraries such as zircote/swagger-php do this.
  • Hybrid. Keep the file in the repository and validate in tests that real responses match it.

Validating against the document

An OpenAPI file is only useful if reality matches it. Even a small check in your test suite catches drift. This simplified validator checks required fields and types from the User schema; production code would use a full JSON Schema validator:

PHP Checking a response against a schema

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Note that the first response has an extra field and is still valid: adding fields is non-breaking, as discussed above.

Practical advice

  • Version the contract, not the code. Internal refactors never need a new API version.
  • Keep old versions running on shared code. Convert domain objects to versioned response shapes in thin "transformer" classes (API resources) instead of copying controllers.
  • Publish a changelog and a deprecation policy, for example "at least six months' notice".
  • Never reuse a version number for different behavior.
  • Put the version in the OpenAPI info.version and in a response header such as X-Api-Version, so bug reports are unambiguous.
  • Mind caching. URL versions cache naturally; header versions need Vary.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which change is a breaking change for existing API clients?

    Clients that read name will break. Additive changes are safe as long as clients ignore unknown fields.
  2. 2. What is the main advantage of URL path versioning such as /v2/users?

    Versions in the path are easy to see and to route. The trade-off is that the URL of a resource differs between versions.
  3. 3. Which header tells clients when an API version will stop working?

    Sunset carries the retirement date; Deprecation marks that the endpoint is deprecated.
  4. 4. What is an OpenAPI document?

    OpenAPI describes the contract. Tools generate docs, SDKs and validators from it.

Summary

  • Additive changes are safe; renames, removals and type changes are breaking and need a new version.
  • Common strategies: URL path, media-type header and date-based versions. Start with the URL.
  • Resolve the version in one place and route to versioned handlers; keep shared logic in common code.
  • Announce retirement with Deprecation, Sunset and a Link to the migration guide.
  • OpenAPI 3.1 describes your API as data: paths, parameters, responses and reusable components. It can be written by hand, generated from code, and validated in tests.

Next up: Introduction to Databases.