Search code examples
annotationsswaggeropenapiswagger-php

Are declarations of entire responses reusable in swagger-php?


I would love a way to declare some responses that are the same for every endpoint; for example every endpoint will output a 401 if you don't have a proper token, and then there can be another group of endpoints that will all output 404 if you don't have a valid id of something in the beginning of your path.

So for almost every method I find myself copy-pasting things such as this:

* @OA\Response(response=401, description="If no token..."),
* @OA\Response(response=404, description="If ID of thing invalid..."),

The getting started section says that reusable responses are supported, but covering only the properties (of successful responses).

There are no examples for the kind of thing i'm looking for, and I also can't get myself to guess anything that would compile.

Something like @OA\Response(ref="#/components/schemas/Unauthorized") seems like it should be the way (and the compilation doesn't complain about the presence of the ref attribute), but how do i then declare what the Unauthorized schema looks like? Because declaring a @OA\Response says it only expects the fields: "ref", "response", "description", "headers", "content", "links", "x", none of which can serve as an identifier.

I am using this in conjunction with L5-swagger for Laravel support.


Solution

  • Declare a response outside of an operation:

    /**
     * @OA\Response(response="Unauthorized", description="If no token...")
     */
    

    This will add it to the #/components/responses/ using the response= as value as key.

    Then you're able to reuse it later inside an operation:

    /**
     * @OA\Get(
     *   path="/example",
     *   @OA\Response(response=401, ref="#/components/responses/Unauthorized")
     * )
     */