Click here to Skip to main content
14,637,454 members
Articles » Web Development » ASP.NET » Howto
Article
Posted 14 Feb 2016

Stats

122.3K views
2.2K downloads
48 bookmarked

RESTful Web API Help Documentation using Swagger UI and Swashbuckle

Rate this:
4.82 (23 votes)
Please Sign up or sign in to vote.
4.82 (23 votes)
18 Feb 2016CPOL
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

Image 1

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.

Image 2

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

Image 3

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)

Image 4

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.

Image 5

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

Image 6

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

Image 7

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.

Image 8

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.

Image 9

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

Image 10

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”

Image 11

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

Image 12

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

Image 13

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.

Image 14

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:

Image 15

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

Image 16

Image 17

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.

Image 18

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>

Image 19

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.

Image 20

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:

Image 21

POST operation details:

Image 22

DELETE operation details:

Image 23

GET by Id operation details:

Image 24

PUT operation details:

Image 25

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.

Image 26

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

Image 27

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

Image 28

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

Image 29

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.

Image 30

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”.

Image 31

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:

Image 32

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 India
No Biography provided

Comments and Discussions

 
Questionentity data model wizard Pin
Member 1346595415-Oct-17 1:57
MemberMember 1346595415-Oct-17 1:57 
AnswerRe: entity data model wizard Pin
Sreekanth Mothukuru19-Oct-17 21:04
MemberSreekanth Mothukuru19-Oct-17 21:04 
QuestionHow do we implement OAuth Authorization Code Flow Pin
Sourav Das2-Oct-17 16:45
MemberSourav Das2-Oct-17 16:45 
AnswerRe: How do we implement OAuth Authorization Code Flow Pin
Sreekanth Mothukuru19-Oct-17 21:11
MemberSreekanth Mothukuru19-Oct-17 21:11 
QuestionHow do we generate the 'Models' section in a Swagger editor using Swashbuckle ? Pin
Raghunath Rajendren27-Jul-17 21:06
MemberRaghunath Rajendren27-Jul-17 21:06 
QuestionAdd Basic Auth Header? Pin
Er. Manoj Sethi27-Apr-17 7:02
MemberEr. Manoj Sethi27-Apr-17 7:02 
AnswerRe: Add Basic Auth Header? Pin
Sreekanth Mothukuru22-Jul-17 3:46
MemberSreekanth Mothukuru22-Jul-17 3:46 
QuestionCreate custom name for Swagger definitions Pin
Member 130546765-Apr-17 18:31
MemberMember 130546765-Apr-17 18:31 
AnswerRe: Create custom name for Swagger definitions Pin
Sreekanth Mothukuru17-Apr-17 1:57
MemberSreekanth Mothukuru17-Apr-17 1:57 
Questionpretty much copied from MS Pin
me_pollack15-Feb-17 12:53
Memberme_pollack15-Feb-17 12:53 
AnswerRe: pretty much copied from MS Pin
Garth J Lancaster15-Feb-17 16:28
professionalGarth J Lancaster15-Feb-17 16:28 
GeneralRe: pretty much copied from MS Pin
Sreekanth Mothukuru17-Apr-17 1:42
MemberSreekanth Mothukuru17-Apr-17 1:42 
AnswerRe: pretty much copied from MS Pin
Sreekanth Mothukuru17-Apr-17 1:37
MemberSreekanth Mothukuru17-Apr-17 1:37 
GeneralMy vote of 5 Pin
Member 1284482811-Nov-16 0:13
MemberMember 1284482811-Nov-16 0:13 
GeneralRe: My vote of 5 Pin
Sreekanth Mothukuru11-Nov-16 7:36
MemberSreekanth Mothukuru11-Nov-16 7:36 
QuestionThanks a lot for the article. Pin
suhanshetty8-Nov-16 5:01
Membersuhanshetty8-Nov-16 5:01 
AnswerRe: Thanks a lot for the article. Pin
Sreekanth Mothukuru8-Nov-16 7:41
MemberSreekanth Mothukuru8-Nov-16 7:41 
QuestionCan you show us a demo on how to customize the index.html? Pin
frankmail00718-Aug-16 6:59
Memberfrankmail00718-Aug-16 6:59 
AnswerRe: Can you show us a demo on how to customize the index.html? Pin
Sreekanth Mothukuru19-Aug-16 8:06
MemberSreekanth Mothukuru19-Aug-16 8:06 
QuestionTwo questions on navigation Pin
NatZol10-May-16 3:37
MemberNatZol10-May-16 3:37 
AnswerRe: Two questions on navigation Pin
Sreekanth Mothukuru10-May-16 4:17
MemberSreekanth Mothukuru10-May-16 4:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.