Adding Swagger OpenAPI to an ASP.NET Web API

Leave a comment

In this post, we will add Swagger OpenAPI to an ASP.NET Web API project. Swagger OpenAPI is a way to document the capabilities of your API. We can do this in .NET by adding the Swashbuckle NuGet package.

Let’s continue with our Web Api project we created earlier. We will open the project in Visual Studio and add the Swashbuckle.AspNetCore package:

Click OK:

Now open Startup.cs and go to ConfigureServices:

We will add the following code:

[sourcecode language=”CSharp”] services.AddSwaggerGen(c =>
{
c.SwaggerDoc("CarlCRMOpenAPISpec",
new OpenApiInfo {
Title = "Carl CRM API",
Version = "v1"
});
});

[/sourcecode]

It should look like:

Now, in the Configure method, add:

[sourcecode] app.UseSwagger();

app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Carl CRM API V1");
});
[/sourcecode]

It should look like:

Now run the project. When the browser opens, change the URL to add /swagger. We see our API:

Let’s send a request using Swagger. We will select /api/Customers:

Click Execute. We get back a response body and headers:

Now if we add a v1/swagger.json to our URL, we get the OpenAPI definition:

Let’s publish this up to our Azure App Service:

Click Publish:

We now see this in our App Service as well:

 

Carl de Souza
Keep learning. Keep building.

Explore AI, agents & Microsoft technology.

I share practical ideas, tutorials, and videos about AI, AI agents, Microsoft technologies, and the Power Platform.

Subscribe on YouTube →
Carl de Souza Enterprise Architect at Microsoft · AI Technology Expert

Leave a Reply

Your email address will not be published. Required fields are marked *