Swagger/OpenAPI Generation for PHP: Automating API Documentation
Swagger (now OpenAPI) is a standard for describing RESTful APIs that allows developers, clients, and automated tools to understand the capabilities of a service without access to the source code. For PHP developers, the key tool is the zircote/swagger-php library (formerly known as swagger-php), which automatically generates an OpenAPI specification from annotations in the code.
What is zircote/swagger-php?
This is the main library for generating OpenAPI specifications in PHP. It analyzes PHPDoc annotations in controllers, models, and routes, creating a JSON/YAML file that can be used for:
- Automatic documentation generation (Swagger UI, ReDoc)
- Generating client libraries for various languages
- API testing (Postman, Insomnia)
- Request and response validation
Installation and Setup
Installation via Composer:
composer require zircote/swagger-phpMinimal configuration for Laravel (or any framework) involves creating annotations in the controller. Example of a simple controller with OpenAPI annotations:
<?php
namespace App\\Http\\Controllers\\Api;
use OpenApi\\Annotations as OA;
/** * @OA\\Info(title="My API", version="1.0.0") * @OA\\Server(url="https://api.example.com") */class UserController extends Controller{ /** * @OA\\Get( * path="/api/users/{id}", * summary="Get user by ID", * @OA\\Parameter( * name="id", * in="path", * required=true, * @OA\\Schema(type="integer") * ), * @OA\\Response( * response=200, * description="Successful response", * @OA\\JsonContent(ref="#/components/schemas/User") * ), * @OA\\Response(response=404, description="User not found") * ) */ public function show($id) { // logic }}Generating the Specification
To create the OpenAPI file, run the command:
vendor/bin/openapi src -o public/openapi.yamlOr use PHP code:
<?php
use OpenApi\\Generator;
$openapi = Generator::scan(['/path/to/project/src']);file_put_contents('public/openapi.json', $openapi->toJson());Advanced Features
The library supports:
- Nested schemas — automatic creation of models from annotations
- Endpoint grouping via @OA\\Tag
- Security — @OA\\SecurityScheme for JWT, OAuth2
- Request examples — @OA\\RequestBody with examples
Example model with annotations:
<?php
/** * @OA\\Schema( * schema="User", * required={"id", "email"}, * @OA\\Property(property="id", type="integer", format="int64"), * @OA\\Property(property="email", type="string", format="email"), * @OA\\Property(property="name", type="string"), * @OA\\Property(property="created_at", type="string", format="date-time") * ) */class User{ // properties}Integration with Frameworks
For Laravel, there is the package darkaonline/l5-swagger, which adds:
- Automatic generation on each request
- Built-in Swagger UI
- Configuration via config file
Installation:
composer require darkaonline/l5-swaggerphp artisan vendor:publish --provider="L5Swagger\\L5SwaggerServiceProvider"For Symfony, use nelmio/api-doc-bundle.