Swagger in .NET

Multiple Request/Response examples for Swagger UI in ASP.NET core

How to add multiple examples for request/response or JsonPatch request in SwaggerUI with Swashbuckle.

Nitesh Singhal
4 min readJan 24, 2022

In this short tutorial, we are going to explore how can we add multiple examples for request and response in SwaggerUI.

Let’s Start by creating a project

dotnet new webapi -o demoswagger

we get default “weatherforecast ”controller.

Now we want to see different response example in swagger.

add required nuget package

<PackageReference Include="Swashbuckle.AspNetCore.Filters" Version="7.0.2" />

and we have to add required code to startup

services.AddSwaggerGen(c =>
{
...
c.ExampleFilters(); // add this to support examples
});
services.AddSwaggerExamplesFromAssemblyOf<Startup>(); // to automatically search all the example from assembly.

Response Example

With this let’s add first example class.

and we have to tell controller to use this example.

and we run the application.

I know it is not a great example but think of scenario where you have different response in case of BadRequest. This could be useful to know the correct response.

Request Example

For request, I will create a different controller where we have some POST request.

Let’s define model first

public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public string Contact { get; set; }
}

Create PersonController.cs. I have just examples for get and post method.

Now define the example classes.

and add the required code to controller.

and when we run the app, we get following result in swagger UI.

Now we can choose different example based on what we want to test.

Examples for JsonPatch

JsonPatch support multiple operation and remembering all the required field for each operation is not easy. so it very useful to have all the example added in the swagger so that we don’t to remember and we can simply use whichever we want to test.

Here I tried to cover all operation example.

Add request example to controller.

Now you can see all the possible example for JsonPatch to test.

Summary

In this tutorial, we have learned how to make use of possibility of adding multiple example for easier testing via swagger.

Hope it is useful.

Happy coding and keep learning.

My other swagger related blogs.

--

--

Nitesh Singhal

Software architect, Exploring ASP.Net core and containerization technologies