Skip to main content

SwashBuckle - Swagger Open API Documentation


Swashbuckle Open API


Swagger is Open API documentation used to understand the various methods and the request/responses of various endpoints. It generates the Web API SDK for clients.


Swashbuckle.AspNetCore is an open-source project for generating Swagger documents for ASP.Net Core Web APIs. Another open-source project is NSwag for generating swagger documents.


Enable Swagger in .NET Core Apps - 

Note - Install the Swashbuckle.AspNetCore NuGet package into your solution.Don't install Swashbuckle.AspNetCore.Swagger package)


Add the below to the Configure() Method - 

app.UseSwagger();

app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "AppName"); });


using Swashbuckle.AspNetCore.Examples;
using Swashbuckle.AspNetCore.Swagger;

public void ConfigureServices(IServiceCollection services)
{
    // Register the Swagger generator, defining 1 or more Swagger documents
    services.AddSwaggerGen(c =>
    {
        var appVersion = "v" + typeof(RuntimeEnvironment).GetTypeInfo().Assembly.GetCustomAttribute<AssemblyFileVersionAttribute>().Version;
        c.SwaggerDoc("v1", new Info 
        { 
            Title = "My API",
            Description = "API Description"
            Contact = new Contact
            {
                Name = "Team Name",
                Url = "Link to team confluence/documentation pages"
            } 
            Version = appVersion 
        });

        c.AddSecurityDefinition("Bearer", new ApiKeyScheme
        {
            In = "header",
            Description = "Please Enter OAuth with Bearer into field",
            Name = "Authorization",
            Type = "apiKey"
        });

        c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>> {{ 'Bearer', Enumerable.Empty<string>()}});

        c.CustomSchemaIds((type) => type.ToString()
             .Replace("[", "_")
             .Replace("]", "_")
             .Replace("{", "_")
             .Replace("}", "_")
             .Replace(",", "_")
             .Replace("`", "_")
        );

        c.OperationFilter<SwaggerHeadFilter> //Research
        c.Operation<ExamplesOperationFilter>();

        //Set the comments path for the Swagger JSON and UI - Xml files containing the summary comments are created in the ./bin folder of the basedirectory
        //Swagger uses that to for showing the summary
        var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
        var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
        c.IncludeXmlComments(xmlPath);
        c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFile2));
    });
}

//Controller
[ProducesResponseType(typeof(Task<ResponseType>), 200)] //POST
[ProducesResponseType(typeof(Task<OkResult>), 200)]          //DELETE
[ProducesResponseType(typeof(Task<ResponseType>), 201)] //POST(Create)
[ProducesResponseType(typeof(Task<ResponseType>), 400)]
[ProducesResponseType(typeof(Task<ResponseType>), 401)]
[ProducesResponseType(typeof(Task<ResponseType>), 404)]
[ProducesResponseType(typeof(Task<ResponseType>), 416)]
[ProducesResponseType(typeof(Task<ResponseType>), 500)]
[SwaggerRequestExample(typeof(Request), typeof(RequestExampleClassType))]
[HttpPost("Route")]
[HttpGet("Route")]
[HttpDelete("Route")]

//Examples Class
public class RequestExample : IExamplesProvider
{
    public object GetExamples()
    {
        return new Request
        {
            {field} = value,
            ....
        }
    }
}


Comments