main Configuration Reference

# Symfony Configuration

Here’s the complete configuration of API Platform for Symfony including default values:

# api/config/packages/api_platform.yaml
api_platform:

    # The title of the API.
    title: 'API title'

    # The description of the API.
    description: 'API description'

    # The version of the API.
    version: '0.0.0'

    # Set this to false if you want Webby to disappear.
    show_webby: true

    # Specify a name converter to use.
    name_converter: ~

    # Specify an asset package name to use.
    asset_package: null

    # Specify a path name generator to use.
    path_segment_name_generator: 'api_platform.path_segment_name_generator.underscore'

    validator:
        # Enable the serialization of payload fields when a validation error is thrown.
        # If you want to serialize only some payload fields, define them like this: [ severity, anotherPayloadField ]
        serialize_payload_fields: []

    eager_loading:
        # To enable or disable eager loading.
        enabled: true

        # Fetch only partial data according to serialization groups.
        # If enabled, Doctrine ORM entities will not work as expected if any of the other fields are used.
        fetch_partial: false

        # Max number of joined relations before EagerLoading throws a RuntimeException.
        max_joins: 30

        # Force join on every relation.
        # If disabled, it will only join relations having the EAGER fetch mode.
        force_eager: true

    # Enable the Swagger documentation and export.
    enable_swagger: true

    # Enable Swagger UI.
    enable_swagger_ui: true

    # Enable ReDoc.
    enable_re_doc: true

    # Enable the entrypoint.
    enable_entrypoint: true

    # Enable the docs.
    enable_docs: true

    # Skip response body construction on HEAD requests so collections are not iterated.
    # Disable to process HEAD identically to GET.
    enable_head_request_optimization: true

    # Enable the data collector and the WebProfilerBundle integration.
    enable_profiler: true

   collection:
        # The name of the query parameter to filter nullable results (with the ExistsFilter).
        exists_parameter_name: 'exists'

        # The default order of results.
        order: 'ASC'

        # The name of the query parameter to order results (with the OrderFilter).
        order_parameter_name: 'order'

        pagination:
            # The default name of the parameter handling the page number.
            page_parameter_name: 'page'

            # The name of the query parameter to enable or disable pagination.
            enabled_parameter_name: 'pagination'

            # The name of the query parameter to set the number of items per page.
            items_per_page_parameter_name: 'itemsPerPage'

            # The name of the query parameter to enable or disable the partial pagination.
            partial_parameter_name: 'partial'

    mapping:
        # The list of paths with files or directories where the bundle will look for additional resource files.
        paths: []

    doctrine:
        # To enable or disable Doctrine ORM support.
        enabled: true

    doctrine_mongodb_odm:
        # To enable or disable Doctrine MongoDB ODM support.
        enabled: false

    oauth:
        # To enable or disable OAuth.
        enabled: false

        # The OAuth client ID.
        clientId: ''

        # The OAuth client secret.
        clientSecret: ''

        # The OAuth type.
        type: 'oauth2'

        # The OAuth flow grant type.
        flow: 'application'

        # The OAuth token URL. Make sure to check the specification tokenUrl is not needed for an implicit flow.
        tokenUrl: ''

        # The OAuth authentication URL.
        authorizationUrl: ''

        # The OAuth scopes.
        scopes: []

    graphql:
        # Enabled by default with installed api-platform/graphql.
        enabled: false

        # The default IDE (graphiql) used when going to the GraphQL endpoint. False to disable.
        default_ide: 'graphiql'

        graphiql:
            # Enabled by default with installed api-platform/graphql and Twig.
            enabled: false

        introspection:
            # Enabled by default with installed api-platform/graphql.
            enabled: true

        # The nesting separator used in the filter names.
        nesting_separator: _

        collection:
            pagination:
                enabled: true

    swagger:
        # The active versions of OpenAPI to be exported or used in the swagger_ui. The first value is the default.
        versions: [2, 3]

        # The swagger API keys.
        api_keys: []
            # The name of the header or query parameter containing the API key.
            # name: ''

            # Whether the API key should be a query parameter or a header.
            # type: 'query' or 'header'

        swagger_ui_extra_configuration:
            # Controls the default expansion setting for the operations and tags. It can be 'list' (expands only the tags), 'full' (expands the tags and operations) or 'none' (expands nothing).
            docExpansion: list
            # If set, enables filtering. The top bar will show an edit box that you can use to filter the tagged operations that are shown.
            filter: false
            # You can use any other configuration parameters too.

    openapi:
        # The contact information for the exposed API.
        contact:
            # The identifying name of the contact person/organization.
            name:
            # The URL pointing to the contact information. MUST be in the format of a URL.
            url:
            # The email address of the contact person/organization. MUST be in the format of an email address.
            email:
        # A URL to the Terms of Service for the API. MUST be in the format of a URL.
        termsOfService:
        # The license information for the exposed API.
        license:
            # The license name used for the API.
            name:
            # URL to the license used for the API. MUST be in the format of a URL.
            url:

    http_cache:
        # To make all responses public by default.
        public: ~

        invalidation:
            # To enable the tags-based cache invalidation system.
            enabled: false

            # URLs of the Varnish servers to purge using cache tags when a resource is updated.
            urls: []

            # To pass options to the client charged with the request.
            request_options: []

            # Use another service as the purger for example "api_platform.http_cache.purger.varnish.xkey"
            purger: 'api_platform.http_cache.purger.varnish.ban'

    mercure:
        # Enabled by default with installed symfony/mercure-bundle.
        enabled: false

        # The URL sent in the Link HTTP header. If not set, will default to MercureBundle's default hub URL.
        hub_url: null

    messenger:
        # Enabled by default with installed symfony/messenger and not installed symfony/symfony.
        enabled: false

    elasticsearch:
        # To enable or disable Elasticsearch support.
        enabled: false

        # The hosts to the Elasticsearch nodes.
        hosts: []

        # The mapping between resource classes and indexes.
        mapping: []

    # The list of exceptions mapped to their HTTP status code.
    exception_to_status:
        # With a status code.
        Symfony\Component\Serializer\Exception\ExceptionInterface: 400

        # Or with a constant defined in the 'Symfony\Component\HttpFoundation\Response' class.
        ApiPlatform\Exception\InvalidArgumentException: !php/const Symfony\Component\HttpFoundation\Response::HTTP_BAD_REQUEST

        ApiPlatform\Exception\FilterValidationException: 400

        Doctrine\ORM\OptimisticLockException: 409

        # ...

    # The list of enabled formats. The first one will be the default.
    formats:
        jsonld:
            mime_types: ['application/ld+json']

        json:
            mime_types: ['application/json']

        html:
            mime_types: ['text/html']

        # ...

    # The list of enabled patch formats. The first one will be the default.
    patch_formats: []

    # The list of enabled docs formats. The first one will be the default.
    docs_formats:
        jsonld: ['application/ld+json']
        #jsonapi: ['application/vnd.api+json']
        jsonopenapi: ['application/vnd.openapi+json']
        html: ['text/html']

    # The list of enabled error formats. The first one will be the default.
    error_formats:
        jsonproblem:
            mime_types: ['application/problem+json']

        jsonld:
            mime_types: ['application/ld+json']

        # ...

    # Global resources defaults, see in the next section.
    defaults:
        # ...

