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 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...".
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; }
-
-
- public void ConfigureServices( IServiceCollection services )
- {
- services.AddMvc().SetCompatibilityVersion( CompatibilityVersion.Version_2_1 );
-
-
- services.AddSwaggerGen( c =>
- {
- c.SwaggerDoc( "v1", new Info { Title = "Sample API", Version = "version 1" } );
- } );
- }
-
-
- public void Configure( IApplicationBuilder app, IHostingEnvironment env )
- {
- if ( env.IsDevelopment() )
- {
- app.UseDeveloperExceptionPage();
-
-
- app.UseSwagger();
-
-
-
- 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" );
- }
- }
ValuesController controller
- [Route( "api/[controller]" )]
- [ApiController]
- public class ValuesController : ControllerBase
- {
- public ValuesController()
- {
- ValueSamples.Initialize();
- }
-
-
- [HttpGet]
- public ActionResult<Dictionary<int, string>> Get()
- {
- return ValueSamples.MyValue;
- }
-
-
- [HttpGet( "{id}" )]
- public ActionResult<string> Get( int id )
- {
- return ValueSamples.MyValue.GetValueOrDefault( id );
- }
-
-
- [HttpPost]
- public void Post( [FromBody] string value )
- {
- var maxKey = ValueSamples.MyValue.Max( x => x.Key );
-
- ValueSamples.MyValue.Add( maxKey + 1, value );
- }
-
-
- [HttpPut( "{id}" )]
- public void Put( int id, [FromBody] string value )
- {
- ValueSamples.MyValue.Add( id, value );
- }
-
-
- [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