Home > Software engineering >  Best practice for including common http error codes in swagger / openapi definition
Best practice for including common http error codes in swagger / openapi definition

Time:12-22

I'm wondering about good practices about including common error types in Swagger/OpenAPI definition.

Let's consider following controller method:

[HttpGet]
[ProducesResponseType(StatusCodes.Status400BadRequest)] // to be or not to be?
public ActionResult SomeMethod(Foo foo)
{
    if (foo.Property != "expectedValue")
    {
        return BadRequest();
    }

    return Ok();
}

So, I'm performing some logic in the controller, which might end up in a state in which I want to return 400 BadRequest. Note, that I don't return any content. Since I develop a REST API that generates Swagger/OpenAPI definition and tools like autorest may be used to generate client code based on that definition, I want to be sure it is as accurate as possible.

My question is:

  • should I declare explicitly that the user might get 400 Bad Request

OR

  • this makes sense only in case I want to describe the format of response content (in case 400Bad request has some content)

The same applies to codes like 401, 404 etc.

CodePudding user response:

The object BadRequest is used as a response (Result) with StatusCode=400. DotNet has several response types with predefined StatusCode, so you can use different methods, for example: NotFound(404):https://docs.microsoft.com/en-us/dotnet/api/system.web.http.apicontroller.notfound?view=aspnetcore-2.2

InternalServerError(500):https://docs.microsoft.com/en-us/dotnet/api/system.web.http.apicontroller.internalservererror?view=aspnetcore-2.2

Or simply use StatusCode for any other code that is not predefined:https://docs.microsoft.com/en-us/dotnet/api/system.web.http.apicontroller.statuscode?view=aspnetcore-2.2

CodePudding user response:

Even if (in addition to the returned http code, 400, 401, etc..) you do not return any payload at all, you should yet explicitly declare such responses.

Do not forget that in a "code-first" approach, your build chain could automatically generate the OpenApi contract (based on your code) as well as a nice user documentation.

In the contrary approach (contract-first), the code generated based on your OpenApi file would contain these response descriptions.

  • Related