NelmioApiDocBundle Documentation

repository·5.x·Indexed 25 days ago

https://github.com/nelmio/nelmioapidocbundle

A Symfony bundle for automatically generating OpenAPI/Swagger API documentation. It supports splitting documentation into multiple areas, customizing model names via configuration or PHP 8 attributes, and exporting documentation to JSON, YAML, or HTML via the CLI. It provides integration with various UI controllers including Swagger UI, Redocly, Stoplight, and Scalar.

Tokens
21.1K
Snippets
62
Records
89
Agent score
79%

What's inside NelmioApiDocBundle

  1. Configure documentation areas to filter routes

    5.x

    The areas configuration allows you to create multiple documentation sets by filtering routes based on different criteria. Each area can have its own documentation base, security schemes, and cache settings.

    Area filtering options:

    • path_patterns: A list of regular expressions to match against the route path.
    • host_patterns: A list of regular expressions to match against the route host.
    • name_patterns: A list of regular expressions to match against the route name.
    • with_attribute: If true, only routes with the #[Areas] attribute are documented.
    • disable_default_routes: If true, disables default routes that do not have annotations/attributes.
    • security: Defines security schemes (e.g., Bearer tokens) for the area.
    • documentation: The base OpenAPI/Swagger documentation for this specific area.
    nelmio_api_doc:
        # ...
        areas:
            default:
                path_patterns:
                    - '^/api'
                host_patterns:
                    - '^api\.'
                name_patterns:
                    - '^api_v1'
                with_attribute: false
                security:
                    MyBearerScheme:
                        type: 'http'
                        scheme: 'bearer'
                disable_default_routes: false
                documentation:
                    info:
                        title: 'My App'
                        description: 'My App Description'
                cache:
                    pool: null
                    item_id: null
  2. Split documentation into multiple Areas

    5.x

    You can use the nelmio_api_doc.areas configuration to split your API documentation into several distinct parts (e.g., default, internal, commercial). Each area can have its own filtering rules based on path patterns, host patterns, or route name patterns.

    By default, the default area is used when accessing /api/doc.

    nelmio_api_doc:
        areas:
            default:
                path_patterns: [ ^/api ]
                host_patterns: [ ^api\. ]
            internal:
                path_patterns: [ ^/internal ]
            commercial:
                path_patterns: [ ^/commercial ]
            store:
                # Includes routes with names containing 'store'
                name_patterns: [ store ]
  3. Use serialization groups for validation constraints

    5.x

    You can use the groups option in #[Model] to specify constraint validation groups. This requires enabling use_validation_groups: true in your nelmio_api_doc configuration.

    When enabled, the groups set in the model will apply to both serializer properties and validator constraints. For example, a property marked with #[Assert\NotBlank(groups: ['create'])] will be documented as required in the OpenAPI schema only when the create group is active.

    nelmio_api_doc:
        use_validation_groups: true
  4. How model property extraction works (JMS vs Symfony)

    5.x

    The bundle uses different mechanisms to describe models depending on your serializer:

    1. Symfony PropertyInfo component: Used if you are not using the JMS Serializer. It supports Doctrine attributes, type hints, and PHP doc blocks. It also supports serialization groups via the Symfony serializer.
    2. JMS Serializer: Used by default if the JMS Serializer is present. It uses JMS metadata. Property types must be specified in JMS attributes, though additional info can be extracted from PHP doc blocks.

    Note on JMS Groups: Each permutation of serialization context (e.g., Groups) is treated as a separate Path. This may result in multiple component schemas (e.g., ItemResponse and ItemResponse2) even if the groups are effectively the same. This is by design.

  5. Automatically generate security definitions from #[IsGranted]

    5.x

    Since version 5.2, NelmioApiDocBundle can automatically generate security definitions in your OpenAPI documentation based on the Symfony #[IsGranted] attribute.

    To enable this, you must configure the security scheme(s) per area in your areas configuration. When a controller method uses #[IsGranted(attribute: 'scope')], the bundle will include that security scheme and the specified scope in the generated OpenAPI path definition.

    nelmio_api_doc:
        # ...
    
        areas:
            default:
                security:
                    ApiKeyAuth:
                        type: 'apiKey'
                        name: 'X-API-Key'
                        in: 'header'
  6. How Type and Property Describers work

    5.x

    NelmioApiDocBundle uses describers to generate OpenAPI schemas for properties. There are two main types of describers:

    1. Type Describers: Used for individual properties. They are chained together and executed based on priority. If multiple describers support the same type, they combine their generated schema.
    2. Model Describers: Used for entire models (classes).

    Crucial distinction based on configuration:

    • If type_info is set to true (recommended for Symfony 7.2+), you must implement TypeDescriberInterface. The PropertyDescriberInterface will be ignored.
    • If type_info is set to false, you must implement PropertyDescriberInterface.
  7. How model describers work

    5.x

    Model describers are used to generate the OpenAPI schema for entire classes (models). They are documented in the components.schemas section of the OpenAPI documentation.

    Key behaviors:

    • No Chaining: Unlike type describers, model describers are not chained. Only one model describer will be used for a given model.
    • Priority: If multiple describers support the same model, the one with the highest priority wins.
    • Model vs. Property: Model describers handle the class itself, while property describers handle individual properties within a model.
  8. Inspect NelmioApiDocBundle configuration

    5.x

    You can inspect the configuration of the bundle using Symfony console commands. Use config:dump-reference to see the default configuration values and debug:config to see the actual values currently being used by your application.

    # displays the default config values
    $ php bin/console config:dump-reference nelmio_api_doc
    
    # displays the actual config values used by your application
    $ php bin/console debug:config nelmio_api_doc
    # displays the default config values
    $ php bin/console config:dump-reference nelmio_api_doc
    
    # displays the actual config values used by your application
    $ php bin/console debug:config nelmio_api_doc
  9. Update routing for NelmioApiDocBundle 3.0

    5.x

    In version 3.0, the routing resource was renamed. You must update your routing configuration (e.g., app/config/routing.yml) to point to the new XML file instead of the old YAML file.

    Change the NelmioApiDocBundle resource from @NelmioApiDocBundle/Resources/config/routing.yml to @NelmioApiDocBundle/Resources/config/routing/swaggerui.xml.

    # app/config/routing.yml
    NelmioApiDocBundle:
        resource: "@NelmioApiDocBundle/Resources/config/routing/swaggerui.xml"
        prefix:   /api/doc
  10. Update Swagger-PHP annotations for OpenAPI 3.0

    5.x

    When upgrading to NelmioApiDocBundle 4.0, you must update your PHP annotations because the zircote/swagger-php library changed its namespace from Swagger to OpenApi.

    To simplify the migration, you can keep the SWG alias, but it is recommended to switch to OA and update the annotation prefixes.

    Namespace change:

    • Change use Swagger\Annotations as SWG to use OpenApi\Annotations as OA.
    • Update annotation prefixes from @SWG\... to @OA\....
  11. Refactor Response Schemas to use Media Type annotations

    5.x

    In NelmioApiDocBundle 4.0 (OpenAPI 3.0), you should replace generic @OA\Schema annotations inside a response with explicit media type annotations to ensure the correct Content-Type is set in the documentation.

    • Use @OA\JsonContent(...) instead of @OA\Response(..., @OA\Schema(...)) for JSON responses.
    • Use @OA\XmlContent(...) instead of @OA\Response(..., @OA\Schema(...)) for XML responses.

    Note: If you use the @Model annotation directly (e.g., @OA\Response(..., @Model(...))), the media type defaults to json automatically.

  12. Document query parameters with MapQueryParameter

    5.x

    You can automatically generate documentation for individual query parameters using the Symfony #[MapQueryParameter] attribute.

    To customize the documentation for a specific parameter, add the #[OA//Parameter] attribute to your controller method. You must set in: 'query' and set the name property to match the name of the controller method parameter.

    #[OA//Parameter(
        name: 'id',
        description: 'Some additional parameter description',
        in: 'query',
    )]