Improving API Documentation with Proper Status Code Responses

Osama HaiDer
2 min readJan 4, 2025

--

When building APIs, clear and detailed documentation plays a vital role in making your APIs easy to understand and use. One way to achieve this is by adding proper status code response types in your API wrapper project. This blog will show you how to enhance your API documentation using the Swashbuckle.AspNetCore.Filters NuGet package.

Why Proper Status Code Responses Matter

Including proper status code responses helps:

  • Improve Clarity: Developers can quickly understand the possible outcomes of an API request.
  • Enhance Swagger UI: Examples for each status code make the documentation more user-friendly.
  • Streamline Debugging: Precise responses help identify issues faster during integration.

Step-by-Step Solution

1. Install the NuGet Package

To get started, install the Swashbuckle.AspNetCore.Filters package in your project. Run the following command in your terminal:

Install-Package Swashbuckle.AspNetCore.Filters

2. Configure Swagger to Use Example Filters

In your Program.cs (or Startup.cs, depending on your setup), add the necessary configuration:

builder.Services.AddSwaggerGen(options => options.ExampleFilters());
builder.Services.AddSwaggerExamplesFromAssemblies(Assembly.GetEntryAssembly());

This setup enables Swagger to pick up response examples from your assemblies.

3. Add Response Examples to API Endpoints

Now, use SwaggerResponseExample attributes to provide meaningful examples for different status codes. Here’s how you can define an endpoint:

app.MapGet("/api/bar",
[SwaggerResponseExample((int)HttpStatusCode.OK, typeof(MessageBodyOkExample))]
[SwaggerResponseExample((int)HttpStatusCode.BadRequest, typeof(MessageBody400Example))]
() => new MessageBody
{
Message = "Connected"
})
.Produces<MessageBody>((int)HttpStatusCode.OK)
.Produces<MessageBody>((int)HttpStatusCode.BadRequest);

Key Points in the Example:

  • SwaggerResponseExample: Specifies the response examples for 200 OK and 400 Bad Request.
  • Produces<T>(): Explicitly defines the response type and status code.

Benefits of This Approach

  • Enhanced Documentation: Developers can easily see what responses to expect for various scenarios.
  • Improved Maintainability: Examples are centralized, reducing duplication and confusion.
  • Better Developer Experience: Clear API behavior improves usability and integration.

Conclusion

Adding proper status code responses is a simple yet powerful way to improve your API documentation. By using the Swashbuckle.AspNetCore.Filters package, you can provide clear examples and make your APIs more developer-friendly. Start implementing these changes today to make your APIs stand out!

Let me know your thoughts or questions in the comments below. Happy coding!

--

--

Osama HaiDer
Osama HaiDer

Written by Osama HaiDer

SSE at TEO International | .Net | Azure | AWS | Web APIs | C#

No responses yet