RESTful Web API Help Documentation using Swagger UI and Swashbuckle

Sign in

Articles » Web Development » ASP.NET » Howto

 

Article

Browse Code

Stats

Revisions (4)

Alternatives

Comments

Add your own
alternative version

Tagged as

JavascriptCSSSQLC#MVCVS2013ASP.NETserviceWebServer

Stats

9.1K views

131 downloads

23 bookmarked

Posted 14 Feb 2016

RESTful Web API Help Documentation using Swagger UI and Swashbuckle

Sreekanth Mothukuru, 18 Feb 2016 CPOL

   4.86 (11 votes)
 
Rate this:

How to create an interactive interface (help documentation) to represent our RESTful API using popular framework Swagger & Swashbuckle.

Source Code: Download SwaggerUi_2.zip

Idea

The aim of this article is to educate developers on how to create interactive interface which represent their Restful API to provide a rich discovery, documentation and playground experience to their API consumers.

Process

In this article we are going to create a simple Restful API in Asp.Net and integrate Swashbuckle & Swagger UI. The article has been listed into three sections

  1. Creating an Asp.Net Web API project
  2. Connect to Sql Server Database using Entity Data Model (.edmx) and Scaffold API Controller
  3. Integrating Swashbuckle/Swagger UI framework to represent API operations

Creating an Asp.Net Web API project

Start by creating a new “Asp.Net Web Application” with the name “Swagger

Select Web API from the template which means Visual Studio is going to add MVC and Web API related folders and core references to our application. Also, click “Change Authentication” to choose “No Authentication” and click OK. With this we are going to skip Account related Controller as well as Views from our project.

After executing Visual Studio bootstrap here is the project files and folder structure:

We will get routes set for both RouteConfig.cs for MVC controller as well as WebApiConfig.cs for Web API Controller in our App_Start folder.

Note: You can see “HelpPages” folder in Areas. This folder will hold Models, Views, Controllers and other Help related files that are being generated by Visual Studio to represent Web API help (We will see this later in this article)

If you see "Installed packages" under NuGet Package Manager, you will notice “Microsoft Asp.Net Web API 2.2 Help Page” package already being added to the project along with MVC, Razor and Core packages.

Connect to SQL Server Database using Entity Data Model (edmx) and Scaffold API Controller

Let us first connect our application to the database table using entity data model. Start by creating a new item “ADO.NET Entity Data Model” with the name “SwaggerModel” in the Models folder.

Attached is the script file used to create new table to our database Download SQL.zip

Select “EF Designer from database” from the wizard and click “Next” to connect to the Database server (SQL Server in our case)

From the Entity Data Model Wizard screen, select connection to the Sql Server and name the connection string as “SwaggerConStr” which will be saved in web.config file.

Hit “Next” to select Entity Framework version (in our case 6.x). Click “Next” to choose our Company table to include in our EDMX file.

Select the table and click “Finish” button which will eventually generate our POCO class “Company.cs” and a database context class “SwaggerConStr

Now that our Entity Data Model and Context is created, we can create a new API Controller using visual Studio scaffolding feature. But before scaffolding API controller, let us first build the application in order to make use of the context. Delete existing ValuesController.cs from the controller folder before scaffolding.

Right click on the Controllers folder and add “Controller…” this will open “Add Scaffold” window with various scaffolding options. Select “Web API 2 Controller with actions, using Entity Framework” and click “Add”

From the Add Controller window, select Model (in our case Company.cs) as well as Data Context classes (SwaggerConStr.cs). Name the new controller as “CompanyController.cs” and click “Add” button

New controller created with operations for each http verbs (GET, PUT, POST and DELETE)

Build and run the application to see the following screen. From the UI top navigation, you can see the “API” link which will navigate us to default “Asp.Net API Help Page” screens. The Help home page looks like this.

Note: In order to check the API, add “/api/company” to the url and submit in the browser.

If you click on any of the operation link, it will show more details like the “Request” information with URI & body parameters and “Response” type and formats like json or xml. Here is how it displays for GET method:

