Using swagger to generate the ASP. NET core Web API documentation

Source: Internet
Author: User
Tags response code



For building a consumer application, understanding the various methods of the API is a challenge for development. In order to make your API more conducive to reading.
Using swagger to generate good documents and help pages for your Web API,. NET core implements Swashbuckle.aspnetcore, and using swagger is very simple, just add a set of NuGet packages and modify startup to get it done.



. Swashbuckle.aspnetcore Open Source Project, the ASP. NET Core Web API generates swagger documentation



. Swagger is a machine readable representation of the RESTful style API interface. He can support the document Interaction Client SDK generation and has visibility



1. Getting Started



Three main components:



Swashbuck.AspNetCore.Swagger:Swagger object model and middleware, exposing swaggerdocument objects as JSON endpoints.



Swashbuckle.AspNetCore.SwaggerGen: A swagger generator that can build swaggerdocument objects directly from routes, controllers, and models. He is usually combined with swagger endpoint middleware to automatically expose Swaggerjson



The embedded version of the Swashbuckle.AspNetCore.SwaggerUI:Swagger UI tool, Swagger the embedded version of the UI tool, interprets Swagger json as a rich, customizable Web API feature description experience. It includes a built-in test harness for public methods.



2. Install the three components by following command



You can add swashbuckle using the following method



Install-package Swashbuckle.aspnetcore



3. Add and configure to swagger to middleware



Add the swagger generator to the Startup.cs configureservices method.


public void ConfigureServices (IServiceCollection services)
{
    services.AddDbContext <TodoContext> (opt => opt.UseInMemoryDatabase ("TodoList"));
    services.AddMvc ();
    // Register the Swagger generator and define one or more Swagger documents
    services.AddSwaggerGen (c =>
    {
        c.SwaggerDoc ("v1", new Info {Title = "My API", Version = "v1"});
    });
}
The Info class is contained in the Swashbuckle.AspNetCore.Swagger namespace.

In the Configure method of the Startup.cs class. Enable middleware services, mainly generate JSON documents and SwaggerUI.

public void Configure (IApplicationBuilder app)
{
    // Enable the middleware service to generate Swagger as a JSON endpoint
    app.UseSwagger ();
    // Enable the middleware service to swagger-ui and specify the Swagger JSON endpoint
    app.UseSwaggerUI (c =>
    {
        c.SwaggerEndpoint ("/ swagger / v1 / swagger.json", "My API V1");
    });
    app.UseMvc ();
}


Launch the app, navigate to http: // localhost: <random_port> /swagger/v1/swagger.json and display the document describing the endpoint.

You can view the generated Swagger UI by browsing http: // localhost: <random_port> / swagger.

 

 

 

Every public action method in TodoController can be tested from the UI. Click a method name to expand the node. Add parameters, stand-alone "test"!

4.Customization and scalability

Swagger provides a documented object model and custom UI.

API Info and Description
By passing some information to the AddSwaggerGen methods, such as 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 = "Shayne Boyer", Email = "", Url = "https://twitter.com/spboyer"},
        License = new License {Name = "Use under LICX", Url = "https://example.com/license"}
    });
});
The picture below describes the version information displayed by Swagger UI

XML comments
Enable XML comments


Configure Swagger so that Swagger uses the generated XML file. For Linux and non-Window operating systems, file names and paths are case sensitive.

public void ConfigureServices (IServiceCollection services)
{
    services.AddDbContext <TodoContext> (opt => opt.UseInMemoryDatabase ("TodoList"));
    services.AddMvc ();

    // Register the Swagger generator, defining one or more Swagger documents
    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 = "Shayne Boyer", Email = "", Url = "https://twitter.com/spboyer"},
            License = new License {Name = "Use under LICX", Url = "https://example.com/license"}
        });

        // Set the comments path for the Swagger JSON and UI.
        var basePath = PlatformServices.Default.Application.ApplicationBasePath;
        var xmlPath = Path.Combine (basePath, "TodoApi.xml");
        c.IncludeXmlComments (xmlPath);
    });
}
In the previous code, ApplicationBasePath gets the basic path of the application. Used to find XML annotation files. TodoApi.xml is only applicable in this example, the name of the XML annotation file generated by the citation is based on the name of the application.

