When consuming a Web API, understanding its various methods can be challenging for a developer. Swagger, also known as Open API, solves the problem of generating useful documentation and help pages for Web APIs. It provides benefits such as interactive documentation, client SDK generation, and API discoverability.
Swagger
Swagger is a language-agnostic specification for describing REST APIs. The Swagger project was donated to the OpenAPI Initiative, where it's now referred to as Open API. Swagger is useful
- To minimize the amount of work needed to connect disassociated services.
- To reduce the amount of time needed to accurately document a service.
Swagger specification (swagger.json)
The core to the Swagger flow is the Swagger specification—by default, a document named swagger.json. It's generated by the Swagger tool chain (or third-party implementations of it) based on your service. It describes the capabilities of your API and how to access it with HTTP. It drives the Swagger UI and is used by the tool chain to enable discovery and client code generation
Example
{ "swagger": "2.0", "info": { "version": "v1", "title": "API V1" }, "basePath": "/", "paths": { "/api/Todo": { "get": { "tags": [ "Todo" ], "operationId": "ApiTodoGet", "consumes": [], "produces": [ "text/plain", "application/json", "text/json" ], "responses": { "200": { "description": "Success", "schema": { "type": "array", "items": { "$ref": "#/definitions/TodoItem" } } } } }, "post": { ... } }, "/api/Todo/{id}": { "get": { ... }, "put": { ... }, "delete": { ... }, "definitions": { "TodoItem": { "type": "object", "properties": { "id": { "format": "int64", "type": "integer" }, "name": { "type": "string" }, "isComplete": { "default": false, "type": "boolean" } } } }, "securityDefinitions": {} }
Swagger UI
Swagger UI offers a web-based UI that provides information about the service, using the generated Swagger specification.Swashbuckle include an embedded version of Swagger UI, so that it can be hosted in your ASP.NET Core app using a middleware registration call
Integrating Swagger using Swashbuckle
We can integrate the Swagger in our application using Swashbuckle with the following steps
- Add package Swashbuckle.AspNetCore to the application
- Add the Swagger generator to the services collection in the Startup.ConfigureServices method
using Swashbuckle.AspNetCore.Swagger; public void ConfigureServices(IServiceCollection services) { services.AddDbContext(opt => opt.UseInMemoryDatabase("TodoList")); services.AddMvc(); // Register the Swagger generator, defining one or more Swagger documents services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" }); }); }
- In the Startup.Configure method, enable the middleware for serving the generated JSON document and the Swagger UI
// 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"); });
- This will enable the basic integration of the swagger. You can check the generated swagger docuement describing the endpoints in [BASE-URL]/swagger/v1/swagger.json and Swagger UI can be found in [BASE-URL]/swagger
Customization:
- To get the Swagger at APP root directly, set the RoutePrefix property to an empty string
app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); c.RoutePrefix = string.Empty; });
- The configuration action passed to the AddSwaggerGen method adds information such as the author, license, and description
services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Version = "v1", Title = "ToDo API", Description = "A simple example ASP.NET Core Web API", TermsOfService = "None", Contact = new Contact { Name = "Contact name", Email = "Test@test.com", Url = "Web site URL" }, License = new License { Name = "Use under LICX", Url = "Licence terms page url" } }); });
- We can show the xml comments added to the methods and properties in the Swagger UI. For that we need to enable the XML documentation File for the project.
- Enable XML documentation for the project
- In Visual Studio, Right-click the project in Solution Explorer and select Properties
- Check the XML documentation file box under the Output section of the Build tab
Note: If you are using Visual Studio Code, add the following in .csproj file
bin\Debug\$(TargetFramework)\$(MSBuildProjectName).xml
- Configure in ConfigureServices
public void ConfigureServices(IServiceCollection services) { services.AddDbContext(opt => opt.UseInMemoryDatabase("TodoList")); services.AddMvc(); // Register the Swagger generator, defining one or more Swagger documents services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" }); // Set the comments path for the Swagger JSON and UI. var xmlFile = $"{Assembly.GetEntryAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); }); }
Happy Coding 😊
You can find more from here and here
0 comments:
Post a Comment