Understanding the various methods of an API can be a challenge for a developer when building a consuming application.

Generating good documentation and help pages as a part of your Web API using Swagger with the .NET Core implementation Swashbuckle is as easy as adding a couple of NuGet packages and modifying the Startup.cs.

  • Swashbuckle is an open source project for generating Swagger documents for Web APIs that are built with ASP.NET Core MVC.

  • Swagger is a machine readable representation of a RESTful API that enables support for interactive documentation, client SDK generation and discoverability.

This tutorial builds on the sample on Building Your First Web API with ASP.NET Core MVC and Visual Studio. If you'd like to follow along, download the sample at https://github.com/aspnet/Docs/tree/master/aspnetcore/tutorials/first-web-api/sample.

Getting Started

There are two core components to Swashbuckle

  • Swashbuckle.SwaggerGen : provides the functionality to generate JSON Swagger documents that describe the objects, methods, return types, etc.

  • Swashbuckle.SwaggerUI : an embedded version of the 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.

NuGet Packages

You can add Swashbuckle with any of the following approaches:

  • From the Package Manager Console:
Copy
bash
  1. Install-Package Swashbuckle -Pre
  • In Visual Studio:

    • Right click your project in Solution Explorer > Manage NuGet Packages
    • Enter Swashbuckle in the search box
    • Check "Include prerelease"
    • Set the Package source to nuget.org
    • Tap the Swashbuckle package and then tap Install

Add and configure Swagger to the middleware

Add SwaggerGen to the services collection in the Configure method, and in the ConfigureServices method, enable the middleware for serving generated JSON document and the SwaggerUI.

Copy
C#
  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3. // Add framework services.
  4. services.AddMvc();
  5. services.AddLogging();
  6. // Add our repository type
  7. services.AddSingleton<ITodoRepository, TodoRepository>();
  8. // Inject an implementation of ISwaggerProvider with defaulted settings applied
  9. services.AddSwaggerGen();
  10. }
  11. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  12. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
  13. {
  14. app.UseMvcWithDefaultRoute();
  15. // Enable middleware to serve generated Swagger as a JSON endpoint
  16. app.UseSwagger();
  17. // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
  18. app.UseSwaggerUi();
  19. }

In Visual Studio, press ^F5 to launch the app and navigate to http://localhost:<random_port>/swagger/v1/swagger.json to see the document generated that describes the endpoints.

Note

Microsoft Edge, Google Chrome and Firefox display JSON documents natively. There are extensions for Chrome that will format the document for easier reading. Example below reduced for brevity.

