ASP.NET Core Web API-Swagger


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.

  1. API Design - It provides a structured approach to designing APIs, allowing developers to define endpoints, request/response formats, error handling, and other important aspects.
  2. API Testing - Swagger UI allows developers to test API endpoints directly from the browser, making it convenient to verify the functionality and behavior of the API.
  3. API Documentation - Swagger enables the automatic generation of comprehensive and interactive API documentation, making it easier for developers to understand and use the API.

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.

  1. Start Visual Studio and select Create a new project.
  2. In the Create a new project dialog, select ASP.NET Core Web Application -> Next.
  3. In the Configure your new project dialog, enter Swtest for Project name -> Create.

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.

ASP.NET Core web API Swagger

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

ASP.NET Core web API Swagger

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.

ASP.NET Core web API Swagger

Now click on the Above Try it Out! button. To check return data through API.

ASP.NET Core web API Swagger
Next