# Global Resources Defaults for Symfony

If you need to globally configure all the resources instead of adding configuration in each one, it’s possible to do so with the defaults key:

# api/config/packages/api_platform.yaml
api_platform:
    defaults:
        description: ~
        iri: ~
        short_name: ~
        operations: ~

        graphql: ~

        elasticsearch: ~

        security: ~
        security_message: ~
        security_post_denormalize: ~
        security_post_denormalize_message: ~

        cache_headers:
            # Automatically generate etags for API responses.
            etag: true

            # Default value for the response max age.
            max_age: 3600

            # Default value for the response shared (proxy) max age.
            shared_max_age: 3600

            # Default values of the "Vary" HTTP header.
            vary: ["Accept"]

            invalidation:
                xkey:
                    glue: " "

        normalization_context:
            # Default value to omit null values in conformance with the JSON Merge Patch RFC.
            skip_null_values: true

            # Set to false to disable the generation of Skolem IRIs (`/.well-known/genid/{id}`) globally.
            # Available since API Platform 4.3, see the serialization documentation.
            gen_id: true
        denormalization_context: ~
        swagger_context: ~
        openapi_context: ~
        deprecation_reason: ~
        fetch_partial: ~
        force_eager: ~
        formats: ~
        filters: ~
        hydra_context: ~
        mercure: ~
        messenger: ~
        order: ~

        # To enable or disable pagination for all resource collections.
        pagination_enabled: true

        # To allow the client to enable or disable the pagination.
        pagination_client_enabled: false

        # To allow the client to set the number of items per page.
        pagination_client_items_per_page: false

        # To allow the client to enable or disable the partial pagination.
        pagination_client_partial: false

        # The default number of items per page.
        pagination_items_per_page: 30

        # The maximum number of items per page.
        pagination_maximum_items_per_page: ~

        # To allow partial pagination for all resource collections.
        # This improves performances by skipping the `COUNT` query.
        pagination_partial: false

        # To use cursor-based pagination.
        pagination_via_cursor: ~

        pagination_fetch_join_collection: ~

        route_prefix: ~
        validation_groups: ~
        sunset: ~
        input: ~
        output: ~
        stateless: ~
        schemes: ~
        options: ~
        host: ~
        parameters: ~

        # The URL generation strategy to use for IRIs
        url_generation_strategy: !php/const ApiPlatform\Metadata\UrlGeneratorInterface::ABS_PATH

        # To enable collecting denormalization errors
        collectDenormalizationErrors: false

        # ...

