PHP API Documentation with Plain PHP 8.3

PHP API Documentation with Plain PHP 8.3

PHP API Documentation with Plain PHP 8.3

A PHP API can return valid JSON and still be difficult for other developers to understand, integrate with, or maintain when its endpoints, parameters, authentication rules, and response formats are undocumented. Experienced PHP developers address this problem by documenting the API contract clearly, using practical examples, and keeping the documentation aligned with the actual implementation. With PHP 8.3, you can build useful API documentation using plain PHP, without introducing a framework or a complex documentation platform; the key is choosing a maintainable structure and generating an OpenAPI specification that tools such as Swagger UI can display.

PHP API Documentation Approaches

ApproachMaintenanceEffortBest for
Hand-written MarkdownManual updatesLow initiallySmall APIs and internal guides
Static OpenAPI fileManual specification updatesMediumStable APIs with a defined contract
PHP 8 attribute-based generationUpdated alongside controller codeMedium initiallyPHP applications with evolving endpoints
Postman/Insomnia exportCollection must stay synchronizedLow to mediumTeams already using API clients
Admin-panel docsDepends on panel and integrationMedium to highApplications with existing administrative interfaces

Selecting a documentation strategy means balancing implementation effort against long-term accuracy and maintenance. I evaluate each approach by how closely it follows application changes, how easily developers can review its contract, and whether consumers need interactive testing. These differences become particularly important as an API gains endpoints and additional maintainers.

  • Hand-written Markdown: Use it for installation instructions, business rules, and integration examples, but avoid making it the only technical API reference.
  • OpenAPI specifications: Establish a standardized contract that supports reusable schemas, endpoint descriptions, client generation, and interactive documentation.
  • PHP attributes: Keep endpoint metadata beside controller methods, although generating a complete specification requires additional implementation work.
  • API client collections: Support development and testing, but exported Postman or Insomnia collections may omit authentication requirements, response schemas, and reusable components.
  • Administrative documentation: Works with existing admin panels, but introducing an entire administrative system solely to publish API references adds unnecessary complexity.

My recommendation is to use OpenAPI as the source of truth and Swagger UI as the presentation layer, adding PHP attributes where endpoint metadata benefits from living beside its implementation. This separates the API contract from its presentation while allowing developers to choose between manual maintenance and automated generation. The following infographic illustrates how these components connect.

PHP API documentation pipeline from attributes to OpenAPI spec to Swagger UI

Start with an OpenAPI Contract

Before generating documentation, establish exactly what consumers need to understand about the application. An OpenAPI specification describes HTTP endpoints, parameters, request bodies, response formats, security requirements, and reusable schemas. I recommend defining this contract before introducing automation because generation should preserve intentional API behavior rather than determine it.

Swagger UI reads the specification and presents its contents through an interactive browser interface. Developers can inspect available operations, examine expected payloads, and execute test requests when the configured environment permits. This makes the documentation useful during initial integration and ongoing development.

For a straightforward PHP application, begin with a hand-written openapi.yaml file. Consider an application exposing one endpoint for retrieving a customer by ID and another for creating a customer. Even this limited example benefits from explicitly describing operations and expected responses.

A minimal specification could look like this:

openapi: 3.0.3

info:
  title: Customer API
  description: API documentation for the customer service.
  version: 1.0.0

servers:
  - url: https://api.example.com
    description: Production server

paths:
  /api/customers/{id}:
    get:
      summary: Get a customer
      operationId: getCustomer
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: integer
      responses:
        '200':
          description: Customer retrieved successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Customer'
        '404':
          description: Customer not found

  /api/customers:
    post:
      summary: Create a customer
      operationId: createCustomer
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - name
                - email
              properties:
                name:
                  type: string
                email:
                  type: string
                  format: email
      responses:
        '201':
          description: Customer created successfully
        '422':
          description: Validation failed

components:
  schemas:
    Customer:
      type: object
      properties:
        id:
          type: integer
        name:
          type: string
        email:
          type: string
          format: email

Although this specification is intentionally small, it already provides meaningful information to an API consumer. The operation ID identifies the endpoint, the path parameter establishes an input requirement, and the response definitions communicate expected HTTP outcomes. A reusable customer schema also prevents unnecessary repetition across multiple operations.

For production applications, extend the contract to cover pagination, filtering, validation failures, rate limits, authentication, and common response structures. I prioritize consistency over documenting a large number of endpoints because incomplete descriptions create uncertainty during integration. Every documented operation should explain the information consumers need to use it correctly.

