Search code examples
phpapi-platform.com

Api platfrom, show possible query parameters in documentation


I have a GET endpoint, that endpoint can return only a single record, so it's not a collection endpoint, but additionally, I need to be able to apply different optional filters with query parameters, for example:

  • deleted - show/hide
  • user - search additionally by user id

Som uri will be something like /product/{$is}?delted=show&user=1

but how can I describe them to be visible in API documentation UI?


Solution

  • With API-Platform 3, using PHP 8 attributes:

    // src/Entity/MyEntity.php
    <?php
    use ApiPlatform\Metadata\ApiResource;
    use ApiPlatform\Metadata\Get;
    use ApiPlatform\OpenApi\Model\Operation as ModelOperation;
    use ApiPlatform\OpenApi\Model\Parameter as ModelParameter;
    
    #[ApiResource(
        new Get(
            openapi: new ModelOperation(
                parameters: [
                    new ModelParameter(
                        name: "deleted",
                        in: "query",
                        schema: [
                            "type" => "string",
                            "enum" => ["show", "hide"],
                        ],
                    ),
                    new ModelParameter(
                        name: "user",
                        in: "query",
                        schema: ["type" => "integer"]
                    )
                ],
            ),
        ),
    )]
    class MyEntity {
        // ...
    }
    

    The "in": "query" indicates that the parameter is located inside the query string (i.e GET parameters set).

    When using API-Platform 2, use openapi_context instead of openapi and passes an array of array instead of an array or ModelParameter objects.

    More information about OpenApi here.