# Laravel Configuration

Here’s the configuration of API Platform for Laravel with its default values, as published in config/api-platform.php by php artisan api-platform:install (or php artisan vendor:publish --tag=api-platform-config):

<?php
// config/api-platform.php

use ApiPlatform\Metadata\Exception\InvalidArgumentException;
use ApiPlatform\Metadata\Operation\UnderscorePathSegmentNameGenerator;
use ApiPlatform\Metadata\UrlGeneratorInterface;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Auth\AuthenticationException;
use Symfony\Component\Serializer\Exception\ExceptionInterface as SerializerExceptionInterface;
use Symfony\Component\Serializer\NameConverter\SnakeCaseToCamelCaseNameConverter;

return [
    'title' => 'API Platform',
    'description' => 'My awesome API',
    'version' => '1.0.0',
    'show_webby' => true,

    'routes' => [
        'domain' => null,
        // Global middleware applied to every API Platform routes
        // 'middleware' => [],
    ],

    'resources' => [
        app_path('Models'),
        app_path('ApiResource'),
    ],

    'formats' => [
        'jsonld' => ['application/ld+json'],
        'json' => ['application/json'],
        // 'jsonapi' => ['application/vnd.api+json'],
        // 'csv' => ['text/csv'],
    ],

    'patch_formats' => [
        'json' => ['application/merge-patch+json'],
    ],

    // When true, 'required' validation rules are replaced with 'sometimes'
    // on PATCH operations, allowing partial updates without requiring all fields.
    'partial_patch_validation' => false,

    // When true (default), HEAD requests skip response body construction so
    // collections are not iterated. Set to false to process HEAD like GET.
    'enable_head_request_optimization' => true,

    'docs_formats' => [
        'jsonld' => ['application/ld+json'],
        // 'jsonapi' => ['application/vnd.api+json'],
        'jsonopenapi' => ['application/vnd.openapi+json'],
        'html' => ['text/html'],
    ],

    'error_formats' => [
        'jsonproblem' => ['application/problem+json'],
    ],

    'defaults' => [
        'pagination_enabled' => true,
        'pagination_partial' => false,
        'pagination_client_enabled' => false,
        'pagination_client_items_per_page' => false,
        'pagination_client_partial' => false,
        'pagination_items_per_page' => 30,
        'pagination_maximum_items_per_page' => 30,
        'route_prefix' => '/api',
        'middleware' => [],
    ],

    'pagination' => [
        'page_parameter_name' => 'page',
        'enabled_parameter_name' => 'pagination',
        'items_per_page_parameter_name' => 'itemsPerPage',
        'partial_parameter_name' => 'partial',
    ],

    'jsonapi' => [
        // When false (default), the JSON:API `data.id` uses the resource scalar
        // identifier and a `data.links.self` IRI is added. When true, `data.id`
        // is the resource IRI.
        'use_iri_as_id' => false,

        // Allow client-generated IDs on JSON:API POST per
        // https://jsonapi.org/format/#crud-creating-client-ids. Off by default
        // to avoid id spoofing on public endpoints.
        'allow_client_generated_id' => false,

        // Require the "type" member of JSON:API request resource objects (400
        // when missing) and reject a "type" that does not match the endpoint
        // resource on POST, PUT and PATCH (409 Conflict). Off by default.
        'strict_resource_type' => false,

        // Expose the "id" and "type" properties as "resourceId" and "resourceType"
        // attributes instead of "_id" and "_type", which are not valid JSON:API
        // member names. Off by default.
        'strict_member_names' => false,
    ],

    'graphql' => [
        'enabled' => false,
        'nesting_separator' => '__',
        'introspection' => ['enabled' => true],
        'max_query_complexity' => 500,
        'max_query_depth' => 200,
        // 'middleware' => null,
    ],

    'graphiql' => [
        // 'enabled' => true,
        // 'domain' => null,
        // 'middleware' => null,
    ],

    // set to null if you want to keep snake_case
    'name_converter' => SnakeCaseToCamelCaseNameConverter::class,

    'exception_to_status' => [
        AuthenticationException::class => 401,
        AuthorizationException::class => 403,
        SerializerExceptionInterface::class => 400,
        InvalidArgumentException::class => 400,
    ],

    'redoc' => [
        'enabled' => true,
    ],

    'scalar' => [
        'enabled' => true,
        'extra_configuration' => [],
    ],

    'swagger_ui' => [
        'enabled' => true,
        // 'apiKeys' => [
        //     'api' => [
        //         'name' => 'Authorization',
        //         'type' => 'header',
        //     ],
        // ],
        // 'oauth' => [
        //     'enabled' => true,
        //     'type' => 'oauth2',
        //     'flow' => 'authorizationCode',
        //     'tokenUrl' => '',
        //     'authorizationUrl' =>'',
        //     'refreshUrl' => '',
        //     'scopes' => ['scope1' => 'Description scope 1'],
        //     'pkce' => true,
        // ],
        // 'license' => [
        //     'name' => 'Apache 2.0',
        //     'url' => 'https://www.apache.org/licenses/LICENSE-2.0.html',
        // ],
        // 'contact' => [
        //     'name' => 'API Support',
        //     'url' => 'https://www.example.com/support',
        //     'email' => '[email protected]',
        // ],
        // 'http_auth' => [
        //     'Personal Access Token' => [
        //         'scheme' => 'bearer',
        //         'bearerFormat' => 'JWT',
        //     ],
        // ],
        //
        // 'with_credentials' => true,
        //
        // Extra options merged into the Swagger UI configuration object, see https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration/
        // 'extra_configuration' => [
        //     'docExpansion' => 'list',
        //     'filter' => true,
        // ],
    ],

    // 'openapi' => [
    //     'tags' => [],
    // ],

    'url_generation_strategy' => UrlGeneratorInterface::ABS_PATH,

    // Class implementing PathSegmentNameGeneratorInterface used to derive route
    // segments from resource short names (e.g. `ProductOrder` -> `product_orders`).
    // Set to DashPathSegmentNameGenerator::class for dasherized segments
    // (e.g. `product-orders`).
    'path_segment_name_generator' => UnderscorePathSegmentNameGenerator::class,

    'serializer' => [
        'hydra_prefix' => false,
        // Read, write and document the subtypes declared in the serializer discriminator map of a resource
        'discriminator_map' => false,
        // 'datetime_format' => \DateTimeInterface::RFC3339,
    ],

    // we recommend using "file" or "acpu"
    'cache' => 'file',

    // Path to an Eloquent model metadata file produced by `php artisan api-platform:metadata:dump`.
    // When set (and APP_DEBUG is false), the model attributes and relations are read from this file
    // at boot instead of being introspected from the database, allowing the app to boot without a
    // live DB (e.g. during `docker build`, `composer install`, or static analysis in CI). Commit the
    // file to VCS or bake it into your image, and re-run the command when your models change. Leave
    // null to disable.
    'metadata_dump' => null,

    // MCP (Model Context Protocol) configuration
    'mcp' => [
        'enabled' => true,
        'middleware' => [],
    ],

    // install `api-platform/http-cache`
    // 'http_cache' => [
    //     'etag' => false,
    //     'max_age' => null,
    //     'shared_max_age' => null,
    //     'vary' => null,
    //     'public' => null,
    //     'stale_while_revalidate' => null,
    //     'stale_if_error' => null,
    //     'invalidation' => [
    //         'urls' => [],
    //         'scoped_clients' => [],
    //         'max_header_length' => 7500,
    //         'request_options' => [],
    //         'purger' => ApiPlatform\HttpCache\SouinPurger::class,
    //     ],
    // ],

    'error_handler' => [
        'extend_laravel_handler' => true,
    ],
];

