Swagger in .NET
Documenting additional API endpoints in Swagger in ASP.Net core
In a typical ASP.Net core WebAPI project when we want to expose an API, we create a controller and implement the API functionality.
But this is not always required, we can map endpoint without defining the controllers. for some trivial task or information you don’t need to create controller and implement the logic there.
for example, if I want to write an API which returns the version.
I can simply write code like this and call it.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
... app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapGet("/version", context =>
{
var config = new { Version = "1.0"};
return context.Response.WriteAsJsonAsync(config);
});
});
}
when I call this endpoint from browser I get following result.
API in Swagger UI
Let’s check if this new API is available in the swagger document or not. Open the swagger UI and we can see that this endpoint is not available in the swagger document. The main purpose of swagger document is to provide all the endpoints which are exposed by webapi, but this endpoint “version” is not listed.
So how do we add it ?
Adding API to swagger document
In this tutorial, we will add this API endpoint to swagger document so that it can be accessed via swagger UI also.
Let’s make the changes.
Add a class “CustomDocumentFilter” in your existing project which has already support for swagger. see below code.
and add following code to AddSwaggerGen method
services.AddSwaggerGen(c =>
{
c.DocumentFilter<CustomDocumentFilter>();
});
Let’s run the application.
You can see the newly added “Version” API.
let’s verify if it is working or not.
as we can see in screenshot the API response is shown correctly.
Summary
Adding any additional endpoint in swagger endpoint is very easy, just follow the same procedure for adding your own API.
Hope this is helpful..!
Let me know your thoughts below..!
If you liked this article please share the energy and press the clap button And follow me for more interesting articles like this one.
My other swagger related blogs.