Although Visual Studio team has put in a great effort to represent Web API Help for those who consume the service, its low point is its very basic user interface and there is no way we could try out an action method. This is where Swagger UI & Swashbuckle come into play.

Integrating Swashbuckle/Swagger UI to represent API operations

According to Swagger website, Swagger is a simple yet powerful representation of your RESTful API. It gives a powerful interface to our API.

According to Swashbuckle GitHub, Swashbuckle seamlessly adds a Swagger to WebApi projects! Combines ApiExplorer and Swagger/swagger-ui to provide a rich discovery, documentation and playground experience to your API consumers. In addition to its Swagger generator, Swashbuckle also contains an embedded version of swagger-ui.

Adding Swashbuckle to our Web API

Go to “Manage NuGet Packages…” and search online for “Swashbuckle”. From the list select “Swashbuckle - Swagger for Web API” created by Richard Morris with the version 5.2.2 and click Install

This will add references to “Swashbuckle - Swagger for Web API” and also to “Swashbuckle.Core - Swagger for Web API” to our project after checking its dependencies. The same will appear in packages.config file as..

<package id="Swashbuckle" version="5.2.2" targetFramework="net45" />
<package id="Swashbuckle.Core" version="5.2.2" targetFramework="net45" />

After successful installation, we see there is a new “SwaggerConfig.cs” config file in our App_Start folder. This is where we set all Swagger related configurations.

In order to have a direct link to our Swagger API interface, all the following action link to the top navigation in “_Layout.cshtml” page.

<li>@Html.ActionLink("Swagger Help", "", "Swagger", new { area = "" }, null)</li>

Now build and run the application. From the top navigation click on “Swagger Help”. It will take us to the Swagger user interface. Hit List Operations to view all interactive action operations with their corresponding verbs.

Clicking on operation will show us Response Class. Clicking on “Try it out!” button will display additional details like Request URL, Response Body, Response Code and Response Headers.

GET Operation:

POST operation details:

DELETE operation details:

GET by Id operation details:

PUT operation details:

To include XML comments in the help document

Go to project properties and under Build tab, select the checkbox “XML documentation file:” in Output section and you will see the XML path from Bin folder where the file is saved.

Now open the Swagger Config file and add the “IncludeXmlComments” statement with a function that returns the path to XML file from bin folder.

private static string GetXmlCommentsPath()
{
    return String.Format(@"{0}\bin\SwaggerUi.XML", System.AppDomain.CurrentDomain.BaseDirectory);
}

This is how global configuration is enabled in SwaggerConfig.cs Register static method

public static void Register()
{
    var thisAssembly = typeof(SwaggerConfig).Assembly;

    GlobalConfiguration.Configuration
        .EnableSwagger(c =>
        {
            c.SingleApiVersion("v1", "SwaggerUi");
            c.IncludeXmlComments(GetXmlCommentsPath());
        })
        .EnableSwaggerUi(c =>
        {
        });
}

To check if XML comments are working on not... Edit controller Get method with some comments like

Run the application and navigate to Swagger Help page from top navigation. You can see xml comments added to the Swagger Help pages.

Customizing Swagger UI with our own Cascading Style Sheets:

Swashbuckle document states that developer can use the predefined method “InjectStylesheet” to inject their custom .css files as an embedded resources. We need to use “Logical Name” of the file as the second parameter and “media=screen” as third optional parameter along with current assembly as a first parameter.

Go and create a new cascading style sheets file “myStyle.css” in the Content folder and add the following style to change the headers default background color from Green to Blue:

.swagger-section #header {
    background-color: #0000ff;
    padding: 14px;
}

Right click on the file and select properties and set its Build Action to “Embedded Resource

Now add the following line to the SwaggerConfig settings to enable UI:

c.InjectStylesheet(thisAssembly, "SwaggerUi.Content.myStyle.css");

Note: The “Logical Name” of the style sheet file.

Now run the application to see the change.

