.NET APIs Part 6 – Swagger

This is part 6 in a series about building APIs in .NET using C#. The previous (part 5) entry is here, and the series starts here.

As you know, an API sits between a client and the back end. It is imperative for the client programmer to know not only what an API does, but what the URL is, what verbs it supports and what parameters are available.

Fortunately, there is an open standard and free server: Open API and Swashbuckle. You install these once for each project and then you can just use them, as we’ll see.

This post will show you how to install them, using Visual Studio. You’ll obtain the bits you need using NuGet. Start by installing Swashbuckle.AspNetCore.

Go to your project’s properties and choose Application and Console Application. Then choose Output under Build and scroll down to where you can check “Generate a file containing API documentation”

Open Program.cs and add the Swagger generator to the services collection:

builder.Services.AddSwaggerGen(
 x =>
 {
     x.SwaggerDoc(
         "v1",
         new OpenApiInfo
         {
             Title = $"{Assembly.GetExecutingAssembly().GetName().Name}",
             Version = "Version 1",
             Description = "Create documentation for myApp",
             Contact = new OpenApiContact
             {
                 Name = "Jesse Liberty",
                 Email = "yourName@gmail.com",
                 Url = new Uri("https://jesseliberty.com")
             }
         });
             var xmlFilename = System.IO.Path.Combine(System.AppContext.BaseDirectory, $"{Assembly.GetExecutingAssembly().GetName().Name}.xml");
             c.IncludeXmlComments(xmlFilename);

});

That's it, you are now ready to create Swagger documentation. We'll review how to do so in the next installment.

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen online courses. His latest book, Building APIs with .NET will be released early in 2025. Liberty is a Senior SW Engineer for CNH and he was a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Microsoft MVP.
This entry was posted in API, C# and tagged . Bookmark the permalink.

4 Responses to .NET APIs Part 6 – Swagger

  1. Pingback: Dew Drop – February 6, 2024 (#4122) – Morning Dew by Alvin Ashcraft

Leave a Reply

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