Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Api Doc Bundle Laravel Package

corponat/api-doc-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require nelmio/api-doc-bundle
    

    Ensure NelmioApiDocBundle is enabled in config/bundles.php:

    Nelmio\ApiDocBundle\NelmioApiDocBundle::class => ['all' => true],
    
  2. 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'
    
  3. 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.


Implementation Patterns

Common Workflows

  1. 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
    {
        // ...
    }
    
  2. Grouping Endpoints: Use @ApiDoc at the class level to group related endpoints:

    /**
     * @ApiDoc(
     *     section="Users",
     *     description="User management endpoints"
     * )
     */
    class UserController extends AbstractController
    {
        // ...
    }
    
  3. Dynamic Documentation: Extend the bundle to fetch docs from external sources (e.g., database) by implementing Nelmio\ApiDocBundle\Resolver\DocResolverInterface.

  4. 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]
    
  5. Authentication: Secure docs with annotations:

    nelmio_api_doc:
        authentication:
            entry_point: /api/login
            key: api_key
    

Integration Tips

  • Symfony Flex: Use symfony/flex to auto-configure the bundle.
  • Doctrine Entities: Leverage nelmio/api-doc-bundle's support for Doctrine metadata to auto-generate schemas for request/response bodies.
  • Event Listeners: Extend doc generation via Nelmio\ApiDocBundle\EventListener\DocListener.
  • Custom Templates: Override Twig templates in templates/NelmioApiDocBundle/ for branding.
  • API Versioning: Use area in config to separate docs by API version (e.g., v1, v2).

Gotchas and Tips

Pitfalls

  1. Annotation Parsing:

    • Issue: Annotations may not parse if PHP attributes are used (prefer annotations for compatibility).
    • Fix: Ensure doctrine/annotations is installed and autoloaded.
  2. Caching:

    • Issue: Docs may not update immediately due to caching.
    • Fix: Clear cache after changes:
      php bin/console cache:clear
      
  3. OpenAPI 3.0 Migration:

    • Issue: Version 4.0 uses OpenAPI 3.0 by default (breaking change from Swagger 2.0).
    • Fix: Stick to nelmio/api-doc-bundle:3.x for Swagger 2.0 or update annotations to OpenAPI 3.0 syntax.
  4. Circular References:

    • Issue: Complex object graphs may cause infinite loops in schema generation.
    • Fix: Use @ApiDoc to explicitly define schemas or limit depth with maxDepth in config.
  5. Route Conflicts:

    • Issue: Docs may override existing routes if /api/doc conflicts.
    • Fix: Customize the route in config:
      nelmio_api_doc:
          route_prefix: 'docs'
          routes:
              api_doc: '/custom-docs'
      

Debugging

  • 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());
    }
    

Extension Points

  1. 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'
    
  2. Dynamic Parameters: Use Nelmio\ApiDocBundle\Annotation\ApiDoc with parameters to define dynamic schemas:

    /**
     * @ApiDoc(
     *     parameters={
     *         {"name":"filter", "dataType":"string", "required":false, "description":"Filter users"}
     *     }
     * )
     */
    
  3. Security Schemes: Extend securitySchemes in config for OAuth2/JWT:

    nelmio_api_doc:
        documentation:
            components:
                securitySchemes:
                    oauth2:
                        type: oauth2
                        flows:
                            password:
                                tokenUrl: /oauth/token
                                scopes: {}
    
  4. Custom Annotations: Create a trait for reusable doc blocks:

    trait ApiDocTrait
    {
        /**
         * @ApiDoc(...)
         */
        public function commonDoc(): void {}
    }
    

Configuration Quirks

  • 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.

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware