3
votes

I have swagger setup so that it generates the open Api Specification & Swagger Ui on project startup using NSwag based on the controllers in my WebApi. I would like to enhance the swagger Ui to include

  • A summary/description for each endpoint
  • Example parameter inputs for endpoints that require them
  • Example request body for POST calls
  • An example access token that can be used only in the swagger documentation to easily authenticate and be able to try everything out (a bit like in this example https://petstore.swagger.io/)

I'm new to NSwag and unsure how to approach adding these enhancements to my code, like where to add them, what i need to use (annotations on controllers? XML comments? another way?) I've tried editing the specification in 'Swagger Editor' but don't see how this can be the way to go since this gets re-generated on every application startup.

I've read the NSwag documentation but that seems to be all about adding the ASP.NET Core middleware, which I already have configured.

Edit: I now have a description at the top of the page, and have been able to add an example with the remarks tag in XML comments - is there a more elegant way to do this rather than using XML comments?

2

2 Answers

3
votes

A description at the top of the page

To customize the API info and description using Nswag, in the Startup.ConfigureServices method, a configuration action passed to the AddSwaggerDocument method adds information such as the author, license, and description:

        services.AddSwaggerDocument(config =>
        {
            config.PostProcess = document =>
            {
                document.Info.Version = "v1";
                document.Info.Title = "ToDo API";
                document.Info.Description = "A simple ASP.NET Core web API";
                document.Info.TermsOfService = "None";
                document.Info.Contact = new NSwag.OpenApiContact
                {
                    Name = "Shayne Boyer",
                    Email = string.Empty,
                    Url = "https://twitter.com/spboyer"
                };
                document.Info.License = new NSwag.OpenApiLicense
                {
                    Name = "Use under LICX",
                    Url = "https://example.com/license"
                };
            };
        });

The Swagger UI displays the version's information as below:

enter image description here

  • A summary/description for each endpoint Example parameter inputs for
  • endpoints that require them Example request body for POST calls An
  • example access token that can be used only in the swagger
  • documentation to easily authenticate and be able to try everything out (a bit like in this example https://petstore.swagger.io/)

You could add the description/example by adding the following elements to the action header.

Use the <summary> element to describe the Endpoint.

Use the <remarks> element to supplements information specified in the <summary> element and provides a more robust Swagger UI. The <remarks> element content can consist of text, JSON, or XML. You could also use it to add sample.

Use the <param> element to add the required parameters. Besides, you could also use the Data annotations attribute with the Model, it will change the UI behavior.

Use the <response> elements to describe response types.

sample code as below:

    /// <summary>
    /// Creates a TodoItem.
    /// </summary>
    /// <remarks>
    /// Sample request:
    ///
    ///     POST /Todo
    ///     {
    ///        "id": 1,
    ///        "name": "Item1",
    ///        "isComplete": true
    ///     }
    ///
    /// </remarks>
    /// <param name="todoitem"></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>
    #region snippet_CreateActionAttributes
    [ProducesResponseType(StatusCodes.Status201Created)]     // Created
    [ProducesResponseType(StatusCodes.Status400BadRequest)]  // BadRequest
    #endregion snippet_CreateActionAttributes
    #region snippet_CreateAction
    [HttpPost]
    public ActionResult<TodoItem> Create(TodoItem todoitem)
    {
        _context.TodoItems.Add(todoitem);
        _context.SaveChanges();

        return CreatedAtRoute("GetTodo", new { id = todoitem.Id }, todoitem);
    }

The Swagger UI now looks as below:

enter image description here

More detail information, please check the following tutorials:

Customize API documentation using NSwag

Customize API info and description using Swashbuckle

3
votes

Figured this out now, ended up using operation processors to configure the Swagger UI/OpenApi endpoint summary, request examples, path parameter example values and the possible UI response codes

There isn't a lot of documentation online for doing it this way (all i could find was the XML comment way of doing it so this took a lot of trial and error to get this working)

Posting my solution here for anyone else who would prefer not to clutter up their controllers with XML comments.

  1. Apply OpenApiOperationProcessor attribute to the controller action enter image description here

  2. Create the Operation Processor and code the SwaggerUI customizations enter image description here

  3. Example values for path parameters can be filled out as so enter image description here