Implement Open API specification in .NET Core Web API using Swagger.

Documentation is always crucial part of development, developers can always check that API is available or not before creating a new one. Swagger is a great framework to use when it comes to API documentation. It’s not only provide the UI but also provide an OpenAPI specification which is used to create client for using the API. Using this specification and Swagger Codegen, you can create client for c#, angular and many more.

The purpose of this post is not just to implement swagger but also to describe how you can specify other OpenAPI specification properties like schemes and hosts which is important when you are working with Azure API management.

Prerequisites

To follow along you need

Let’s Get Started

Step 1: Create a .NET Core API using Visual studio 2017.

Step 2: Remove existing controller and create a new empty controller and name it UserController.


Step 3: Add the following actions in UserController.

[ApiController]
public class UserController : ControllerBase
{
[HttpGet]
[Route(“api/user/”)]
public IEnumerable<string> Get()
{
return new string[] { “value1”, “value2” };
}
[HttpPost]
[Route(“api/user/”)]
public void Post([FromBody] string value)
{
}

[HttpPut]
[Route(“api/user/”)]
public void Put(int id, [FromBody] string value)
{
}

[HttpDelete]
[Route(“api/user/”)]
public void Delete(int id)
{
}

[HttpGet]
[Route(“api/user/getById/”)]
public string GetById(int id)
{
return “value”;
}
}

Step 4

: Install swagger in your project.

Install-Package Swashbuckle.AspNetCore -Version 4.0.1



Step 5

: Create a new file in root project which will specify additional properties in swagger/OpenAPI specification file.

using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace APIDocumentationWithSwagger
{
public class SwaggerAdditionProperties : IDocumentFilter
{
public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
{
swaggerDoc.Schemes = new string[] { “http”, “https” };

// you can specify other properties as per your need
// swaggerDoc.Host, swaggerDoc.BasePath, etc
}
}
}

Step 6

: Go to startup.cs file and register swagger in code.

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

// Register the Swagger generator, defining 1 or more Swagger documents
services.AddSwaggerGen(c =>
{
c.SwaggerDoc(“v1”, new Info { Title = “My API”, Version = “v2” });
c.DocumentFilter<SwaggerAdditionProperties>();
});
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}

app.UseHttpsRedirection();
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();

// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint(“/swagger/v1/swagger.json”, “My API V1”);
c.RoutePrefix = string.Empty;
});
app.UseMvc();
}
}

Step 7

: Remove Launch Browser, so that swagger can be the default page when we run the server.

That’s it. We are done configuring our code let run the application now you should see the swagger page by default and you can see all the APIs you have.

You can generate the specification file by clicking on /swagger/v1/swagger.json link as highlighted above.

Points of interest

Adding additional properties (step 5) will be effective when you are working with Azure API management and trying to import operations that time your specification (json) file must contains properties such as schemes, host etc.

Thanks for reading.

Source

Leave a comment

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