.NET Core REST API With Swagger

What is a REST API?

 
REST API is short for Representational State Transfer Application Program Interface and can be divided into two sub-categories as below.
 

Stateless API

 
API does not store client state session in the server; In Stateless, every call goes through the whole cycle and should result in the same response.
 
Example
 
http://example.com/catalog?item=1729
 

Stateful API

 
API  holds the client session in the server; meaning that previous information exchanged is used in order to respond. Each client gets its own response customized based on their previous inputs.
 
Example
 
http://netflix.com/Favourites
 

What is Swagger?

"Swagger is a powerful yet easy-to-use suite of API developer tools for teams and individuals, enabling development across the entire API lifecycle, from design and documentation, to test and deployment.

Swagger consists of a mix of open source, free and commercially available tools that allow anyone, from technical engineers to street smart product managers to build amazing APIs that everyone loves."

Read more about Swagger here.
 
Swagger Nuget used here.
 
Swagger Website
 
https://swagger.io/ 
 

Benefits of using Swagger

  • Easily tested APIs, being able to simulate the usage of any method;
  • A complete view of your API methods and controllers, Swagger groups the API methods per each controller;
  • API documentation, Swagger can be used as part of the documentation.
  • Much more benefits can be found here.

Implementation Step by Step

 
Project creation and NuGet installation
 
Create a new project of type ASP.NET Core Web Application.
 
.NET Core Rest API with Swagger
 
Select the project subcategory as API.
 
.NET Core Rest API with Swagger
 
This is the result of your project creation.
 
.NET Core Rest API with Swagger
 
Double-click on your project and click on "Manage NuGet Packages...".
 
.NET Core Rest API with Swagger
 
 
.NET Core Rest API with Swagger
 
Update your StartUp class in order for your project to recognize Swagger.
  1. public class Startup  
  2.    {  
  3.        public Startup( IConfiguration configuration )  
  4.        {  
  5.            Configuration = configuration;  
  6.        }  
  7.   
  8.        public IConfiguration Configuration { get; }  
  9.   
  10.        // This method gets called by the runtime. Use this method to add services to the container.  
  11.        public void ConfigureServices( IServiceCollection services )  
  12.        {  
  13.            services.AddMvc().SetCompatibilityVersion( CompatibilityVersion.Version_2_1 );  
  14.   
  15.            // Register Swagger  
  16.            services.AddSwaggerGen( c =>  
  17.            {  
  18.                c.SwaggerDoc( "v1"new Info { Title = "Sample API", Version = "version 1" } );  
  19.            } );  
  20.        }  
  21.   
  22.        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  23.        public void Configure( IApplicationBuilder app, IHostingEnvironment env )  
  24.        {  
  25.            if ( env.IsDevelopment() )  
  26.            {  
  27.                app.UseDeveloperExceptionPage();  
  28.   
  29.                // Enable middleware to serve generated Swagger as a JSON endpoint.  
  30.                app.UseSwagger();  
  31.   
  32.                // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),  
  33.                // specifying the Swagger JSON endpoint.  
  34.                app.UseSwaggerUI( c =>  
  35.                {  
  36.                    c.SwaggerEndpoint( "/swagger/v1/swagger.json""My API V1" );  
  37.                } );  
  38.            }  
  39.   
  40.            app.UseMvc();  
  41.        }  
  42.    }  

Project customization

 
In order to use the Swagger API, let's create some scenarios that could take advantage of the Swagger usage.
 
The project with the customization will be like below.
 
.NET Core Rest API with Swagger
 
ValueSamples class
  1. public static class ValueSamples  
  2.   {  
  3.       public static Dictionary<intstring> MyValue;  
  4.   
  5.       public static void Initialize()  
  6.       {  
  7.           MyValue = new Dictionary<intstring>();  
  8.           MyValue.Add( 0, "Value 0" );  
  9.           MyValue.Add( 1, "Value 1" );  
  10.           MyValue.Add( 2, "Value 2" );  
  11.       }  
  12.   }  
ValuesController controller
  1. [Route( "api/[controller]" )]  
  2.    [ApiController]  
  3.    public class ValuesController : ControllerBase  
  4.    {  
  5.        public ValuesController()  
  6.        {  
  7.            ValueSamples.Initialize();  
  8.        }  
  9.   
  10.        // GET api/values  
  11.        [HttpGet]  
  12.        public ActionResult<Dictionary<intstring>> Get()  
  13.        {  
  14.            return ValueSamples.MyValue;  
  15.        }  
  16.   
  17.        // GET api/values/5  
  18.        [HttpGet( "{id}" )]  
  19.        public ActionResult<string> Get( int id )  
  20.        {  
  21.            return ValueSamples.MyValue.GetValueOrDefault( id );  
  22.        }  
  23.   
  24.        // POST api/values  
  25.        [HttpPost]  
  26.        public void Post( [FromBody] string value )  
  27.        {  
  28.            var maxKey = ValueSamples.MyValue.Max( x => x.Key );  
  29.   
  30.            ValueSamples.MyValue.Add( maxKey + 1, value );  
  31.        }  
  32.   
  33.        // PUT api/values/5  
  34.        [HttpPut( "{id}" )]  
  35.        public void Put( int id, [FromBody] string value )  
  36.        {  
  37.            ValueSamples.MyValue.Add( id, value );  
  38.        }  
  39.   
  40.        // DELETE api/values/5  
  41.        [HttpDelete( "{id}" )]  
  42.        public void Delete( int id )  
  43.        {  
  44.            ValueSamples.MyValue.Remove( id );  
  45.        }  
  46.    }  

Using the Swagger

 
Now, push F5 and complete your URL with "/swagger". It must look like this.
 
http://localhost:61986/swagger 
 
.NET Core Rest API with Swagger
 
Let's start testing our Web APIs.
 

Testing the "Get all" method

 
Calling the method from Swagger,
 
.NET Core Rest API with Swagger 
 
Validating the method called from the controller.
 
.NET Core Rest API with Swagger 
 
Checking the API response.
 
.NET Core Rest API with Swagger
 

Testing getting a single result method

 
Inputting data in Swagger,

.NET Core Rest API with Swagger
 

Testing to get a single non-existent record

 
Calling the method from,
 
.NET Core Rest API with Swagger 
 
Validating the call from the controller,

.NET Core Rest API with Swagger
 

Swagger Response

 
.NET Core Rest API with Swagger
 

Testing the post method


Input the data in the Post Method,
 
.NET Core Rest API with Swagger 
 
Validating the received data in the controller
 
.NET Core Rest API with Swagger
 

Swagger Response

 
.NET Core Rest API with Swagger
 
.NET Core Rest API with Swagger 
 
Congratulations, you have successfully integrated Swagger with your Rest API, 
 External References
  • https://swagger.io/
  • https://www.nuget.org/packages/Swashbuckle.AspNetCore
  • https://docs.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-swashbuckle