One distinction deserves particular attention: OpenAPI describes the API contract rather than implementing application behavior. Declaring a 201 response does not make a PHP controller return that status code, and documenting a required field does not automatically validate incoming requests. The implementation and specification must agree through deliberate development practices and appropriate tests.

Keep the initial specification under version control, preferably in a dedicated location such as docs/openapi.yaml. This makes documentation changes visible during code review and allows developers to compare revisions through ordinary Git workflows. It also provides a stable starting point for introducing automated generation when manual maintenance becomes inconvenient.

Serve Swagger UI with Plain PHP

Publishing interactive API documentation does not require installing a PHP framework or building a dedicated administration application. Swagger UI provides the browser interface, while a lightweight PHP router delivers the interface and its OpenAPI specification through separate HTTP routes. I prefer this arrangement because it keeps documentation infrastructure independent of the application’s architecture.

A practical project structure separates publicly accessible files from application documentation and generated specifications. The public entry point handles incoming requests, while the OpenAPI document remains available through a controlled PHP endpoint. This arrangement also makes it easier to introduce authentication or deployment-specific restrictions later.

A practical project structure looks like this:

project/
├── public/
│ └── index.php
├── docs/
│ └── openapi.yaml
└── src/
 └── CustomerController.php

The following example assumes the project uses PHP’s built-in development server or another web server configured to forward requests through public/index.php. The router distinguishes documentation requests from specification requests and returns the appropriate content. Keep this routing logic straightforward so it remains easy to maintain.

Create the entry point:

<?php

declare(strict_types=1);

$routes = [
    'GET /docs' => static function (): void {
        header('Content-Type: text/html; charset=utf-8');

        echo <<<'HTML'
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Customer API Documentation</title>
    <link rel="stylesheet"
          href="https://unpkg.com/swagger-ui-dist@5/swagger-ui.css">
</head>
<body>
    <div id="swagger-ui"></div>

    <script src="https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js"></script>
    <script>
        SwaggerUIBundle({
            url: '/openapi.yaml',
            dom_id: '#swagger-ui'
        });
    </script>
</body>
</html>
HTML;
    },

    'GET /openapi.yaml' => static function (): void {
        $file = dirname(__DIR__) . '/docs/openapi.yaml';

        if (!is_file($file)) {
            http_response_code(404);
            header('Content-Type: text/plain; charset=utf-8');
            echo 'OpenAPI specification not found';
            return;
        }

        header('Content-Type: application/yaml; charset=utf-8');
        readfile($file);
    },
];

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$path = parse_url(
    $_SERVER['REQUEST_URI'] ?? '/',
    PHP_URL_PATH
);

$route = $method . ' ' . $path;

if (!isset($routes[$route])) {
    http_response_code(404);
    header('Content-Type: application/json; charset=utf-8');

    echo json_encode([
        'error' => 'Route not found',
    ]);

    exit;
}

$routes[$route]();

Run the application from the project directory:

php -S localhost:8000 -t public public/index.php

Open /docs in your browser and check whether Swagger UI successfully loads the specification from /openapi.yaml. If the interface appears without endpoint definitions, inspect the specification route before changing the Swagger UI configuration. A successful page load does not necessarily mean that the browser received a valid OpenAPI document.

Several implementation details determine whether this setup behaves reliably. First, use parse_url() to extract the request path instead of comparing the complete request URI, because query strings should not affect documentation route selection. Second, return the correct content type for HTML, YAML, and JSON responses so browsers and API tools interpret resources correctly.

Third, avoid exposing the entire documentation directory through the public filesystem when only a particular specification needs to be served. A PHP endpoint can read and return the required file without making unrelated project files directly accessible. This also provides a convenient place to apply access restrictions.

Lightweight PHP router serving an OpenAPI specification and Swagger UI to a browser

Generate Documentation with PHP 8 Attributes

A manually maintained OpenAPI document works well when an API changes infrequently and its contract remains relatively stable. However, maintaining a separate specification becomes repetitive when developers regularly introduce endpoints, modify parameters, or change controller behavior. PHP 8 attributes provide an alternative by placing documentation metadata directly alongside the methods responsible for handling requests.

Attributes are useful because PHP supports inspecting them through reflection without parsing specially formatted comments. This makes it possible to create a small generator that discovers documented controller methods and converts their metadata into an OpenAPI document. The approach requires initial development but reduces unnecessary duplication as the application evolves.

Start by creating a custom attribute class. Its responsibility should remain limited to describing the information needed by the documentation generator rather than implementing application behavior. Keeping the definition simple also makes it easier to extend the documentation model later.

