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
Install the Swashbucle.AspNetCore NuGet,
.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. public IConfiguration Configuration { get; }
  8. // This method gets called by the runtime. Use this method to add services to the container.
  9. public void ConfigureServices( IServiceCollection services )
  10. {
  11. services.AddMvc().SetCompatibilityVersion( CompatibilityVersion.Version_2_1 );
  12. // Register Swagger
  13. services.AddSwaggerGen( c =>
  14. {
  15. c.SwaggerDoc( "v1", new Info { Title = "Sample API", Version = "version 1" } );
  16. } );
  17. }
  18. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  19. public void Configure( IApplicationBuilder app, IHostingEnvironment env )
  20. {
  21. if ( env.IsDevelopment() )
  22. {
  23. app.UseDeveloperExceptionPage();
  24. // Enable middleware to serve generated Swagger as a JSON endpoint.
  25. app.UseSwagger();
  26. // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
  27. // specifying the Swagger JSON endpoint.
  28. app.UseSwaggerUI( c =>
  29. {
  30. c.SwaggerEndpoint( "/swagger/v1/swagger.json", "My API V1" );
  31. } );
  32. }
  33. app.UseMvc();
  34. }
  35. }

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<int, string> MyValue;
  4. public static void Initialize()
  5. {
  6. MyValue = new Dictionary<int, string>();
  7. MyValue.Add( 0, "Value 0" );
  8. MyValue.Add( 1, "Value 1" );
  9. MyValue.Add( 2, "Value 2" );
  10. }
  11. }
ValuesController controller
  1. [Route( "api/[controller]" )]
  2. [ApiController]
  3. public class ValuesController : ControllerBase
  4. {
  5. public ValuesController()
  6. {
  7. ValueSamples.Initialize();
  8. }
  9. // GET api/values
  10. [HttpGet]
  11. public ActionResult<Dictionary<int, string>> Get()
  12. {
  13. return ValueSamples.MyValue;
  14. }
  15. // GET api/values/5
  16. [HttpGet( "{id}" )]
  17. public ActionResult<string> Get( int id )
  18. {
  19. return ValueSamples.MyValue.GetValueOrDefault( id );
  20. }
  21. // POST api/values
  22. [HttpPost]
  23. public void Post( [FromBody] string value )
  24. {
  25. var maxKey = ValueSamples.MyValue.Max( x => x.Key );
  26. ValueSamples.MyValue.Add( maxKey + 1, value );
  27. }
  28. // PUT api/values/5
  29. [HttpPut( "{id}" )]
  30. public void Put( int id, [FromBody] string value )
  31. {
  32. ValueSamples.MyValue.Add( id, value );
  33. }
  34. // DELETE api/values/5
  35. [HttpDelete( "{id}" )]
  36. public void Delete( int id )
  37. {
  38. ValueSamples.MyValue.Remove( id );
  39. }
  40. }

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