.Net Core API

Setting Up a .NET Core Web API with Swagger UI

Building a robust and well-documented API is a crucial aspect of modern software development. In this blog post, we'll walk you through the process of setting up a .NET Core Web API and integrating Swagger UI for easy API exploration and testing.

What is Swagger?

Swagger is an open-source framework that simplifies API development by allowing developers to describe, document, and test APIs. Swagger UI, in particular, provides a user-friendly interface for visualizing and interacting with your API endpoints.

Prerequisites

Before we get started, ensure you have the following prerequisites installed:

Step 1: Create a New .NET Core Web API Project

You can create a new .NET Core Web API project using the command-line or Visual Studio. We'll use the command-line for simplicity:

1dotnet new webapi -n MyWebApi
2cd MyWebApi

This command creates a new Web API project named MyWebApi.

Step 2: Add Swagger to Your Project

To add Swagger to your project, you'll need to install the Swashbuckle.AspNetCore NuGet package. Open a terminal and navigate to your project's root directory, then run:

1dotnet add package Swashbuckle.AspNetCore

Step 3: Configure Swagger in Startup.cs

In your Startup.cs file, locate the ConfigureServices method and add the Swagger generator:

1// Add this using statement at the top of the file:
2using Microsoft.OpenApi.Models;
3
4// Inside ConfigureServices method:
5services.AddSwaggerGen(c =>
6{
7 c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
8});
9

Next, in the Configure method, enable the Swagger UI:

1// Inside Configure method, before app.UseAuthorization():
2app.UseSwagger();
3app.UseSwaggerUI(c =>
4{
5 c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
6});
7

Step 4: Create an API Controller

Create a sample API controller to test Swagger. In your project, create a new file named SampleController.cs:

1using Microsoft.AspNetCore.Mvc;
2
3[Route("api/[controller]")]
4[ApiController]
5public class SampleController : ControllerBase
6{
7 [HttpGet]
8 public IActionResult Get()
9 {
10 return Ok("Hello from the API!");
11 }
12}
13

Step 5: Build and Run Your Web API

Build your project by running:

1dotnet build

And then run it:

1dotnet run

Your API should now be running at https://localhost:5001 (or http://localhost:5000).

Step 6: Explore Your API with Swagger

Open your web browser and navigate to https://localhost:5001/swagger (or http://localhost:5000/swagger). You'll be greeted with the Swagger UI interface, which allows you to explore and test your API endpoints interactively.

Conclusion

In this blog post, we've shown you how to set up a .NET Core Web API project and integrate Swagger UI for easy API documentation and testing. This combination will greatly simplify the process of developing and documenting your APIs, making it easier for both developers and consumers to work with your API. Happy coding!