There are three components that we need to buckle-up in our Web API application. These are, not surprisingly, called Swashbuckle:
- Swashbuckle.AspNetCore.SwaggerGen : builds SwaggerDocument objects from your router, controllers and models.
- Swashbuckle.SwaggerUI : embedded version of Swagger UI tool which uses the above documents for a rich customizable experience for describing the Web API functionality and includes built in test harness capabilities for the public methods.
- Swashbuckle.AspNetCore.Swagger: Swagger object model and middleware to expose SwaggerDocument objects as JSON endpoints.
1) If you are using Visual Studio 2017, execute the following command from the Package Manager Console:
install-package --version 2.1.0 Swashbuckle.AspNetCore
You can find the Package Manager Console in Visual Studio 2017 at Tools >> NuGet Package Manager >> Package Manager Console.
2) From a terminal window in the main project folder, enter the following command:
dotnet add package Swashbuckle.AspNetCore -Version 2.1.0
using Swashbuckle.AspNetCore.Swagger;
Next, add the Swagger generator to bottom of the ConfigureServices() method in Startup.cs:
// Register the Swagger generator, defining one or more Swagger
// documents
services.AddSwaggerGen(c => {
c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
});
// Enable middleware to serve generated Swagger as 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");
});
NOTE: You can exclude the service generated by an API controller by annotating the controller class with: [ApiExplorerSettings(IgnoreApi = true)]
Run your application with CTRL + F5.
Point your browser to http://localhost:{port number}/swagger/v1/swagger.json and you will see a JSON document that describes the endpoints of your service.
You can also see the Swagger UI at URL
http://localhost{port number}/swagger.
In the above example the API service is Studentapi. Your service will be under API V1. Click on it and you will see something similar to the following:
To test out GET, click on the first blue GET button and the section will expand describing to you the structure of your object:
Click on the “Try it out!” button to view the data coming back from the service for all items in the collection:
Click on the first blue GET button again to collapse the section. Now, click on the second blue GET button to test retrieval of an item by id.
Enter a value for ‘id’ then click the “Try it out!” button. It should get for you the item for that id.
In a similar manner, go ahead and test out all the other POST, DELETE, and PUT buttons.
The official Swagger website at http://swagger.io/. You can generate a Swagger client for most programming languages at http://editor.swagger.io/.
No comments:
Post a Comment