Pages

Friday, September 11, 2020

Swagger: Getting started guide - Generate web api documention with Swagger ASP.NET Core

Introduction

For people that don't know what Swagger is.

"Swagger is a set of open-source tools built around the OpenAPI Specification that can help you design, build, document and consume REST APIs."
Source

This "Swagger: Getting started guide" post will explain the basics and how to use Swagger with:
  • ASP.NET Core 3.1
  • Swashbuckle.AspNetCore 5.5.1

  • Source code

    You can find the source code of this post on: https://github.com/gergroen/Swagger-getting-started-guide

    Post summary

  • Installing NuGet
  • Create dto
  • Create api controller
  • Configure services and application
  • Swagger page

  • Installing NuGet

    First create a empty ASP.NET Core Web application project and install the next nuget packages.
  • Swashbuckle.AspNetCore

  • Create dto

    Create a dto class like this CoffeeDto class.
    namespace Swagger.GettingStarted
    {
        public class CoffeeDto
        {
            public string Name { get; set; } = string.Empty;
        }
    }
    

    Create api controller

    Add a api controller class for your dto. And add comments to the operations.
    using System.Collections.Generic;
    using Microsoft.AspNetCore.Mvc;
    
    namespace Swagger.GettingStarted
    {
        /// <summary>
        /// Coffee controller
        /// </summary>
        [Produces("application/json")]
        [Route("api/[controller]")]
        [ApiController]
        public class CoffeeController : ControllerBase
        {
            /// <summary>
            /// Get all coffees
            /// </summary>
            /// <returns></returns>
            [Route("")]
            [HttpGet]
            public List GetAll()
            {
                return new List
                {
                    new CoffeeDto{ Name = "Americano"},
                    new CoffeeDto{ Name = "Latte"},
                    new CoffeeDto{ Name = "Cappuccino"},
                    new CoffeeDto{ Name = "Espresso"},
                };
            }
        }
    }
    

    Configure services and application

    Enable "xml documentation file" in the project -> properties -> build -> output.
    Then we need to configure in the Startup class the services with AddSwaggerGen where we include the xml documentation file.
    Configure the application with UseSwagger to generate the openapi json and UseSwaggerUI for the swagger documentation page.
    using System;
    using System.IO;
    using System.Reflection;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.DependencyInjection;
    
    namespace Swagger.GettingStarted
    {
        public class Startup
        {
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddControllers();
                services.AddSwaggerGen(c => {
                    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                    c.IncludeXmlComments(xmlPath);
                });
            }
    
            public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                app.UseSwagger();
                app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
                });
                app.UseRouting();
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllers();
                });
            }
        }
    }
    

    Swagger page

    Run the application and add /swagger to the url in the browser to show the swagger page.
    On this page is shown all the controllers, the operations and the dto's of the api.

    Useful links:

    Source code
    Swagger documentation

    No comments:

    Post a Comment