Skip to Content
Course content

199: API Documentation with OpenAPI in PHP

Click on the "Edit" button in the top corner of the screen to edit your slide content.

A few years back, I joined a project where the lead backend developer had just left the company. The frontend team was completely stuck; they were trying to integrate a complex order-processing system, but the only "documentation" available was a three-year-old Google Doc and a handful of Slack messages. I remember spending an entire Tuesday watching a junior dev pull his hair out because the API was returning a 400 Bad Request, and nobody knew why. It turned out the customer_id had to be a UUID, but the documentation said it was an integer. We wasted days on guesswork that could have been solved in seconds with a standardized contract.

That is where OpenAPI (formerly known as Swagger) comes in. Instead of writing documentation as a separate, static document that immediately goes out of date the moment you change a line of code, OpenAPI allows you to define your API's "contract" in a machine-readable format. In the PHP world, we don't usually write these massive YAML or JSON files by hand—that's a recipe for madness. Instead, we use attributes directly in our code to describe our endpoints, and then we generate the specification automatically.

Defining the API Contract with Swagger-PHP Attributes

If you're using PHP 8, you have a huge advantage: Attributes. Using a library like zircote/swagger-php, you can annotate your controllers and models so that the documentation lives exactly where the logic does. When you change a parameter in your code, you're looking right at the attribute that describes it, making it much harder to forget to update the docs.

Let's look at a real example. Suppose you're building a Product Inventory API. You don't want to just say "this returns a product"; you want to define exactly what a Product looks like. You do this by creating a Schema. I usually put these directly on the Data Transfer Objects (DTOs) or the Entity classes:

use OpenApi\Attributes as OA;

#[OA\Schema(description: "Product model")]
class Product {
    #[OA\Property(description: "The unique identifier of the product", example: 101)]
    public int $id;

    #[OA\Property(description: "The name of the product", example: "Mechanical Keyboard")]
    public string $name;

    #[OA\Property(description: "Current stock level", example: 42)]
    public int $stockQuantity;
}

By doing this, you've created a single source of truth. If you add a price property later, you add one attribute here, and every single endpoint that returns a Product is automatically updated in the documentation.

Mapping Endpoints to Request and Response Types

Now that we have our schema, we need to tell OpenAPI how our controllers use it. This is where you define your paths, methods, and expected responses. I've found that being overly explicit here saves hours of debugging for the people consuming your API.

Instead of a generic "200 OK" response, you can link the response directly to the Product schema we just built. Here is how I would handle a GET request for a specific product:

#[OA\Get(
    path: '/products/{id}',
    summary: 'Get product details',
    tags: ['Inventory'],
    parameters: [
        new OA\Parameter(
            name: 'id',
            in: 'path',
            required: true,
            description: 'The ID of the product to retrieve',
            schema: new OA\Schema(type: 'integer')
        )
    ],
    responses: [
        new OA\Response(
            response: 200,
            description: 'Successful operation',
            content: new OA\JsonContent(ref: '#/components/schemas/Product')
        ),
        new OA\Response(
            response: 404,
            description: 'Product not found'
        )
    ]
)]
public function getProduct(int $id) {
    // Implementation logic here...
}

Notice the ref in the JsonContent. This tells the generator, "Don't redefine the product here; just look at the Product schema we already defined." This keeps your controller clean and your documentation DRY (Don't Repeat Yourself).

Generating and Serving the Specification

Writing the attributes is only half the battle. To actually use this, you need to scan your code and output a openapi.json or openapi.yaml file. You can do this via a CLI command provided by the library, or better yet, create a small internal route in your PHP app that generates it on the fly during development.

Once you have that JSON file, you can plug it into Swagger UI. This transforms that dry JSON into an interactive website where your frontend team can actually click "Try it out," send real requests to your local server, and see the exact response format. It turns the API from a "black box" into a transparent, testable tool. In my experience, this is the single biggest boost you can give to your team's velocity.




📋 Practical Task

Exercise: Documenting a Book Store API

You have been handed a partially completed Book Store API. Your task is to implement OpenAPI documentation using attributes so the frontend team knows how to interact with the bookstore.

Requirements:

  • Create an #[OA\Schema] for a Book class with the following properties: id (integer), title (string), author (string), and isbn (string).
  • Annotate the GET /books/{isbn} method. It should:
    • Take a required isbn parameter in the path.
    • Return a 200 OK response that references the Book schema.
    • Return a 404 Not Found response.
  • Annotate the POST /books method. It should:
    • Accept a RequestBody that references the Book schema.
    • Return a 201 Created response.

Ensure you use OpenApi\Attributes` as OA and correctly link the responses to the schema using the ref property.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.