# Global Resources Defaults for Laravel

If you need to globally configure all the resources instead of adding configuration in each one, it’s possible to do so with the defaults key:

<?php
// config/api-platform.php

use ApiPlatform\Metadata\UrlGeneratorInterface;

return [
    'defaults' => [
        'description' => null,
        'iri' => null,
        'short_name' => null,
        'operations' => null,

        'graphql' => null,

        'elasticsearch' => null,

        'security' => null,
        'security_message' => null,
        'security_post_denormalize' => null,
        'security_post_denormalize_message' => null,

        'cache_headers' => [
            // Automatically generate etags for API responses.
            'etag' => true,

            // Default value for the response max age.
            'max_age' => 3600,

            // Default value for the response shared (proxy) max age.
            'shared_max_age' => 3600,

            // Default values of the "Vary" HTTP header.
            'vary' => ['Accept'],

            'invalidation' => [
                'xkey' => [
                    'glue' => ' ',
                ],
            ],
        ],

        'normalization_context' => [
            // Default value to omit null values in conformance with the JSON Merge Patch RFC.
            'skip_null_values' => true,

            // Set to false to disable the generation of Skolem IRIs (`/.well-known/genid/{id}`) globally.
            // Available since API Platform 4.3, see the serialization documentation.
            'gen_id' => true,
        ],

        'denormalization_context' => null,
        'swagger_context' => null,
        'openapi_context' => null,
        'deprecation_reason' => null,
        'fetch_partial' => null,
        'force_eager' => null,
        'formats' => null,
        'filters' => null,
        'hydra_context' => null,
        'mercure' => null,
        'messenger' => null,
        'order' => null,

        // To enable or disable pagination for all resource collections.
        'pagination_enabled' => true,

        // To allow the client to enable or disable the pagination.
        'pagination_client_enabled' => false,

        // To allow the client to set the number of items per page.
        'pagination_client_items_per_page' => false,

        // To allow the client to enable or disable the partial pagination.
        'pagination_client_partial' => false,

        // The default number of items per page.
        'pagination_items_per_page' => 30,

        // The maximum number of items per page.
        'pagination_maximum_items_per_page' => null,

        // To allow partial pagination for all resource collections.
        // This improves performances by skipping the `COUNT` query.
        'pagination_partial' => false,

        // To use cursor-based pagination.
        'pagination_via_cursor' => null,

        'pagination_fetch_join_collection' => null,

        'route_prefix' => null,
        'validation_groups' => null,
        'sunset' => null,
        'input' => null,
        'output' => null,
        'stateless' => null,
        'parameters' => null,

        // The URL generation strategy to use for IRIs
        'url_generation_strategy' => UrlGeneratorInterface::ABS_PATH,

        // To enable collecting denormalization errors
        'collectDenormalizationErrors' => false,
    ],
];