<?php

declare(strict_types=1);

#[Attribute(Attribute::TARGET_METHOD)]
final class ApiEndpoint
{
    public function __construct(
        public readonly string $method,
        public readonly string $path,
        public readonly string $summary,
        public readonly int $successCode = 200
    ) {
    }
}

Now attach that attribute to your controller methods. Each attribute should describe the relevant HTTP operation and its public endpoint information rather than attempting to reproduce the complete controller implementation. This establishes a clear relationship between the application method and its corresponding documentation entry.

<?php

declare(strict_types=1);

final class CustomerController
{
    #[ApiEndpoint(
        method: 'GET',
        path: '/api/customers/{id}',
        summary: 'Retrieve a customer',
        successCode: 200
    )]
    public function show(int $id): array
    {
        return [
            'id' => $id,
            'name' => 'John Smith',
            'email' => '[email protected]',
        ];
    }

    #[ApiEndpoint(
        method: 'POST',
        path: '/api/customers',
        summary: 'Create a customer',
        successCode: 201
    )]
    public function store(): array
    {
        return [
            'message' => 'Customer created',
        ];
    }
}

These examples focus on endpoint discovery and basic metadata, which is sufficient to demonstrate the generation process. A production implementation should introduce additional attributes for request parameters, authentication requirements, request bodies, and response schemas. The objective is to make important contract information explicit without creating an unnecessarily complicated annotation system.

Next, create a small generator named generate-openapi.php. The generator uses PHP reflection to inspect the controller, retrieve its attributes, and construct an OpenAPI document containing the discovered paths. It writes JSON because JSON is a valid OpenAPI input format and PHP can encode the resulting structure without requiring an additional YAML dependency.

<?php

declare(strict_types=1);

require __DIR__ . '/ApiEndpoint.php';
require __DIR__ . '/CustomerController.php';

$controller = new ReflectionClass(CustomerController::class);

$paths = [];

foreach ($controller->getMethods(
    ReflectionMethod::IS_PUBLIC
) as $method) {
    $attributes = $method->getAttributes(ApiEndpoint::class);

    foreach ($attributes as $attribute) {
        /** @var ApiEndpoint $endpoint */
        $endpoint = $attribute->newInstance();

        $httpMethod = strtolower($endpoint->method);

        $parameters = [];

        preg_match_all(
            '/\{([^}]+)\}/',
            $endpoint->path,
            $matches
        );

        foreach ($matches[1] as $parameter) {
            $parameters[] = [
                'name' => $parameter,
                'in' => 'path',
                'required' => true,
                'schema' => [
                    'type' => 'string',
                ],
            ];
        }

        $paths[$endpoint->path][$httpMethod] = [
            'summary' => $endpoint->summary,
            'operationId' => $method->getName(),
            'parameters' => $parameters,
            'responses' => [
                (string) $endpoint->successCode => [
                    'description' => 'Successful response',
                ],
            ],
        ];
    }
}

$specification = [
    'openapi' => '3.0.3',
    'info' => [
        'title' => 'Customer API',
        'version' => '1.0.0',
    ],
    'paths' => $paths,
];

$output = json_encode(
    $specification,
    JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES
);

if ($output === false) {
    throw new RuntimeException(
        'Unable to generate OpenAPI specification'
    );
}

$file = __DIR__ . '/docs/openapi.json';

if (!is_dir(dirname($file))) {
    mkdir(dirname($file), 0775, true);
}

if (file_put_contents($file, $output . PHP_EOL) === false) {
    throw new RuntimeException(
        'Unable to write OpenAPI specification'
    );
}

echo "OpenAPI specification generated successfully.\n";

Run the generator using the following command:

php generate-openapi.php

The generated file contains an OpenAPI document with paths discovered from the controller’s attributes. Its structure can then be served through the same PHP endpoint used for a manually maintained specification. This means the presentation layer does not need to change when the project moves from manual documentation to attribute-based generation.

Here is an abbreviated example of the generated JSON structure:

{
  "openapi": "3.0.3",
  "info": {
    "title": "Customer API",
    "version": "1.0.0"
  },
  "paths": {
    "/api/customers/{id}": {
      "get": {
        "summary": "Retrieve a customer",
        "operationId": "show",
        "responses": {
          "200": {
            "description": "Successful response"
          }
        }
      }
    }
  }
}

