Installation:
composer require nelmio/api-doc-bundle
Ensure NelmioApiDocBundle is enabled in config/bundles.php:
Nelmio\ApiDocBundle\NelmioApiDocBundle::class => ['all' => true],
Basic Configuration:
Add to config/packages/nelmio_api_doc.yaml:
nelmio_api_doc:
documentation:
info:
title: 'My API'
description: 'API Documentation'
version: '1.0.0'
First Use Case: Annotate a controller method to generate API docs:
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
class UserController extends AbstractController
{
/**
* @ApiDoc(
* resource=true,
* description="Get a user by ID",
* requirements={
* {"name":"id", "dataType":"integer", "requirement":"\d+"}
* },
* statusCodes={
* 200="Returned when successful",
* 404="Returned when user not found"
* }
* )
*/
public function getUser(int $id): JsonResponse
{
// ...
}
}
Access docs at /api/doc.
Controller Annotations:
Use @ApiDoc on methods to define:
resource: Marks as a resource endpoint (e.g., /users).description: Human-readable description.requirements: URL parameter validation (regex).statusCodes: Expected HTTP responses.filters: Query parameter definitions.parameters: Request body or form data schemas.Example for POST with body:
/**
* @ApiDoc(
* description="Create a user",
* input="Nelmio\ApiDocBundle\Annotation\ApiDoc::class",
* statusCodes={
* 201="User created",
* 400="Invalid input"
* }
* )
*/
public function postUser(Request $request): JsonResponse
{
// ...
}
Grouping Endpoints:
Use @ApiDoc at the class level to group related endpoints:
/**
* @ApiDoc(
* section="Users",
* description="User management endpoints"
* )
*/
class UserController extends AbstractController
{
// ...
}
Dynamic Documentation:
Extend the bundle to fetch docs from external sources (e.g., database) by implementing Nelmio\ApiDocBundle\Resolver\DocResolverInterface.
Swagger UI Integration:
Enable Swagger UI in nelmio_api_doc.yaml:
nelmio_api_doc:
areas: # Limit to specific areas (e.g., ["api"])
documentation:
components:
securitySchemes:
bearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
swagger:
versions: [3]
Authentication: Secure docs with annotations:
nelmio_api_doc:
authentication:
entry_point: /api/login
key: api_key
symfony/flex to auto-configure the bundle.nelmio/api-doc-bundle's support for Doctrine metadata to auto-generate schemas for request/response bodies.Nelmio\ApiDocBundle\EventListener\DocListener.templates/NelmioApiDocBundle/ for branding.area in config to separate docs by API version (e.g., v1, v2).Annotation Parsing:
doctrine/annotations is installed and autoloaded.Caching:
php bin/console cache:clear
OpenAPI 3.0 Migration:
nelmio/api-doc-bundle:3.x for Swagger 2.0 or update annotations to OpenAPI 3.0 syntax.Circular References:
@ApiDoc to explicitly define schemas or limit depth with maxDepth in config.Route Conflicts:
/api/doc conflicts.nelmio_api_doc:
route_prefix: 'docs'
routes:
api_doc: '/custom-docs'
Enable Debug Mode:
nelmio_api_doc:
debug: true
Logs raw doc generation to var/log/dev.log.
Validate OpenAPI:
Use tools like Swagger Editor to validate the generated api_doc.json (output at /api/doc.json).
Check Event Dispatching:
Override Nelmio\ApiDocBundle\Event\DocEvent to inspect doc generation:
// src/EventListener/CustomDocListener.php
public function onDoc(DocEvent $event) {
dump($event->getDoc());
}
Custom Doc Resolver:
Implement DocResolverInterface to fetch docs from non-annotated sources (e.g., YAML files):
class YamlDocResolver implements DocResolverInterface
{
public function resolve(): array
{
return yaml_parse(file_get_contents('docs/api.yaml'));
}
}
Register in services.yaml:
Nelmio\ApiDocBundle\Resolver\DocResolverInterface: '@app.yaml_doc_resolver'
Dynamic Parameters:
Use Nelmio\ApiDocBundle\Annotation\ApiDoc with parameters to define dynamic schemas:
/**
* @ApiDoc(
* parameters={
* {"name":"filter", "dataType":"string", "required":false, "description":"Filter users"}
* }
* )
*/
Security Schemes:
Extend securitySchemes in config for OAuth2/JWT:
nelmio_api_doc:
documentation:
components:
securitySchemes:
oauth2:
type: oauth2
flows:
password:
tokenUrl: /oauth/token
scopes: {}
Custom Annotations: Create a trait for reusable doc blocks:
trait ApiDocTrait
{
/**
* @ApiDoc(...)
*/
public function commonDoc(): void {}
}
Area Limitation:
Use areas to restrict docs to specific routes (e.g., ["api"]), but ensure routes are properly namespaced.
Default Values:
Override defaults in nelmio_api_doc.yaml:
nelmio_api_doc:
documentation:
default:
tags:
- name: "Default"
description: "Default endpoints"
JSON Output:
Access raw OpenAPI spec at /api/doc.json for CI/CD validation.
PHP 8 Attributes:
While the bundle supports annotations, PHP 8 attributes may require additional setup (e.g., php-attributes package). Stick to annotations for stability.
How can I help you explore Laravel packages today?