Customizing Swagger UI with our own JavaScript:

Swashbuckle document states that developer can use the predefined method “InjectJavaScript” to inject their custom JavaScript files as an embedded resources. We need to use “Logical Name” of the file as the second parameter along with current assembly as a first.

Go and create a new JavaScript file “myScript.js” in the Scripts folder and add the following basic script to display custom alert message when the document loads.

$(document).ready(function () {
    alert("Hello from custom JavaScript file.");
});

Right click on the file and select properties to set its Build Action to “Embedded Resource”.

Now add the following line to the SwaggerConfig settings to enable UI:

c.InjectJavaScript(thisAssembly, "SwaggerUi.Scripts.myScript.js");

Note: The “Logical Name” of the JavaScript file.

Run the application to see the alert message:

Note: We can use “InjectJavaScript” feature to add our own user interface and behavior before we interacting with the API help. Check this nice article by Steve Michelotti on how to "Customize Authentication Header in SwaggerUI using Swashbuckle".

Finally our SwaggerConfig Register method file looks like this:

public static void Register()
{
    var thisAssembly = typeof(SwaggerConfig).Assembly;

    GlobalConfiguration.Configuration
        .EnableSwagger(c =>
        {
            c.SingleApiVersion("v1", "SwaggerUi");
            c.IncludeXmlComments(GetXmlCommentsPath());
        })
        .EnableSwaggerUi(c =>
        {
            c.InjectStylesheet(thisAssembly, "SwaggerUi.Content.myStyle.css");
            c.InjectJavaScript(thisAssembly, "SwaggerUi.Scripts.myScript.js");
        });
}

There are several other methods to implement to customize. I will update this article later.

Check out my other articles related Asp.Net MVC, Web API, Angular etc.,

Create an ASP.NET Web Forms Application using Bootstrap and Web API

Create a Responsive HTML Table using FooTable and Apply Client Side Binding using Handlebars.Js

Use Dependency Injector "Ninject" to dynamically choose between ORM‘s (Entity Framework or Dapper) and Databases (SQL Server or Oracle Database)

First AngularJs Application using ASP.NET MVC, $http & $window Services, EF and CRUD Implementation

Baby Steps towards ASP.NET 5 Web Application and see What’s New

Hope you learnt something new from this article. Feel free to "Rate This Article""Bookmark" and give suggestion in "Comments" section below.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Sreekanth Mothukuru


  

Technical Lead
India 

No Biography provided

You may also be interested in...


Upgrading Swagger to 5.2.X for Web API with Owin


Cloud-based Data Warehousing as a Service, Built for Analytics


WSDL Equivalent for Rest API


SAPrefs - Netscape-like Preferences Dialog


Ajaxion - Standalone AJAX - Part 1 of 2 - A UI perspective on REST


Generate and add keyword variations using AdWords API

Comments and Discussions

You must Sign In to use this message board.

Search Comments 

 
Profile popups    Spacing 
Relaxed
Compact
Tight
   Layout 
Normal
Open Topics
Open All
Thread View
   Per page 
10
25
50
    
     
-- There are no messages in this forum --

Go to top

Permalink | AdvertisePrivacy | Terms of Use | Mobile 
Web02 | 2.8.160426.1 | Last Updated 18 Feb 2016

Article Copyright 2016 by Sreekanth Mothukuru
Everything else Copyright © CodeProject, 1999-2016

Layout: fixed | fluid

来自为知笔记(Wiz)

时间: 2024-10-07 12:42:46

RESTful Web API Help Documentation using Swagger UI and Swashbuckle的相关文章

对RESTful Web API的理解与设计思路

距离上一篇关于Web API的文章(如何实现RESTful Web API的身份验证)有好些时间了,在那篇文章中提到的方法是非常简单而有效的,我在实际的项目中就这么用了,代码经过一段时间的磨合,已经很稳定了,所以我打算写篇总结,并在最近这段时间里提供一个ASP.net Web API的综合例子. 对四个HTTP方法的理解 众所周知,HTTP有四个方法,GET.POST.PUT和DELETE,分别对应数据库的SELECT.INSERT.UPDATE和DELETE,一般的教程说到这里也就Over了,

