PHP
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions
-
Section 4: Object-Oriented PHP
-
Section 5: Working with Data
-
Section 6: Modern PHP (PHP 8)
-
Section 7: Working with Files and Networking
-
Section 8: Common PHP Frameworks Overview
-
Section 9: Tooling and Ecosystem
-
Section 10: Practical Projects
-
Section 11: Interview Practice
-
Section 12: More Standard Library
-
Section 13: Data Structures and Algorithms in PHP
-
Section 14: More Practice Exercises
-
Section 15: More Security and Best Practices
-
Section 16: More Testing and Tooling
-
Section 17: WordPress-Style CMS Concepts
-
Section 18: Advanced OOP Practice
-
Section 19: More Web Fundamentals
-
Section 20: Database Practice
-
Section 21: PHP Manual: Array Functions
-
Section 22: PHP Manual: Date and Calendar Functions
-
Section 23: PHP Manual: Filesystem and Directory Functions
-
Section 24: PHP Manual: Filter and Var Handling
-
Section 25: PHP Manual: Math Functions
-
Section 26: PHP Manual: JSON and XML
-
Section 27: PHP Manual: Network and Stream Functions
-
Section 28: PHP Manual: Error and Exception Handling
-
Section 29: PHP Manual: Output Control and Misc
-
Section 30: PHP Manual: FTP, Zip, and Mail
-
Section 31: Modern PHP Frameworks Deep Dive
-
Section 32: PHP Design Patterns
-
Section 33: More Practice Exercises
-
Section 34: PHP Performance and Deployment
-
Section 35: More Interview Practice
-
Section 36: More PHP Standard Library
-
Section 37: PHP Concurrency and Async
-
Section 38: More Web Development Practice
-
Section 39: PHP Testing Deep Dive
-
Section 40: Composer and Package Development
-
Section 41: PHP Security Deep Dive
-
Section 42: More Practical Projects
-
Section 43: Legacy PHP Maintenance
-
Section 44: More Algorithm Practice
-
Section 45: Final Practice and Review
-
Section 46: PHP for E-Commerce Patterns
-
Section 47: PHP API Design Deep Dive
-
Section 48: PHP Caching Strategies
-
Section 49: PHP Queue and Background Jobs
-
Section 50: PHP Multi-Tenancy Patterns
-
Section 51: PHP Real-Time Features
-
Section 52: PHP CMS and Content Modeling
-
Section 53: PHP Internationalization
-
Section 54: More Framework-Specific Practice
-
Section 55: PHP Legacy Code Refactoring
-
Section 56: More Practice Projects Round 2
-
Section 57: PHP Command-Line Applications
-
Section 58: PHP and Microservices
-
Section 59: More Interview and Review Round 2
199: API Documentation with OpenAPI in PHP
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 aBookclass with the following properties:id(integer),title(string),author(string), andisbn(string). - Annotate the
GET /books/{isbn}method. It should:- Take a required
isbnparameter in the path. - Return a
200 OKresponse that references theBookschema. - Return a
404 Not Foundresponse.
- Take a required
- Annotate the
POST /booksmethod. It should:- Accept a
RequestBodythat references theBookschema. - Return a
201 Createdresponse.
- Accept a
Ensure you use OpenApi\Attributes` as OA and correctly link the responses to the schema using the ref property.
There are no comments for now.