swaggeropenapiswagger-php

Documenting multiple response possibilities with OpenApi annotation


I have an endpoint that can return either a single item or a list of items, depending on the parameters passed in (There's no flexibility in the endpoint currently, I am unable to make code changes).

I am trying to generate API documentation with OpenApi annotations.

My endpoint: {{url}}/qualification/{qualification_id}/holder/{holder_id}

The {holder} parameter is optional. If only the {qualification_id } parameter is supplied, a list of people that have received the qualification is returned, e.g.:

{{url}}/qualification/156/holder returns

<holder>
    <holder>
        <id>34</id>
        <name>Tim</name>
        <expired>false</expired>
    </holder>
    <holder>
        <id>87</id>
        <name>Andy</name>
        <expired>false</expired>
    </holder>
    <holder>
        <id>346</id>
        <name>Ralph</name>
        <expired>true</expired>
    </holder>
<holder>

For this my response annotation is:

@OA\Response(
    response=200,
    @OA\JsonContent(
        type="array",
        @OA/Items(ref="#/components/schemas/QualificationHolder")
    )
)

However, if the {holder_id} parameter is also supplied, only that specific qualification record holder is returned e.g.:

{{url}}/qualification/156/holder/346 returns:

<holder>
    <id>346</id>
    <name>Ralph</name>
    <expired>true</expired>
</holder>

For this my response annotation would be:

@OA\Response(
    response=200,
    @OA\JsonContent(ref="#/components/schemas/QualificationHolder")
)

My problem is that I don't know how to combine these so that the documentation generated by using the OpenApi annotations indicates that the response could be EITHER of those options, and I can't find any documentation on line to indicate anything, either. Everything I find points me towards how to set up the json/yaml file, which is not what I need for this.


Solution

  • After digging through the zircote/swagger-php code making some assumptions while looking at the examples, I got it working by using the following annotation:

    @OA\Response(
        response=200,
        @OA\JsonContent(
            oneOf={
                @OA\Schema(ref="#/components/schemas/QualificationHolder"),
                @OA\Schema(
                    type="array",
                    @OA\Items(ref="#/components/schemas/QualificationHolder")
                )
            }
        )
    )