Swagger is an open-source tool which help developers design, build, document, and consume RESTful APIs (Application Programming Interfaces). The Swagger specification defines the structure and details of the API endpoints, request/response payloads, headers, authentication methods, and more.
Advantage of Swagger
When you use swagger, You can take following advantages.
To add to Swagger in web API Project, you need to follow these steps:
Step 1: Create an ASP.NET Web API Project
We use the version of Visual Studio 2022 and .NET Framework 6.0 to build the app.
Now build and run the app, you will see the following image shows the application.
Step 2: ByDefault WeatherForecast ApiController
By Default, the WeatherForecast Controller will be created with the following code:
using Microsoft.AspNetCore.Mvc;
namespace Swtest.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
}
Step 3: Add Swagger Client
Installing Swagger from NuGet Package Manager, from Visual Studio project.
Right click Tools > NuGet Package Manager->Manage NuGet for Solution. In the opened NuGet-Solution dialog - Click Browse, then Search Swagger and Install Swashbuckle.ASPNetCore
After installation, Once you have installed this package, The Program.cs file will be updated. Here is how it would look in code.
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Step 4: Run the project and test swagger.
Now Click on the GET to expand the Blog API box.
Now click on the Above Try it Out! button. To check return data through API.