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.

Select the project subcategory as API.

This is the result of your project creation.

Double-click on your project and click on "Manage NuGet Packages...".

Install the Swashbucle.AspNetCore NuGet,

Update your StartUp class in order for your project to recognize Swagger.
- public class Startup
- {
- public Startup( IConfiguration configuration )
- {
- Configuration = configuration;
- }
- public IConfiguration Configuration { get; }
- // 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 Swagger
- services.AddSwaggerGen( c =>
- {
- c.SwaggerDoc( "v1", new Info { Title = "Sample API", Version = "version 1" } );
- } );
- }
- // 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();
- // 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" );
- } );
- }
- app.UseMvc();
- }
- }
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.

ValueSamples class
- public static class ValueSamples
- {
- public static Dictionary<int, string> MyValue;
- public static void Initialize()
- {
- MyValue = new Dictionary<int, string>();
- MyValue.Add( 0, "Value 0" );
- MyValue.Add( 1, "Value 1" );
- MyValue.Add( 2, "Value 2" );
- }
- }
- [Route( "api/[controller]" )]
- [ApiController]
- public class ValuesController : ControllerBase
- {
- public ValuesController()
- {
- ValueSamples.Initialize();
- }
- // GET api/values
- [HttpGet]
- public ActionResult<Dictionary<int, string>> Get()
- {
- return ValueSamples.MyValue;
- }
- // GET api/values/5
- [HttpGet( "{id}" )]
- public ActionResult<string> Get( int id )
- {
- return ValueSamples.MyValue.GetValueOrDefault( id );
- }
- // POST api/values
- [HttpPost]
- public void Post( [FromBody] string value )
- {
- var maxKey = ValueSamples.MyValue.Max( x => x.Key );
- ValueSamples.MyValue.Add( maxKey + 1, value );
- }
- // PUT api/values/5
- [HttpPut( "{id}" )]
- public void Put( int id, [FromBody] string value )
- {
- ValueSamples.MyValue.Add( id, value );
- }
- // DELETE api/values/5
- [HttpDelete( "{id}" )]
- public void Delete( int id )
- {
- ValueSamples.MyValue.Remove( id );
- }
- }
Using the Swagger
Now, push F5 and complete your URL with "/swagger". It must look like this.
http://localhost:61986/swagger

Let's start testing our Web APIs.
Testing the "Get all" method
Calling the method from Swagger,
Validating the method called from the controller.
Checking the API response.

Testing getting a single result method
Inputting data in Swagger,

Testing to get a single non-existent record
Calling the method from,
Validating the call from the controller,

Swagger Response

Testing the post method
Input the data in the Post Method,
Validating the received data in the controller

Swagger Response

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

Nakul ChaudhariPosted Oct 14, 2019, 7:05 AM
Thanks for the article. I am successfully integrated Swagger but facing issue while consuming it in web application. I am using below code but getting 404 error "Using (var httpClient = new HttpClient()) { using (var response = await httpClient.GetAsync("my end point")) { string apiResponse = await response.Content.ReadAsStringAsync(); } }" Can you please help me on this?