# Resolving Container Parameters in Resource Configuration

This is not available with Laravel, only with the Symfony integration.

Symfony container parameters (%app.some_param%) can be referenced inside resource configuration, whether it is declared with YAML, XML, or PHP attributes. This lets you keep values such as a security expression or a route prefix in parameters.yaml instead of hard-coding them in the resource.

Two resolution rules apply, depending on the field:

  • On plain string fields (shortName, description, uriTemplate, routePrefix, routeName, host, controller, provider, processor, securityMessage, securityPostDenormalizeMessage, and securityPostValidationMessage), %param% is resolved anywhere in the string.
  • On ExpressionLanguage fields (security, securityPostDenormalize, securityPostValidation, condition), the whole trimmed value must be a single %param% reference to be resolved. A partial use, or a real modulo expression such as object.value % 2 === 0, reaches the expression engine untouched.

YAML and XML resource configuration also resolve %param% in a URI variable Link’s fromClass and toClass values.

%% escapes a literal %, and %env(...)% parameters are not allowed in resource configuration.

# config/services.yaml
parameters:
    app.admin_security: 'is_granted("ROLE_ADMIN")'
// src/ApiResource/Book.php
namespace App\ApiResource;

use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Get;

#[ApiResource(
    operations: [
        new Get(security: '%app.admin_security%'),
    ],
)]
final class Book
{
}

The same %app.admin_security% reference works unchanged in an equivalent YAML or XML resource configuration file.

You can also help us improve the documentation of this page.

Using an AI coding agent? See the documentation index for LLMs at /docs/llms.txt.

Made with love by

Les-Tilleuls.coop can help you design and develop your APIs and web projects, and train your teams in API Platform, Symfony, Next.js, Kubernetes and a wide range of other technologies.

Learn more

Copyright © 2023 Kévin Dunglas

Sponsored by Les-Tilleuls.coop