Copy
JavaScript
  1. {
  2. "swagger": "2.0",
  3. "info": {
  4. "version": "v1",
  5. "title": "API V1"
  6. },
  7. "basePath": "/",
  8. "paths": {
  9. "/api/Todo": {
  10. "get": {
  11. "tags": [
  12. "Todo"
  13. ],
  14. "operationId": "ApiTodoGet",
  15. "consumes": [],
  16. "produces": [
  17. "text/plain",
  18. "application/json",
  19. "text/json"
  20. ],
  21. "responses": {
  22. "200": {
  23. "description": "OK",
  24. "schema": {
  25. "type": "array",
  26. "items": {
  27. "$ref": "#/definitions/TodoItem"
  28. }
  29. }
  30. }
  31. },
  32. "deprecated": false
  33. },
  34. "post": {
  35. ...
  36. }
  37. },
  38. "/api/Todo/{id}": {
  39. "get": {
  40. ...
  41. },
  42. "put": {
  43. ...
  44. },
  45. "delete": {
  46. ...
  47. },
  48. "definitions": {
  49. "TodoItem": {
  50. "type": "object",
  51. "properties": {
  52. "key": {
  53. "type": "string"
  54. },
  55. "name": {
  56. "type": "string"
  57. },
  58. "isComplete": {
  59. "type": "boolean"
  60. }
  61. }
  62. }
  63. },
  64. "securityDefinitions": {}
  65. }

This document is used to drive the Swagger UI which can be viewed by navigating to http://localhost:<random_port>/swagger/ui

Each of the methods in the ToDo controller can be tested from the UI. Tap a method to expand the section, add any necessary parameters and tap "Try it out!".

Customization & Extensibility

Swagger is not only a simple way to represent the API, but has options for documenting the object model, as well as customizing the interactive UI to match your look and feel or design language.

API Info and Description

The ConfigureSwaggerGen method can be used to add information such as the author, license, description.

Copy
C#
  1. services.ConfigureSwaggerGen(options =>
  2. {
  3. options.SingleApiVersion(new Info
  4. {
  5. Version = "v1",
  6. Title = "ToDo API",
  7. Description = "A simple example ASP.NET Core Web API",
  8. TermsOfService = "None",
  9. Contact = new Contact { Name = "Shayne Boyer", Email = "", Url = "http://twitter.com/spboyer"},
  10. License = new License { Name = "Use under LICX", Url = "http://url.com" }
  11. });
  12. });

The following image shows the Swagger UI displaying the version information added.

XML Comments

To enable XML comments, right click the project in Visual Studio and select Properties and then check the XML Documentation file box under the Output Settings section.

Configure Swagger to use the generated XML file.

Note

For Linux or non-Windows operating systems, file names and paths can be case sensitive. So ToDoApi.XMLwould be found on Windows but not CentOS for example.

Copy
C#
  1. // This method gets called by the runtime. Use this method to add services to the container.
  2. public void ConfigureServices(IServiceCollection services)
  3. {
  4. // Add framework services.
  5. services.AddMvc();
  6. services.AddLogging();
  7. // Add our repository type.
  8. services.AddSingleton<ITodoRepository, TodoRepository>();
  9. // Inject an implementation of ISwaggerProvider with defaulted settings applied.
  10. services.AddSwaggerGen();
  11. // Add the detail information for the API.
  12. services.ConfigureSwaggerGen(options =>
  13. {
  14. options.SingleApiVersion(new Info
  15. {
  16. Version = "v1",
  17. Title = "ToDo API",
  18. Description = "A simple example ASP.NET Core Web API",
  19. TermsOfService = "None",
  20. Contact = new Contact { Name = "Shayne Boyer", Email = "", Url = "http://twitter.com/spboyer"},
  21. License = new License { Name = "Use under LICX", Url = "http://url.com" }
  22. });
  23. //Determine base path for the application.
  24. var basePath = PlatformServices.Default.Application.ApplicationBasePath;
  25. //Set the comments path for the swagger json and ui.
  26. var xmlPath = Path.Combine(basePath, "TodoApi.xml");
  27. options.IncludeXmlComments(xmlPath);
  28. });
  29. }
  30. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  31. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
  32. {
  33. app.UseStaticFiles();
  34. app.UseMvcWithDefaultRoute();
  35. // Enable middleware to serve generated Swagger as a JSON endpoint.
  36. app.UseSwagger();
  37. // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
  38. app.UseSwaggerUi();
  39. }

In the code above, ApplicationBasePath gets the base path of the app, which is needed to set the full path to the XML comments. TodoApi.xml only works for this example, the name of the generated XML comments file is based on the name of your application.

Adding the triple slash comments to the method enhances the Swagger UI by adding the description to the header of the section.

Copy
C#
  1. /// <summary>
  2. /// Deletes a specific TodoItem.
  3. /// </summary>
  4. /// <param name="id"></param>
  5. [HttpDelete("{id}")]
  6. public void Delete(string id)
  7. {
  8. TodoItems.Remove(id);
  9. }

Note that the UI is driven by the generated JSON file, and these comments are also in that file as well.

Copy
JavaScript
  1. "delete": {
  2. "tags": [
  3. "Todo"
  4. ],
  5. "summary": "Deletes a specific TodoItem",
  6. "operationId": "ApiTodoByIdDelete",
  7. "consumes": [],
  8. "produces": [],
  9. "parameters": [
  10. {
  11. "name": "id",
  12. "in": "path",
  13. "description": "",
  14. "required": true,
  15. "type": "string"
  16. }
  17. ],
  18. "responses": {
  19. "204": {
  20. "description": "No Content"
  21. }
  22. },
  23. "deprecated": false
  24. }

Here is a more robust example, adding <remarks /> where the content can be just text or adding the JSON or XML object for further documentation of the method.

Copy
C#
  1. /// <summary>
  2. /// Creates a TodoItem.
  3. /// </summary>
  4. /// <remarks>
  5. /// Note that the key is a GUID and not an integer.
  6. ///
  7. /// POST /Todo
  8. /// {
  9. /// "key": "0e7ad584-7788-4ab1-95a6-ca0a5b444cbb",
  10. /// "name": "Item1",
  11. /// "isComplete": true
  12. /// }
  13. ///
  14. /// </remarks>
  15. /// <param name="item"></param>
  16. /// <returns>New Created Todo Item</returns>
  17. /// <response code="201">Returns the newly created item</response>
  18. /// <response code="400">If the item is null</response>
  19. [HttpPost]
  20. [ProducesResponseType(typeof(TodoItem), 201)]
  21. [ProducesResponseType(typeof(TodoItem), 400)]
  22. public IActionResult Create([FromBody, Required] TodoItem item)
  23. {
  24. if (item == null)
  25. {
  26. return BadRequest();
  27. }
  28. TodoItems.Add(item);
  29. return CreatedAtRoute("GetTodo", new { id = item.Key }, item);
  30. }

Notice the enhancement of the UI with these additional comments.

DataAnnotations

You can decorate the API controller with System.ComponentModel.DataAnnotations to help drive the Swagger UI components.

Adding the [Required] annotation to the Name property of the TodoItem class will change the ModelSchema information in the UI. [Produces("application/json")]RegularExpression validators and more will further detail the information delivered in the generated page. The more metadata that is in the code produces a more desciptive UI or API help page.

Copy
C#
  1. using System;
  2. using System.ComponentModel;
  3. using System.ComponentModel.DataAnnotations;
  4. namespace TodoApi.Models
  5. {
  6. public class TodoItem
  7. {
  8. public string Key { get; set; }
  9. [Required]
  10. public string Name { get; set; }
  11. [DefaultValue(false)]
  12. public bool IsComplete { get; set; }
  13. }
  14. }

Describing Response Types

Consuming developers are probably most concerned with what is returned; specifically response types, error codes (if not standard). These are handled in the XML comments and DataAnnotations.

Take the Create() method for example, currently it returns only "201 Created" response by default. That is of course if the item is in fact created, or a "204 No Content" if no data is passed in the POST Body. However, there is no documentation to know that or any other response. That can be fixed by adding the following piece of code.

Copy
C#
  1. /// <summary>
  2. /// Creates a TodoItem.
  3. /// </summary>
  4. /// <remarks>
  5. /// Note that the key is a GUID and not an integer.
  6. ///
  7. /// POST /Todo
  8. /// {
  9. /// "key": "0e7ad584-7788-4ab1-95a6-ca0a5b444cbb",
  10. /// "name": "Item1",
  11. /// "isComplete": true
  12. /// }
  13. ///
  14. /// </remarks>
  15. /// <param name="item"></param>
  16. /// <returns>New Created Todo Item</returns>
  17. /// <response code="201">Returns the newly created item</response>
  18. /// <response code="400">If the item is null</response>
  19. [HttpPost]
  20. [ProducesResponseType(typeof(TodoItem), 201)]
  21. [ProducesResponseType(typeof(TodoItem), 400)]
  22. public IActionResult Create([FromBody, Required] TodoItem item)
  23. {
  24. if (item == null)
  25. {
  26. return BadRequest();
  27. }
  28. TodoItems.Add(item);
  29. return CreatedAtRoute("GetTodo", new { id = item.Key }, item);
  30. }

Customizing the UI

The stock UI is very functional as well as presentable, however when building documentation pages for your API you want it to represent your brand or look and feel.

Accomplishing that task with the Swashbuckle components is simple but requires adding the resources to serve static files that would not normally be included in a Web API project and then building the folder structure to host those files.

Add the "Microsoft.AspNetCore.StaticFiles": "1.0.0-*" NuGet package to the project.

Enable static files middleware.

Copy
C#
  1. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  2. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
  3. {
  4. // Enable static files middleware.
  5. app.UseStaticFiles();
  6. app.UseMvcWithDefaultRoute();
  7. // Enable middleware to serve generated Swagger as a JSON endpoint
  8. app.UseSwagger();
  9. // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
  10. app.UseSwaggerUi();
  11. }

Acquire the core index.html file used for the Swagger UI page from the Github repository <https://github.com/domaindrivendev/Ahoy/tree/master/test/WebSites/CustomizedUi/wwwroot/swagger/ui>_ and put that in the wwwroot/swagger/ui folder and also create a new custom.css file in the same folder.

Reference custom.css in the index.html file.

Copy
html
  1. <link href='custom.css' media='screen' rel='stylesheet' type='text/css' />

The following CSS provides a simple sample of a custom header title to the page.

custom.css file

Copy
css

  1. .swagger-section #header
  2. {
  3. border-bottom: 1px solid #000000;
  4. font-style: normal;
  5. font-weight: 400;
  6. font-family: "Segoe UI Light","Segoe WP Light","Segoe UI","Segoe WP",Tahoma,Arial,sans-serif;
  7. background-color: black;
  8. }
  9. .swagger-section #header h1
  10. {
  11. text-align: center;
  12. font-size: 20px;
  13. color: white;
  14. }

index.html body

Copy
html
  1. <body class="swagger-section">
  2. <div id="header">
  3. <h1>ToDo API Documentation</h1>
  4. </div>
  5. <div id="message-bar" class="swagger-ui-wrap" data-sw-translate>&nbsp;</div>
  6. <div id="swagger-ui-container" class="swagger-ui-wrap"></div>
  7. </body>

There is much more you can do with the page, see the full capabilities for the UI resources at the Swagger UI Github repository.

ASP.NET Web API Help Pages using Swagger的更多相关文章

  1. 使用ASP.NET Web API Help Pages 创建在线接口文档

    操作步骤 1.新建Web API项目 2.在项目Areas文件夹下找到以下文件,取消注释图中代码. 3.右键解决方案,属性,如图设置. 4.运行程序,点击右上角API 接口列表: 详情-无参数: 详情 ...

  2. web API help pages with Swagger / OpenAPI

    https://docs.microsoft.com/en-us/aspnet/core/tutorials/web-api-help-pages-using-swagger?view=aspnetc ...

  3. ASP.NET Core 中文文档 第二章 指南 (09) 使用 Swagger 生成 ASP.NET Web API 在线帮助测试文档

    原文:ASP.NET Web API Help Pages using Swagger 作者:Shayne Boyer 翻译:谢炀(kiler) 翻译:许登洋(Seay) 对于开发人员来说,构建一个消 ...

  4. Swagger 生成 ASP.NET Web API

    使用 Swagger 生成 ASP.NET Web API 在线帮助测试文档 原文:ASP.NET Web API Help Pages using Swagger作者:Shayne Boyer翻译: ...

  5. Asp.Net Web Api中使用Swagger

    关于swagger 设计是API开发的基础.Swagger使API设计变得轻而易举,为开发人员.架构师和产品所有者提供了易于使用的工具. 官方网址:https://swagger.io/solutio ...

  6. [水煮 ASP.NET Web API2 方法论](1-1)在MVC 应用程序中添加 ASP.NET Web API

    问题 怎么样将 Asp.Net Web Api 加入到现有的 Asp.Net MVC 项目中 解决方案 在 Visual Studio 2012 中就已经把 Asp.Net Web Api 自动地整合 ...

  7. Creating Help Pages for ASP.NET Web API -摘自网络

    When you create a web API, it is often useful to create a help page, so that other developers will k ...

  8. ASP.NET Web API 文件產生器 - 使用 Swagger

    转帖:http://kevintsengtw.blogspot.hk/2015/12/aspnet-web-api-swagger.html Swagger 是一套 API 互動文件產生器,使用 HT ...

  9. ASP.NET Web API 中使用 swagger 来管理 API 文档

    本文以 ASP.NET Web API 为后台框架,利用 EF6 连接 postgreSQL 数据库,使用 swagger 来生成 REST APIs文档.文章分二个部分,第一部分主要讲如何用 EF6 ...

随机推荐

  1. 表格table嵌套,边框合并问题

    [问题] 外层table与内层table嵌套,内外表格都需边框时,设置“border=1”,但边框会重复,造成某些地方边框粗,有些地方边框细的问题.   [解决办法]: 外表格样式: <tabl ...

  2. WEB核心IOC篇

    ioc概念的理解:(不是技术是一种设计思想) IOC (控制反转)     IoC(Inverse of Control)的字面意思是 控制反转 ,它包括两个内容:     其一是控制 (控制对象的实 ...

  3. Java并发之Condition 并发同步控制

    package com.thread.test.thread; import java.util.PriorityQueue; import java.util.concurrent.locks.Co ...

  4. 【Python】-【类解析】--【脚本实例】

    通过脚本事例,解析下Python中类的几个概念在脚本中的应用 脚本如下: ++++++++++++++++++++++++++++++++++++++++ #!/usr/bin/env python# ...

  5. (企业面试部分)超详细思路讲解SQL语句的查询实现,及数据的创建。

    企业面试部分详细的SQL问题,思路讲解 第一步:创建数据库表,及插入数据信息 --Student(S#,Sname,Sage,Ssex) 学生表 CREATE TABLE student( sno ) ...

  6. python中mysqldb的用法

    1.引入MySQLdb库 import MySQLdb 2.和数据库建立连接 conn=MySQLdb.connect(host="localhost",user="ro ...

  7. 省级联动(使用ajax实现)

    在博客园学习了很多实用的东西,现在该慢慢开始自己写写博客文章, 由于本人水平有限,刚走出校园的小菜鸟,另外,文章在表述和代码方面如有不妥之处,欢迎批评指正.留下你 的脚印,欢迎评论! 有什么问题,可以 ...

  8. x01.os.9: 进程切换

    进入内核后,当然不能无所事事.先创建三个进程,分别打印 A,B,C.虽然只是简单的打印,但却是一切扩展的基础,不可等闲视之. 进程切换,涉及一系列的寄存器需要保护,于是,就有了 ProcessStac ...

  9. x01.os.1: BIOS 中断

    这只是一点准备工作.为了显示字符串,需要调用中断:int  0x10 (AH=0x13).具体参数设置,参考我的归纳整理如下: INT 10 (AH = 0) -----------------功能: ...

  10. ELF Format 笔记(八)—— 符号的类型和属性(st_info)

    我是天空里的一片云,偶尔投影在你的波心,你不必讶异,更无须欢喜,在转瞬间消灭了踪影.你我相逢在黑夜的海上,你有你的,我有我的,方向:你记得也好,最好你忘掉,在这交会时互放的光亮! —— 徐志摩·偶然 ...