使用 Swagger UI 与 Swashbuckle 创建 RESTful Web API 帮助文件

作者:Sreekanth Mothukuru 2016年2月18日 本文旨在介绍如何使用常用的 Swagger 和 Swashbuckle 框架创建描述 Restful API 的交互界面,并为 API 用户提供丰富的探索.文件和操作体验. 源代码: 下载 SwaggerUi_2.zip 步骤 在本文中,我们将在 Asp.Net 创建一个简单的 Restful API,并整合 Swashbuckle 和 Swagger UI.本文分为三部分. 创建 Asp.Net Web API项目 通过实体数

ASP.NET Web API Help Pages using Swagger

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 i

web API help pages with Swagger / OpenAPI

https://docs.microsoft.com/en-us/aspnet/core/tutorials/web-api-help-pages-using-swagger?view=aspnetcore-2.2 When consuming a Web API, understanding its various methods can be challenging for a developer. Swagger, also known as OpenAPI, solves the pro

我所理解的RESTful Web API [Web标准篇]

REST不是一个标准,而是一种软件应用架构风格.基于SOAP的Web服务采用RPC架构,如果说RPC是一种面向操作的架构风格,而REST则是一种面向资源的架构风格.REST是目前业界更为推崇的构建新一代Web服务(或者Web API)的架构风格.由于REST仅仅是一种价格风格,所以它是与具体的技术平台无关的,也就是说采用REST架构的应用未必一定建立在Web之上,所以在正式介绍REST之前,我们先来简单认识一下Web. 目录 一.TCP/IP与HTTP 二.Web资源       媒体类型   

学习使用MEAN开发RESTful WEB api,实现数据的CRUD

800?"800px":this.width); max-height:800px; height:expression_r(this.height>800?"800px":this.height); } --> MEAN M=MongoDB 非关系型数据库 E=Express Node中的web开发模块 A=Angular.js Google的javascript开发框架 N=Node.js javascript的服务端运行环境 下面通过youtube

Swagger UI 及Swashbuckle

一.概念: 由Swagger网站可知,Swagger是展示RESTful API的简单而强大的方法,它为此API提供了强大的接口. 由Swashbuckle GitHub可知,Swashbuckle可将Swagger无缝添加到WebApi中!将ApiExplorer与Swagger/swagge-ui 合并可以给 API 用户带来丰富的探索.文件和操作体验.除Swagger生成器外,Swashbuckle还包含嵌入式版本的swagger-ui. 二.使用 1.使用包命令添加到项目 install

Swagger UI教程 API 文档神器 搭配Node使用 web api 接口文档 mvc接口文档

两种方案 一.Swagger 配置 web Api 接口文档美化 二.通过NodeJS 发布Swagger UI 配置api 文档 先说一下简单的 Swagger 配置 web Api  Swagger-UI本身只提供在线测试功能,要集成它还需要告诉它本项目提供的各种服务和参数信息.这里就需要一些工作量了,不过好在许多第三方库已经给我们完成了这一工作.我这里用的是Swashbuckle,使用它也比较简单,直接使用Nuget添加其程序包即可: 1.初始化包  PM> Install-Package

使用 Swagger 自动生成 ASP.NET Core Web API 的文档、在线帮助测试文档(ASP.NET Core Web API 自动生成文档)

对于开发人员来说,构建一个消费应用程序时去了解各种各样的 API 是一个巨大的挑战.在你的 Web API 项目中使用 Swagger 的 .NET Core 封装 Swashbuckle 可以帮助你创建良好的文档和帮助页面. Swashbuckle 可以通过修改 Startup.cs 作为一组 NuGet 包方便的加入项目.Swashbuckle 是一个开源项目,为使用 ASP.NET Core MVC 构建的 Web APIs 生成 Swagger 文档.Swagger 是一个机器可读的 R