Goal of this post is to show how easy it is to add visualization and testing option to our API using Swagger.
Tool/prerequisites we are going to use: Visual Studio, .NET 6, ASP.NET, Swashbuckle.AspNetCore.SwaggerGen and Swashbuckle.AspNetCore.SwaggerUI as NuGet dependencies.
GitRepo is available here.
Nowadays for a complex web application it is almost always necessary to write a WebAPI. One way to test these endpoints during and after implementation is to manually create our own http clients, which is time consuming and hard to follow the constant changes, which can occur regularly with a new API. There are many tools for this purpose. Probably one of the most well known is Swagger, which we are going to showcase.
Start a new ASP.NET Empty project. We are adding a new folder named Controllers and a controller named HomeController.cs to it. Our structure should look like this:
New we are extending the HomeController with our two endpoints:
[Route("api/home")]
public class HomeController : Controller
{
[HttpGet]
[Route("getMessage/{message}")]
public ActionResult<string> Get(string message)
{
return $"Your message from get was {message}";
}
[HttpPost]
[Route("postMessage")]
public ActionResult<string> Post([FromBody] string message)
{
return $"Your message from post was {message}";
}
}
Our endpoints should be available on these two urls:
localhost:port/api/home/getMessage/{message}
localhost:port/api/home/postMessage
Note: at this state the endpoints are not served as we haven’t configured our site to interact with controllers.
Let’s configure our website to serve our endpoints and use Swagger+SwaggerUI. From Nuget we need to add Swashbuckle.AspNetCore.SwaggerGen and Swashbuckle.AspNetCore.SwaggerUI packages. As all of our dependencies are in place we can go to Program.cs and setup these:
var builder = WebApplication.CreateBuilder(args);
// Telling ASP that we want to use the controller feature
builder.Services.AddControllers();
// Adding swagger code generator (and it's dependencies) to the services
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Mapping the endpoints in the controllers to serve them
app.MapControllers();
// Registering swagger middleware
app.UseSwagger();
// Registering the UI service
app.UseSwaggerUI();
// Starting the website
app.Run();
Running our application will fail to load the default page, because we don’t have any. But if we add swagger at the end of our url, the SwaggerUI should appear:
We can click on the endpoint dropdowns and try them out by adding parameters and clicking on the Execute button.
Happy coding!