I recommend introducing additional attributes as the application develops more complex requirements. Separate definitions for response schemas, request bodies, security schemes, and reusable parameters can gradually expand the generator’s capabilities. Keep the implementation predictable and focused on your application instead of attempting to build a general-purpose documentation framework.

Keep Routes and Documentation in Sync

Generating an OpenAPI specification does not guarantee that every application route appears in the published documentation. Developers can introduce routes without adding documentation metadata, or remove endpoints while leaving outdated specifications behind. A continuous integration check helps identify these inconsistencies before they reach deployment.

For a small plain PHP application, start by comparing the application’s route registry with the paths discovered through controller attributes. This checks the public HTTP contract rather than relying on implementation-specific method names. It also provides a straightforward foundation for extending documentation validation as the application grows.

Suppose the application maintains its route definitions in routes.php. The registry should contain the relevant HTTP methods, public paths, and associated handlers so that the documentation check has a reliable source. Avoid maintaining a separate route list solely for documentation because that introduces another opportunity for inconsistencies.

<?php

declare(strict_types=1);

return [
    'GET /api/customers/{id}' => [
        CustomerController::class,
        'show',
    ],

    'POST /api/customers' => [
        CustomerController::class,
        'store',
    ],
];

Create a validation script named check-api-docs.php. Its responsibility is to compare registered application routes against the paths represented by the generated specification and identify missing or unexpected operations. Keep the comparison focused on HTTP methods and paths because those define the externally visible endpoint structure.

<?php

declare(strict_types=1);

require __DIR__ . '/ApiEndpoint.php';
require __DIR__ . '/CustomerController.php';

$routes = require __DIR__ . '/routes.php';

$documented = [];

$reflection = new ReflectionClass(CustomerController::class);

foreach ($reflection->getMethods(
    ReflectionMethod::IS_PUBLIC
) as $method) {
    foreach (
        $method->getAttributes(ApiEndpoint::class)
        as $attribute
    ) {
        $endpoint = $attribute->newInstance();

        $documented[] = strtoupper($endpoint->method)
            . ' ' . $endpoint->path;
    }
}

$registered = array_keys($routes);

sort($registered);
sort($documented);

$missing = array_diff($registered, $documented);
$orphaned = array_diff($documented, $registered);

if ($missing !== [] || $orphaned !== []) {
    fwrite(STDERR, "API documentation is out of sync.\n");

    foreach ($missing as $route) {
        fwrite(STDERR, "Missing documentation: {$route}\n");
    }

    foreach ($orphaned as $route) {
        fwrite(STDERR, "Undocumented route entry: {$route}\n");
    }

    exit(1);
}

echo "API routes and documentation are synchronized.\n";

The check deliberately compares HTTP methods and paths rather than controller method names. A developer may change an endpoint’s handler without changing its public contract, and that should not automatically invalidate its documentation. Conversely, changing a public path should trigger a review of the corresponding specification.

Add the following commands to your CI workflow. The workflow should generate the OpenAPI document, execute the consistency check, and verify that the committed specification reflects the current application metadata. This makes documentation validation part of the normal development process instead of an optional manual activity.

php generate-openapi.php
php check-api-docs.php
git diff --exit-code -- docs/openapi.json

The final command checks whether generating the specification changed the committed file. If a developer modifies an attribute but forgets to commit the resulting specification, the build fails and identifies the missing update. This simple safeguard makes documentation changes visible before they become deployment problems.

One limitation is that the example assumes the route registry contains all relevant application routes and that the reflected controller covers the documented endpoints. Applications with multiple controllers should maintain an explicit controller list or discover them through a controlled application registry. Otherwise, validation may incorrectly report missing documentation or overlook endpoints entirely.

A passing CI build should mean the documentation is consistent with the code, not merely that a YAML or JSON file exists. A syntactically valid specification can still describe an endpoint incorrectly, so validation must examine more than file existence. The goal is to detect meaningful contract differences before consumers encounter them.

CI pipeline comparing route definitions with generated documentation at a checkpoint gate

Maintain Documentation as Part of Development

When a developer introduces a required parameter, changes a response format, or adds authentication, the corresponding specification should be updated in the same pull request. Reviewers can then evaluate whether the implementation and its documented contract agree before approving the change. This also makes documentation ownership part of normal engineering responsibility.

Authentication: Explain whether an endpoint requires bearer tokens, API keys, sessions, or another authentication mechanism. OpenAPI supports reusable security schemes, which avoid repeating authentication instructions across individual operations. Document relevant permissions and distinguish authentication requirements from endpoint-specific authorization rules.

