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

Openapi Laravel Package

api-platform/openapi

Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require api-platform/openapi
    

    Ensure api-platform/core is installed (this package is a dependency).

  2. First Use Case Generate an OpenAPI (Swagger) schema for your API Platform resources:

    use ApiPlatform\OpenApi\Model;
    use ApiPlatform\OpenApi\Factory\OpenApiFactoryInterface;
    
    class CustomOpenApiFactory implements OpenApiFactoryInterface
    {
        public function __invoke(array $context = []): Model
        {
            $openapi = new Model();
            $openapi->info = new Model\Info(
                title: 'My API',
                version: '1.0.0'
            );
    
            // Add paths, components, etc.
            return $openapi;
        }
    }
    
  3. Register the Factory Bind the factory in config/services.php:

    'api_platform.openapi.factory' => \App\OpenApi\CustomOpenApiFactory::class,
    
  4. Access the Schema Fetch the OpenAPI schema via a controller or route:

    use Symfony\Component\HttpFoundation\Response;
    
    return new Response(
        json_encode($this->openApiFactory(), JSON_PRETTY_PRINT),
        Response::HTTP_OK,
        ['Content-Type' => 'application/json']
    );
    

Implementation Patterns

Core Workflows

  1. Extending Default Schema Override or extend the default OpenAPI schema by implementing OpenApiFactoryInterface:

    $openapi = $this->decorated->__invoke($context);
    $openapi->paths->paths['/custom-endpoint'] = new Model\PathItem(...);
    return $openapi;
    
  2. Dynamic Schema Generation Use the $context array to dynamically adjust the schema based on runtime conditions (e.g., environment, user roles):

    if ($context['env'] === 'production') {
        $openapi->servers = [new Model\Server(url: 'https://api.prod.example.com')];
    }
    
  3. Integrating with API Platform Leverage ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface to fetch resource metadata and auto-generate paths, schemas, and operations:

    $resourceMetadataFactory = app(ResourceMetadataFactoryInterface::class);
    $resourceMetadata = $resourceMetadataFactory->create('App\Entity\Book');
    
    $openapi->paths->paths['/api/books'] = new Model\PathItem(
        get: new Model\Operation(ref: '#/components/responses/Book.getCollection')
    );
    
  4. Custom Components Define reusable components (schemas, responses, parameters) in the components section:

    $openapi->components = new Model\Components(
        schemas: [
            'Book' => new Model\Schema(ref: '#/components/schemas/Book'),
        ],
        responses: [
            'BookNotFound' => new Model\Response(ref: '#/components/responses/BookNotFound'),
        ]
    );
    
  5. Security Schemes Add OAuth2, API keys, or other security schemes:

    $openapi->components->securitySchemes = [
        'api_key' => new Model\SecurityScheme(
            type: 'apiKey',
            in: 'header',
            name: 'X-API-KEY'
        ),
    ];
    
  6. Server Configuration Define multiple servers (e.g., dev/staging/prod):

    $openapi->servers = [
        new Model\Server(url: 'https://api.dev.example.com'),
        new Model\Server(url: 'https://api.prod.example.com'),
    ];
    

Integration Tips

  • Symfony Flex Auto-configuration The package auto-registers with API Platform if both are installed. Override via config/packages/api_platform.yaml:

    api_platform:
        openapi:
            enabled: true
            context:
                version: '1.0.0'
    
  • Caching Cache the generated OpenAPI schema to avoid regenerating it on every request:

    $cache = new \Symfony\Component\Cache\SimpleFileCache('/path/to/cache');
    $openapi = $cache->get('openapi_schema', function() use ($context) {
        return $this->openApiFactory()($context);
    });
    
  • Testing Test schema generation in PHPUnit:

    $this->assertArrayHasKey('paths', $openapi->toArray());
    $this->assertEquals('1.0.0', $openapi->info->version);
    

Gotchas and Tips

Common Pitfalls

  1. Schema Validation

    • OpenAPI schemas must adhere to the OpenAPI Specification. Use tools like Swagger Editor to validate manually.
    • Tip: Enable strict validation in the factory:
      $openapi->setStrictValidation(true);
      
  2. Circular References

    • Avoid circular references in $ref fields (e.g., Book schema referencing itself). Use $ref sparingly or break cycles with inline schemas.
  3. Deprecated Features

    • OpenAPI 3.0+ deprecates x- extensions. Replace with extensions or vendor-specific prefixes (e.g., x-api-platform).
  4. Performance Overhead

    • Generating schemas dynamically can be slow. Cache aggressively or pre-generate schemas during deployment.
  5. API Platform Version Mismatch

    • Ensure compatibility between api-platform/core and api-platform/openapi. Check the API Platform docs for version-specific quirks.

Debugging Tips

  1. Inspect Raw Output Dump the raw schema to debug:

    dd($this->openApiFactory()->toArray());
    
  2. Enable Verbose Logging Configure Monolog to log schema generation:

    $logger = new \Monolog\Logger('openapi');
    $logger->pushHandler(new \Monolog\Handler\StreamHandler('/tmp/openapi.log', \Monolog\Logger::DEBUG));
    
  3. Partial Schema Generation Generate only specific parts of the schema (e.g., paths) for debugging:

    $openapi = $this->openApiFactory();
    dd($openapi->paths->toArray());
    

Extension Points

  1. Decorators Use Symfony’s decorator pattern to layer custom logic:

    # config/services.yaml
    App\OpenApi\CustomOpenApiDecorator:
        decorates: 'api_platform.openapi.factory'
        arguments: ['@App\OpenApi\CustomOpenApiDecorator.inner']
    
  2. Event Listeners Listen to kernel.request to modify the schema dynamically:

    use Symfony\Component\HttpKernel\Event\RequestEvent;
    use Symfony\Component\HttpKernel\KernelEvents;
    
    $event->getRequest()->attributes->set('openapi_context', ['custom_key' => 'value']);
    
  3. Custom Model Classes Extend ApiPlatform\OpenApi\Model classes to add custom fields or validation:

    class CustomInfo extends Model\Info
    {
        public string $customField;
    }
    
  4. CLI Generation Generate schemas via a console command for offline use:

    use Symfony\Component\Console\Command\Command;
    use Symfony\Component\Console\Input\InputInterface;
    use Symfony\Component\Console\Output\OutputInterface;
    
    class GenerateOpenApiCommand extends Command
    {
        protected function execute(InputInterface $input, OutputInterface $output): int
        {
            $schema = $this->openApiFactory();
            file_put_contents('openapi.json', json_encode($schema->toArray()));
            return Command::SUCCESS;
        }
    }
    

Configuration Quirks

  1. Context Overrides The $context array passed to the factory can override default values. Ensure consistency:

    $openapi = $this->openApiFactory(['version' => '2.0.0']);
    
  2. Resource Metadata Caching API Platform caches resource metadata. Clear the cache if schema changes aren’t reflected:

    php bin/console cache:clear
    
  3. OpenAPI Version Defaults to OpenAPI 3.1.0. Downgrade if needed:

    $openapi->setVersion('3.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