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

nelmio/api-doc-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require nelmio/api-doc-bundle
    

    Add to config/bundles.php:

    Nelmio\ApiDocBundle\NelmioApiDocBundle::class => ['all' => true],
    
  2. Enable in 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 with @ApiDoc:

    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 the user is not found"
         *     }
         * )
         */
        public function getUser(int $id): JsonResponse
        {
            // ...
        }
    }
    

    Access docs at /api/doc.


Implementation Patterns

Core Workflows

  1. Annotation-Based Documentation: Use @ApiDoc, @ApiFilter, @ApiProperty, and @ApiParam on controllers, entities, and DTOs. Example for filtering:

    /**
     * @ApiFilter(
     *     filterClass=Nelmio\ApiDocBundle\Annotation\Filter\SearchFilter::class,
     *     properties={
     *         "name"="name",
     *         "email"="email"
     *     }
     * )
     */
    public function searchUsers(): JsonResponse
    
  2. Swagger/OpenAPI Integration: Leverage OpenAPI annotations for richer docs:

    /**
     * @OA\Get(
     *     path="/users/{id}",
     *     summary="Get user details",
     *     @OA\Parameter(
     *         name="id",
     *         in="path",
     *         required=true,
     *         @OA\Schema(type="integer")
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="User details",
     *         @OA\JsonContent(ref="#/components/schemas/User")
     *     )
     * )
     */
    
  3. Dynamic Documentation: Use NelmioApiDocBundle\EventListener\DocumentationListener to inject docs programmatically:

    $this->get('nelmio_api_doc.documentation')->addResource(
        new Resource('GET', '/dynamic-endpoint', 'Dynamic Endpoint')
    );
    
  4. Authentication & Security: Define security schemes in config:

    nelmio_api_doc:
        areas:
            path_patterns:
                - ^/api(?!/doc)
        securityDefinitions:
            Bearer:
                type: apiKey
                name: Authorization
                in: header
    
  5. Custom Schemas: Define reusable schemas in YAML:

    nelmio_api_doc:
        models:
            User:
                type: object
                properties:
                    id: { type: integer }
                    name: { type: string }
    

Integration Tips

  • Symfony Flex: Use symfony/flex recipes for seamless setup.
  • API Platform: Works alongside api-platform/core for hybrid docs.
  • Testing: Mock docs in tests with Nelmio\ApiDocBundle\Tests\Fixtures.
  • CI/CD: Generate and validate docs in pipelines using nelmio/api-doc-bundle:validate.

Gotchas and Tips

Pitfalls

  1. Annotation Conflicts:

    • Issue: @ApiDoc and @OA\* annotations may conflict.
    • Fix: Prioritize one format (e.g., OpenAPI) and use nelmio_api_doc.openapi.enabled: true in config.
  2. Caching Headaches:

    • Issue: Docs may not update after changes.
    • Fix: Clear cache (php bin/console cache:clear) or disable caching in config:
      nelmio_api_doc:
          documentation:
              cache: false
      
  3. Route Overrides:

    • Issue: Custom routes may not appear in docs.
    • Fix: Ensure routes are loaded before the NelmioApiDocBundle listener:
      // config/routes.yaml
      api_doc:
          resource: "@NelmioApiDocBundle/Resources/config/routing.yaml"
          prefix: /api/doc
      
  4. Deprecated Annotations:

    • Issue: Older annotations (e.g., @ApiParam) may not work in v5+.
    • Fix: Migrate to OpenAPI annotations or update to latest Nelmio syntax.
  5. CORS Misconfigurations:

    • Issue: Docs UI may block requests.
    • Fix: Configure CORS for /api/doc in your frontend or backend.

Debugging

  1. Enable Verbose Logging:

    nelmio_api_doc:
        documentation:
            debug: true
    

    Logs appear in var/log/dev.log.

  2. Validate OpenAPI: Use the validate command:

    php bin/console nelmio:api-doc:validate
    
  3. Inspect Resources: Dump loaded resources in a controller:

    $resources = $this->get('nelmio_api_doc.documentation')->getResources();
    dd($resources);
    

Extension Points

  1. Custom Event Listeners: Extend documentation generation via events:

    // src/EventListener/CustomDocListener.php
    class CustomDocListener implements EventSubscriber
    {
        public static function getSubscribedEvents()
        {
            return [
                NelmioApiDocBundle\Event\DocumentationEvent::class => 'onDocumentation',
            ];
        }
    
        public function onDocumentation(DocumentationEvent $event)
        {
            $event->getDocumentation()->addResource(new Resource('GET', '/custom', 'Custom Endpoint'));
        }
    }
    
  2. Override Templates: Customize the docs UI by overriding Twig templates in templates/bundles/NelmioApiDocBundle/.

  3. Dynamic Schema Generation: Use Nelmio\ApiDocBundle\Generator\SchemaGeneratorInterface to generate schemas at runtime.

  4. Webpack Encore Integration: Serve static docs via Webpack for SPAs:

    // webpack.config.js
    Encore.addEntry('api-doc', './vendor/nelmio/api-doc-bundle/Resources/public/js/api-doc.js');
    
  5. API Versioning: Use sub-bundles or config overrides per version:

    # config/packages/dev/nelmio_api_doc_v1.yaml
    nelmio_api_doc:
        documentation:
            info:
                title: 'API v1'
                version: '1.0.0'
    
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