Search code examples
swaggerhttpresponseopenapiapi-designhttp-status-codes

Define multiple 2xx responses for the same endpoint/path


We have a GET endpoint, which does not always return data, and the idea is to define two 2xx responses:

  1. If we have some data, then we return a 200 code with the response body.
  2. If we don't have any data, then we return a 204 code and no response body.
"paths": {
     "/my-endpoint/": {
       "get":  {
         "operationId": "myOperation",
         "responses:": {
             "200": {
                 "description": "OK with body",
                 "content": {
                    "application/json": {
                       "schema":{
                          "$ref": "#/components/schemas/MyResponse"
                       }
                   }
                 }
             },
             "204": {
                 "description": "OK"
            }
         }

....

Is this possible / allowed, and what is the best practice for such a use case?


Solution

  • If both cases (having and not having data) mean a standard business scenario, then I agree with your design.

    Both 200 and 204 responses are pretty straightforward for the consumers, and if you add proper documentation, the API design is all right; moreover, if you use this pattern consistently in your APIs.

    The final approval for such a design can be done only by knowing the resource, its purpose, and the business case.