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

Open Api Bundle Laravel Package

draw/open-api-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require draw/open-api-bundle
    

    Add the bundle to config/bundles.php:

    return [
        // ...
        Draw\OpenApiBundle\DrawOpenApiBundle::class => ['all' => true],
    ];
    
  2. First Use Case: Annotate a controller method to generate OpenAPI v2 documentation:

    use OpenApi\Annotations as OA;
    
    class UserController extends AbstractController
    {
        /**
         * @OA\Get(
         *     path="/users/{id}",
         *     summary="Get a user",
         *     @OA\Parameter(
         *         name="id",
         *         in="path",
         *         required=true,
         *         @OA\Schema(type="integer")
         *     ),
         *     @OA\Response(
         *         response=200,
         *         description="User details",
         *         @OA\JsonContent(ref="#/definitions/User")
         *     )
         * )
         */
        public function getUser(int $id): JsonResponse
        {
            // ...
        }
    }
    
  3. Generate Documentation:

    bin/console draw:open-api:generate
    

    Output will be saved to public/api-docs.json.


Implementation Patterns

Common Workflows

  1. Documenting Controllers: Use @OA\* annotations to define endpoints, parameters, responses, and schemas. Example for POST with request body:

    /**
     * @OA\Post(
     *     path="/users",
     *     summary="Create a user",
     *     @OA\RequestBody(
     *         required=true,
     *         @OA\JsonContent(ref="#/definitions/User")
     *     ),
     *     @OA\Response(
     *         response=201,
     *         description="User created",
     *         @OA\JsonContent(ref="#/definitions/User")
     *     )
     * )
     */
    
  2. Reusing Schemas: Define schemas in a separate file (e.g., src/OpenApi/Schemas/User.php) and reference them:

    namespace App\OpenApi\Schemas;
    
    use OpenApi\Annotations as OA;
    
    

/**

  • @OA\Schema(
  • schema="User",
    
  • required={"name", "email"},
    
  • @OA\Property(property="id", type="integer"),
    
  • @OA\Property(property="name", type="string"),
    
  • @OA\Property(property="email", type="string", format="email")
    
  • ) */
    
    
  1. Doctrine Integration: Enable auto-detection of Doctrine entities for schema generation:

    draw_open_api:
        enableDoctrineSupport: true
    

    Annotate entities to generate schemas automatically:

    /**
     * @OA\Schema()
     */
    class User {}
    
  2. REST API Without FOSRest: Use the bundle’s built-in response converters to serialize entities:

    use Draw\OpenApiBundle\Serializer\OpenApiResponse;
    
    public function getUser(int $id): OpenApiResponse
    {
        return $this->openApiResponse(new User());
    }
    

Integration Tips

  • Symfony Serializer: Ensure symfony/serializer is installed for response conversion.
  • Swagger UI: Serve api-docs.json via a route and integrate with Swagger UI.
  • Custom Extractors: Extend the bundle’s extractors (e.g., for custom annotations or traits) by implementing Draw\Component\OpenApi\Extractor\ExtractorInterface.

Gotchas and Tips

Pitfalls

  1. Doctrine Auto-Detection:

    • If enableDoctrineSupport is null, the bundle auto-detects Doctrine, but this may fail in complex setups (e.g., multiple Doctrine instances). Explicitly set true/false if issues arise.
  2. Circular References:

    • Doctrine entities with circular references (e.g., User hasMany Post, Post belongsTo User) may cause infinite recursion in schema generation. Use @OA\Property(ref="#/definitions/User") to break cycles.
  3. Annotation Parsing:

    • Annotations must be parsed before generating docs. Run bin/console draw:open-api:generate after changes, not during runtime.
  4. Response Conversion:

    • The responseConverter option (false by default) requires symfony/serializer and proper normalization logic. Enable it only if you’ve configured serializers for your entities.

Debugging

  • Generate Raw JSON: Use bin/console draw:open-api:generate --raw to inspect the generated OpenAPI spec without formatting.
  • Check Extractors: Run bin/console debug:container draw.open_api.extractor to list available extractors and debug issues.
  • Logs: Enable debug mode (APP_DEBUG=1) to see detailed extraction logs.

Configuration Quirks

  1. convertQueryParameterToAttribute:

    • When true, query parameters (e.g., ?filter[name]=John) are converted to attributes in the schema. Useful for filtering but may not align with your API design.
  2. definitionAliases:

    • Aliases replace class references in the schema (e.g., App\Entity\UserUser). Ensure aliases are unique and don’t conflict with built-in OpenAPI definitions.
  3. Sandbox Installation:

    • The sandbox (draw:open-api:install-sandbox) installs a local copy of draw/open-api for testing. Avoid using it in production; prefer stable Composer versions.

Extension Points

  1. Custom Annotations: Extend the bundle by creating custom annotations and registering them with the AnnotationExtractor. Example:

    // src/OpenApi/Annotation/CustomAnnotation.php
    namespace App\OpenApi\Annotation;
    use OpenApi\Annotations as OA;
    
    #[Attribute]
    class CustomAnnotation extends OA\Annotation {}
    
  2. Event Listeners: Subscribe to draw.open_api.generate events to modify the spec dynamically:

    // src/EventListener/OpenApiListener.php
    namespace App\EventListener;
    
    use Draw\Component\OpenApi\Event\GenerateEvent;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class OpenApiListener implements EventSubscriberInterface
    {
        public static function getSubscribedEvents(): array
        {
            return [
                GenerateEvent::class => 'onGenerate',
            ];
        }
    
        public function onGenerate(GenerateEvent $event): void
        {
            $event->getSpec()->info->title = 'My Custom API';
        }
    }
    
  3. Schema Factories: Override schema generation for specific classes by implementing Draw\Component\OpenApi\Factory\SchemaFactoryInterface.

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