How to integrate Swagger UI in a .NET Core Web API application | Amoenus Dev

Why I do what I do: I envision the world where technology and automation have given us freedom from tedious tasks and everyone can focus on what really matters most to them. My personal goal is to remove obstacles so that together we can move the world forward.
How I do it: I focus on automating tedious and repetitive tasks Identify the best tools for the job and creating integrations between the tools Make solutions to the problems reusable and standardized. Approach problems modularly and find the best tool to solve each smaller problem. Never stop learning to be aware of all the tools and best approaches to apply in the future.
What I do: I write software, implement build/deploy and test automation pipelines Facilitate the knowledge and tools sharing among stakeholders by setting up wikis, demos and user groups. Create UI Mockups to better visualise the end products and gather valuable feedback early on. Attend and present in developer forums to gain and spread the knowledge amongst peers.
Swagger tooling allows you to generate beautiful API documentation, including a UI to explore and test operations, directly from your routes, controllers and models. Setting it up is simple but requires some code changes. To enable swagger integration for your .NET Core Web API project you will need to:
- Install Swashbuckle.AspNetCore package from NuGet
- Change the
Startup.csclass of your Net Core Web API application.- Add using statement for
OpenApiInfo - Modify
Configure(IApplicationBuilder app, IWebHostEnvironment env) - Modify
ConfigureServices(IServiceCollection services)
- Add using statement for
Changes for Startup.cs
Installing Swagger
From your project folder install the Swagger Nuget package (6.1.4 for this instance)
dotnet add package Swashbuckle.AspNetCore --version 6.1.4
Using statement
using Microsoft.OpenApi.Models;
Changes for ConfigureServices()
In the ConfigureServices() method you should add
services.AddMvc();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = "My Awesome API",
Version = "v1"
});
});
Changes for Configure()
In the Configure() method you should add
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My Awesome API V1");
});
I prefer to enable it only for development
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My Awesome API V1");
});
}
Taking it for a spin
After all these changes, we are finally ready to test our new integration.
dotnet run
Navigate to localhost:4200/swagger to see the SwaggerUI
Note: your port may be different
Bonus: Customisation
Now that you have Swagger configured, you might want to change the default theme. You can learn how to do this in this blog post
Did you have any questions or feedback? Please share them in the comments 🤗