Add comments like

/// <summary>
/// Deletes a specific TodoItem.
/// </ summary>
/// <param name = "id"> </ param>
[HttpDelete ("{id}")]
public IActionResult Delete (long id)
{
    var todo = _context.TodoItems.FirstOrDefault (t => t.Id == id);
    if (todo == null)
    {
        return NotFound ();
    }

    _context.TodoItems.Remove (todo);
    _context.SaveChanges ();
    return new NoContentResult ();
}
Add the following comment to the Create method

/// <summary>
/// Creates a TodoItem.
/// </ summary>
/// <remarks>
/// Sample request:
///
/// POST / Todo
/// {
/// "id": 1,
/// "name": "Item1",
/// "isComplete": true
///}
///
/// </ remarks>
/// <param name = "item"> </ param>
/// <returns> A newly-created TodoItem </ returns>
/// <response code = "201"> Returns the newly-created item </ response>
/// <response code = "400"> If the item is null </ response>
[HttpPost]
[ProducesResponseType (typeof (TodoItem), 201)]
[ProducesResponseType (typeof (TodoItem), 400)]
public IActionResult Create ([FromBody] TodoItem item)
{
    if (item == null)
    {
        return BadRequest ();
    }

    _context.TodoItems.Add (item);
    _context.SaveChanges ();

    return CreatedAtRoute ("GetTodo", new {id = item.Id}, item);
}
 Data Annotations
Decorate the model with properties in System.ComponentModel.DataAnnotations to help drive Swagger UI components.

Add the [Required] property to the Name property of the TodoItem class:

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace TodoApi.Models
{
    public class TodoItem
    {
        public long Id {get; set;}

        [Required]
        public string Name {get; set;}

        [DefaultValue (false)]
        public bool IsComplete {get; set;}
    }
}
This property changes the UI behavior and changes the underlying JSON schema:

"definitions": {
    "TodoItem": {
        "required": [
            "name"
        ],
        "type": "object",
        "properties": {
            "id": {
                "format": "int64",
                "type": "integer"
            },
            "name": {
                "type": "string"
            },
            "isComplete": {
                "default": false,
                "type": "boolean"
            }
        }
    }
},
Add the [Produces ("application / json")] attribute to the API controller. Its purpose is to declare that the controller return type supports application / json.

namespace TodoApi.Controllers
{
    [Produces ("application / json")]
    [Route ("api / [controller]")]
    public class TodoController: Controller

{
        private readonly TodoContext _context;
As the use of data annotations in Web APIs increases, UI and API help pages become more descriptive and useful.

Declare the response type

People who use the API care most about what is returned. Especially response types and error codes
When the request is null, the Create operation returns 201 successful creation and 400 bad request. If there is no suitable document in the Swagger UI. Consumers don't understand these results. Solved by adding the annotation class below

/// <summary>
/// Creates a TodoItem.
/// </ summary>
/// <remarks>
/// Sample request:
///
/// POST / Todo
/// {
/// "id": 1,
/// "name": "Item1",
/// "isComplete": true
///}
///
/// </ remarks>
/// <param name = "item"> </ param>
/// <returns> A newly-created TodoItem </ returns>
/// <response code = "201"> Returns the newly-created item </ response>
/// <response code = "400"> If the item is null </ response>
[HttpPost]
[ProducesResponseType (typeof (TodoItem), 201)]
[ProducesResponseType (typeof (TodoItem), 400)]
public IActionResult Create ([FromBody] TodoItem item)
{
    if (item == null)
    {
        return BadRequest ();
    }

    _context.TodoItems.Add (item);
    _context.SaveChanges ();

    return CreatedAtRoute ("GetTodo", new {id = item.Id}, item);
}
Swagger UI now clearly documents the expected HTTP response code:


 

Use Swagger to generate asp.net core Web API documentation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.