Request validation: Describe required fields, accepted data types, supported formats, and validation failures. If the PHP application returns structured 422 responses, include a reusable error schema and representative examples. Consumers should understand which inputs are accepted and how the application communicates invalid requests.

Response consistency: Define predictable response structures and document the meaning of important fields. Developers should not have to guess whether one endpoint returns an object, another returns an array, or a third returns an unrelated message string. Consistent schemas make client integration and automated testing easier.

Pagination and filtering: Explain supported query parameters, default sorting behavior, page sizes, and the mechanism for retrieving subsequent results. Document which parameters are optional and how unsupported values are handled. These details matter when consumers need to retrieve large collections without downloading unnecessary records.

Error handling: Document meaningful status codes such as 400, 401, 403, 404, 409, and 422 wherever they apply. Include reusable error definitions when multiple endpoints share the same response structure. Avoid claiming that every endpoint produces identical errors unless the application actually enforces that behavior.

Security deserves particular attention when publishing interactive documentation. Never include real access tokens, customer information, database credentials, or production secrets in request examples or response payloads. Use representative sample values that explain the expected structure without exposing operational information.

Do not expose private administrative endpoints through publicly accessible Swagger UI simply because those endpoints have been documented. Documentation access and API authorization are separate concerns, and protecting one does not automatically protect the other. Apply suitable access controls to both the documentation interface and the underlying application endpoints.

Finally, version the documentation alongside the API itself. When an application supports multiple API versions, make it clear which specification describes each version and which endpoints belong to each contract. Avoid silently changing the meaning of an existing endpoint because consumers may depend on its established behavior.

Frequently Asked Questions

These answers address practical decisions developers commonly face when introducing API documentation into an existing PHP application. They focus on implementation choices, compatibility, and maintenance rather than assuming every project needs identical tooling. The appropriate solution depends on application complexity and how frequently its public contract changes.

1. How should I document a PHP REST API?

OpenAPI provides a standardized way to describe endpoints, parameters, request bodies, responses, and security requirements for a PHP REST API. You can maintain the specification manually or generate endpoint metadata using PHP 8 attributes and reflection. Swagger UI can then display the resulting specification through an interactive browser interface without requiring a PHP framework.

2. Can Swagger UI work with plain PHP 8.3?

Yes, Swagger UI is a browser-based application that reads an OpenAPI specification rather than depending on a particular PHP framework. A basic PHP router can serve its HTML, JavaScript, CSS, and specification resources through ordinary HTTP routes. This makes it suitable for standalone PHP applications as well as projects built with larger frameworks.

3. Should I use PHP attributes instead of PHPDoc annotations?

PHP 8 attributes provide native, structured metadata that applications can inspect through reflection without parsing specially formatted documentation comments. They are particularly useful when developers want endpoint information to remain close to controller methods. PHPDoc annotations remain reasonable for older applications or projects that already depend on annotation-based documentation tooling.

4. Is manual OpenAPI documentation better than automatic generation?

Manual OpenAPI specifications are often easier to maintain when an API is small, stable, or managed by developers who prefer an explicit contract. Attribute-based generation becomes more attractive when endpoints change frequently and metadata benefits from living alongside controller implementations. A hybrid approach is also effective because basic endpoint information can be generated while complex schemas remain explicitly maintained.

5. How can I automatically check whether API documentation is outdated?

Generate the OpenAPI specification during development or CI and compare its documented paths against the application’s route registry. Add a validation step that fails when routes are missing from the specification or when generation produces changes that have not been committed. For stronger guarantees, validate the specification against the OpenAPI schema and test actual HTTP responses against documented structures.

Conclusion

Good PHP API documentation should make integration easier without introducing unnecessary complexity into application development. For a plain PHP 8.3 project, OpenAPI establishes the contract, Swagger UI provides the interactive interface, and PHP attributes offer a practical way to generate endpoint metadata directly from controller methods. Together, these components create a maintainable documentation workflow without requiring Laravel, Symfony, or a dedicated documentation platform.

Start with a small OpenAPI specification and serve it through a straightforward PHP router before introducing additional automation. Add reflection-based generation when manually maintaining endpoint metadata becomes inconvenient, then introduce CI checks to detect documentation drift. Expand the contract as your application grows, paying particular attention to authentication, validation, response schemas, and API versioning.

The goal is straightforward: when your API changes, its documentation should change with it.

Share:

Get Started on Creating Your Web Apps
with a Reliable Service Today!

Expert WordPress, Shopify & WooCommerce development — on time, every time.

Get a Free Quote →