Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 675
Kees Klomp Avatar asked Oct 28 '25 03:10

Kees Klomp


2 Answers

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
{
}

like image 155
DerManoMann Avatar answered Oct 29 '25 19:10

DerManoMann


Assuming an object is a separate class with its own Open API schema, you can declare it as shown below:

#[OA\Property(
        type: 'array',
        items: new OA\Items(
            oneOf: [
                new OA\Schema(ref: '#/components/schemas/CarsResult'),
                new OA\Schema(ref: '#/components/schemas/TrucksResult'),
            ]
        ),
        nullable: false
    )]
like image 20
Neemias Santos Avatar answered Oct 29 '25 20:10

Neemias Santos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!