.NET6 API Documentation & Example request with Swagger

Picture of Khairul Alam
Khairul Alam
Published on
22.09.2025
Time to Read
3 min

[rank_math_breadcrumb]

Table of Contents

In this post,  Will try to show some basic of Swagger with .NET 6 as well as how to generate example request to make testing handy.

Create a new Web API project with enabling the OpenAPI support.

new project

To add API information and description update builder.Services.AddSwaggerGen() like bellow example:

				
					using Microsoft.OpenApi.Models;
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo
    {
        Title = "WeatherForecast",
        Version = "v1",     
        Description = "This is the API for managing WeatherForecast",
        TermsOfService = new Uri("https://www.linkedin.com/in/khairultaher"),
        Contact = new OpenApiContact
        {
            Name = "khairul Alam",
            Email = "abc@gmail.com",
            Url = new Uri("https://www.linkedin.com/in/khairultaher")
        },
        License = new OpenApiLicense
        {
            Name = "Use under LICX",
            Url = new Uri("https://www.linkedin.com/in/khairultaher"),
        }
    });
}
				
			

Run the app and see the API info and description:

api info

To enable xml comment open .csporj file update propertygroup with these two item:

				
					<PropertyGroup>
  ......
  <GenerateDocumentationFile>True</GenerateDocumentationFile>
  <NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>
				
			

Now configure swagger to use generated xml:

				
					builder.Services.AddSwaggerGen(c =>
{
    ........
    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
    c.IncludeXmlComments(xmlPath);
});
				
			

Go to WeatherForecast controller and add comment on Create action like bellow example:

For POST/PUT:

				
					/// <summary>
/// Add new WeatherForecast
/// </summary>
/// <param name="model"></param>
/// <returns>Return success/fail status</returns>
/// <remarks>
/// **Sample request body:**
///
///     {
///        "id": 1,
///        "Date": "2022-06-24",
///        "TemperatureC": 30,
///        "Summary": "TemperatureC is 30 today",
///     }
///
/// </remarks>
/// <response code="200">Success</response>
/// <response code="401">Failed/Unauthorized</response>
[HttpPost]
[ProducesResponseType(typeof(WeatherForecast), 201)]
[ProducesResponseType(400)]
public async Task<ActionResult<WeatherForecast>> Create([FromBody] WeatherForecast model)
{
    WeatherForecast weatherForecast = new WeatherForecast()
    {
        Id = model.Id,
        Date = model.Date,
        TemperatureC =  model.TemperatureC,
        Summary = model.Summary
    };
    return await Task.FromResult(weatherForecast);  
}
				
			

By runnig the app we will see the information are adedd to swagger:

comment

Look into the example value, see that it show the default values. now we want here to add example value for testing. To do so add Swashbuckle.AspNetCore.Filters NuGet package.
update

				
					using Swashbuckle.AspNetCore.Filters;
builder.Services.AddSwaggerGen(c =>
{
   .........
    c.ExampleFilters();
    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
    c.IncludeXmlComments(xmlPath);
}
builder.Services.AddSwaggerExamplesFromAssemblies(Assembly.GetEntryAssembly());
				
			

Now add new class that will generate example value for the WeatherForecast class.

				
					using Swashbuckle.AspNetCore.Filters;
namespace SwaggerExample
{
    public class WeatherForecastRequestExample : IExamplesProvider<WeatherForecast>
    {
        public WeatherForecast GetExamples()
        {
            return new WeatherForecast()
            {
                Id = 1,
                Date = DateTime.Now,
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = "test data"
            };
        }
    }
}
				
			

rebuild and run the the app again.

Example values

For GET/DELETE request:

				
					/// <summary>
/// Get WeatherForecast By Id
/// </summary>
///<param name="id" example="2">The product id</param>
/// <returns>Return success/fail status</returns>
/// <remarks>
/// **Sample request body:**
///
///     {
///        "id": 2
///     }
///
/// </remarks>
/// <response code="200">Success</response>
/// <response code="401">Failed/Unauthorized</response>
[HttpGet]
[ProducesResponseType(typeof(WeatherForecast), 200)]
[ProducesResponseType(400)]
public ActionResult<WeatherForecast> Get([FromQuery] int id)
{
    return Enumerable.Range(1, 5)
        .Select(index => new WeatherForecast
        {
            Id = index,
            Date = DateTime.Now.AddDays(index),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Summaries[Random.Shared.Next(Summaries.Length)]
        }).Where(w => w.Id == id).FirstOrDefault()!;
}
				
			
example values 2

Swagger shows all available schema information like above but if we don’t want to show them then just add DefaultModelsExpandDepth(-1)

				
					app.UseSwagger();
app.UseSwaggerUI(x =>
{
    x.SwaggerEndpoint("/swagger/v1/swagger.json", "WeatherForecast: API");
    x.DefaultModelsExpandDepth(-1);
});
				
			

Implement authorization:

Take advantage of authentication and authorization to secure your Swagger UI in .NET Core 6

				
					builder.Services.AddSwaggerGen(c =>
{
    .......
    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
    {
        Name = "Authorization",
        Type = SecuritySchemeType.ApiKey,
        Scheme = "Bearer",
        BearerFormat = "JWT",
        In = ParameterLocation.Header,
        Description = "JWT Authorization header using the Bearer scheme. \r\n\r\n Enter 'Bearer' [space] and then your token in the text input below.\r\n\r\nExample: \"Bearer 1safsfsdfdfd\"",
    });
    c.AddSecurityRequirement(new OpenApiSecurityRequirement {
        {
            new OpenApiSecurityScheme {
                Reference = new OpenApiReference {
                    Type = ReferenceType.SecurityScheme,
                        Id = "Bearer"
                }
            },
            new string[] {}
        }
    });
    
   ......
});
				
			
security
Thanks…
50+ companies rely on our top 1% talent to scale their dev teams.
Excellence Our minimum bar.
It has become a prerequisite for companies to develop custom software.
We've stopped counting. Over 50 brands count on us.
Our company specializes in software outsourcing and provides robust, scalable, and efficient solutions to clients around the world.
klikit

Chris Withers

CEO & Founder, Klikit

Klikit-logo
Heartfelt appreciation to Vivasoft Limited for believing in my vision. Their talented developers can take any challenges against all odds and helped to bring Klikit into life.appreciation to Vivasoft Limited for believing in my vision. Their talented developers can take any challenges.
Start with a dedicated squad in 7 days

NDA first, transparent rates, agile delivery from day one.

Where We Build the Future
Scale Engineering Without the Overhead

Elastic offshore teams that integrate with your processes and timezone.

Tech Stack
0 +
Blogs You May Love

Don’t let understaffing hold you back. Maximize your team’s performance and reach your business goals with the best IT Staff Augmentation

let's build our future together

Get to Know Us Better

Explore our expertise, projects, and vision.