phparraysobjectattributesswagger-php

swagger-php response array of objects using attributes


Just learning to use attributes to describe function parameters and responses. I'm trying to describe a response object that returns an array of objects, but so far not a lot of luck using an array, this is what I have now, it returns an object, I would like it to be an array of objects:

#[OA\Response(
    response: 201,
    description: "Get the list",
    content: new OA\JsonContent(
        properties: [
            new OA\Property(
                property: "property name 1",
                type: "string",
                example: "value 1"
            ),
            new OA\Property(
                property: "property name 2",
                type: "string",
                example: "value 2"
            )
        ],
        type: 'object'
    )
)]

Any guidance would be greatly appreciated!


Solution

  • A typical way would be to use a reference of your object schema (if you have). For example, something like https://github.com/zircote/swagger-php/blob/master/Examples/using-links-php81/RepositoriesController.php#L16

    If you prefer to inline the object properties, it should be similar to this (untested):

    <?php
    
    use OpenApi\Attributes as OA;
    
    #[OA\Get(path: '/api/get')]
    #[OA\Response(
        response: 201,
        description: "Get the list",
        content: new OA\JsonContent(
            type: 'array',
            items: new OA\Items(
            // your list item
                type: 'object',
                properties: [
                    new OA\Property(
                        property: "property name 1",
                        type: "string",
                        example: "value 1"
                    ),
                    new OA\Property(
                        property: "property name 2",
                        type: "string",
                        example: "value 2"
                    )
                ]
            )
        )
    )]
    class Controller
    {
    }