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

Swagger Bundle Laravel Package

draw/swagger-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require draw/swagger-bundle
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        Draw\SwaggerBundle\DrawSwaggerBundle::class => ['all' => true],
    ];
    
  2. First Use Case: Annotate a Controller Add @Swagger\Tag and @Swagger\Get annotations to a controller method:

    use Draw\Swagger\Schema\Annotation as Swagger;
    
    class ApiController extends AbstractController
    {
        /**
         * @Swagger\Tag(name="Users")
         * @Swagger\Get(
         *     path="/users",
         *     summary="Get all users",
         *     @Swagger\Response(
         *         response=200,
         *         description="List of users",
         *         @Swagger\Schema(ref="#/definitions/User")
         *     )
         * )
         */
        public function getUsers(): Response
        {
            // ...
        }
    }
    
  3. Generate Documentation Run the command to generate Swagger UI:

    php bin/console draw:swagger:generate
    

    Access the docs at /swagger.


Implementation Patterns

Common Workflows

  1. Documenting API Endpoints Use @Swagger\* annotations for routes, parameters, and responses:

    /**
     * @Swagger\Post(
     *     path="/users",
     *     summary="Create a user",
     *     @Swagger\Parameter(
     *         name="user",
     *         in="body",
     *         required=true,
     *         @Swagger\Schema(ref="#/definitions/User")
     *     ),
     *     @Swagger\Response(
     *         response=201,
     *         description="User created"
     *     )
     * )
     */
    
  2. Defining Schemas Create YAML/JSON schema files in config/swagger/ or inline with @Swagger\Schema:

    # config/swagger/schemas/user.yaml
    definitions:
      User:
        type: object
        properties:
          id: { type: integer }
          name: { type: string }
    
  3. Handling Doctrine Entities Enable Doctrine support in config/packages/draw_swagger.yaml:

    draw_swagger:
        enableDoctrineSupport: true
    

    Use @Swagger\Schema to reference entities:

    @Swagger\Schema(ref="#/definitions/App\Entity\User")
    
  4. Customizing Responses Override default responses with responseConverter:

    draw_swagger:
        responseConverter: true
        schema:
            responses:
                404:
                    description: "Resource not found"
    
  5. Query Parameters Convert query parameters to Swagger attributes:

    draw_swagger:
        convertQueryParameterToAttribute: true
    

Integration Tips

  • Symfony Forms: Use @Swagger\Schema to document form data structures.
  • Event Subscribers: Extend the bundle’s event system to auto-generate docs for dynamic routes.
  • API Platform: Combine with @ApiResource for seamless integration.
  • Testing: Use Draw\Swagger\Extractor\ExtractorInterface to validate docs programmatically.

Gotchas and Tips

Pitfalls

  1. FOSRestBundle Deprecation The bundle no longer supports FOSRestBundle. Migrate to native Symfony routing or use annotations directly.

  2. Doctrine Auto-Detection enableDoctrineSupport: null auto-detects Doctrine, but may fail silently. Explicitly set true/false if issues arise.

  3. Schema Validation The schema config is not validated—ensure it matches Swagger 2.0 format to avoid runtime errors.

  4. Annotation Parsing Annotations must be parsed by the bundle’s extractor. Ensure:

    • Controllers extend Symfony\Bundle\FrameworkBundle\Controller\AbstractController.
    • Annotations are placed above the method, not the class.
  5. Circular References Avoid circular references in schemas (e.g., User referencing Order which references User). Use ref sparingly.


Debugging

  • Check Extracted Data Dump the extracted schema before generation:
    php bin/console debug:swagger:extract
    
  • Validate Swagger Use Swagger Editor to validate the generated JSON/YAML.
  • Clear Cache After config changes, clear the cache:
    php bin/console cache:clear
    

Extension Points

  1. Custom Extractors Implement Draw\Swagger\Extractor\ExtractorInterface to add support for custom annotations or services.

  2. Post-Processing Override the Draw\SwaggerBundle\EventListener\GenerateEvent to modify the generated schema:

    use Draw\SwaggerBundle\Event\GenerateEvent;
    
    $event->setSchema(array_merge($event->getSchema(), ['custom' => 'field']));
    
  3. Schema Aliases Use definitionAliases to simplify FQCNs in docs:

    draw_swagger:
        definitionAliases:
            - { class: App\Entity\User, alias: User }
    
  4. Dynamic Documentation Generate docs on-demand via a custom command:

    use Draw\Swagger\Generator;
    
    $generator = new Generator();
    $schema = $generator->generate();
    file_put_contents('api-docs.json', json_encode($schema));
    

Pro Tips

  • Use @Swagger\Parameter for Path/Query/Headers Differentiate parameter types with in="path", in="query", etc.
  • Leverage @Swagger\Example Add examples for complex requests/responses:
    @Swagger\Parameter(
        @Swagger\Example(
            summary="Example user",
            value={"id": 1, "name": "John Doe"}
        )
    )
    
  • Versioning Include API versions in the schema.info.version field for clarity.
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