banner



How To Display Restful Api Data On Ui Using Html, Css And Javascript

In this article, we will create a simple Restful API in ASP.Net and integrate Swashbuckle & Swagger UI.

  • Download source code - v.2 MB

Idea

The aim of this article is to educate developers on how to create interactive interface which correspond their Restful API to provide a rich discovery, documentation and playground feel 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. Connecting 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

Starting time 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 together MVC and Web API related folders and core references to our awarding. Besides, click "Change Hallmark" to cull "No Authentication" and click OK. With this, we are going to skip Business relationship related Controller equally well as Views from our project.

Image 2

After executing Visual Studio bootstrap, here are the project files and folder construction:

Image 3

Nosotros will get routes ready for both RouteConfig.cs for MVC controller as well equally WebApiConfig.cs for Web API Controller in our App_Start binder.

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

Image 4

If you see "Installed packages" under NuGet Package Director, you will notice "Microsoft ASP.Cyberspace Spider web API two.ii Help Page" parcel already being added to the project along with MVC, Razor and Core packages.

Image 5

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

Let us start connect our application to the database table using entity information model. Start past creating a new item "ADO.Net Entity Information Model" with the name "SwaggerModel" in the Models binder.

Below is the script file used to create new table in our database.

  • Download script

Image 6

Select "EF Designer from database" from the magician and click "Side by side" to connect to the Database server (SQL Server in our case).

Image 7

From the Entity Data Model Wizard screen, select connectedness to the SQL Server and proper noun the connection string as "SwaggerConStr" which volition be saved in web.config file.

Image 8

Hit "Next" to select Entity Framework version (in our instance 6.ten). 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 "Visitor.cs" and a database context class "SwaggerConStr".

Image 10

At present that our Entity Information Model and Context is created, nosotros can create a new API Controller using visual Studio scaffolding feature. Just before scaffolding API controller, permit us first build the application in guild 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 together Controller window, select Model (in our case Company.cs) likewise equally Data Context classes (SwaggerConStr.cs). Name the new controller as "CompanyController.cs" and click "Add together" push.

Image 12

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

Image 13

Build and run the awarding to see the following screen. From the UI top navigation, you tin see the "API" link which will navigate us to default "ASP.NET API Help Page" screens. The Aid dwelling house folio looks like this:

Image 14

Notation: In lodge to cheque the API, add together "/api/visitor" to the url and submit in the browser.

If you click on any of the performance link, it will show more details like the "Asking" information with URI & body parameters and "Response" blazon 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 try to represent Spider web API Aid for those who consume the service, its depression point is its very basic user interface and at that place is no mode we could endeavour out an activity method. This is where Swagger UI & Swashbuckle come into play.

Integrating Swashbuckle/Swagger UI to Represent API Operations

Co-ordinate to Swagger website, Swagger is a elementary nevertheless powerful representation of your RESTful API. It gives a powerful interface to our API.

Co-ordinate 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 feel to your API consumers. In addition to its Swagger generator, Swashbuckle also contains an embedded version of swagger-ui.

Adding Swashbuckle to our Spider web API

Go to "Manage NuGet Packages…" and search online for "Swashbuckle". From the list, select "Swashbuckle - Swagger for Spider web API" created by Richard Morris with the version 5.ii.ii and click Install.

Image 16

Image 17

This will add references to "Swashbuckle - Swagger for Web API" and also to "Swashbuckle.Cadre - Swagger for Web API" to our project afterward checking its dependencies. The same will appear in packages.config file as..

<packet id="          Swashbuckle"          version="          five.2.2"          targetFramework="          net45"          /> <package id="          Swashbuckle.Core"          version="          5.2.two"          targetFramework="          net45"          />

After successful installation, we see at that place is a new "SwaggerConfig.cs" config file in our App_Start folder. This is where nosotros set all Swagger related configurations.

Image 18

In lodge to have a direct link to our Swagger API interface, all the following actions link to the acme navigation in "_Layout.cshtml" page.

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

Image 19

Now build and run the application. From the pinnacle navigation, click on "Swagger Help". It will take us to the Swagger user interface. Hit Listing Operations to view all interactive action operations with their corresponding verbs.

Image 20

Clicking on operation volition testify united states of america Response Class. Clicking on "Attempt it out!" button will display boosted details like Request URL, Response Body, Response Lawmaking and Response Headers.

Get Operation

Image 21

POST Operation Details

Image 22

DELETE Functioning Details

Image 23

Become by Id Operation Details

Image 24

PUT Operation Details

Image 25

To Include XML Comments in the Help Document

Go to projection 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 together the "IncludeXmlComments" statement with a function that returns the path to XML file from bin binder.

          private          static          string          GetXmlCommentsPath() {          return          String.Format     (@"          {0}\bin\SwaggerUi.XML", Organisation.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 non... Edit controller Get method with some comments similar:

Image 27

Run the application and navigate to Swagger Assistance page from top navigation. Y'all can meet XML comments added to the Swagger Help pages.

Image 28

Customizing Swagger UI with Our Own Cascading Style Sheets

Swashbuckle certificate states that programmer can use the predefined method "InjectStylesheet" to inject their custom .css files as an embedded resources. We need to apply "Logical Name" of the file equally the second parameter and "media=screen" as tertiary optional parameter along with current assembly as a start parameter.

Get and create a new cascading style sheets file "myStyle.css" in the Content binder and add the following manner to change the headers default background color from Green to Blueish:

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

Right click on the file and select properties and fix 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 manner sheet file.

Now run the application to meet the change.

Image 30

Customizing Swagger UI with Our Ain JavaScript

Swashbuckle document states that developer can utilize the predefined method "InjectJavaScript" to inject their custom JavaScript files as an embedded resources. We need to apply "Logical Name" of the file every bit the second parameter along with current assembly as a start.

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

$(certificate).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 together the following line to the SwaggerConfig settings to enable UI:

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

Note: The "Logical Proper noun" of the JavaScript file.

Run the application to see the alarm bulletin:

Image 32

Note: Nosotros can utilize "InjectJavaScript" feature to add together our own user interface and behavior earlier nosotros interacting with the API help. Check this nice article by Steve Michelotti on how to "Customize Hallmark Header in SwaggerUI using Swashbuckle".

Finally, our SwaggerConfig Register method file looks similar this:

          public          static          void          Annals() {          var          thisAssembly =          typeof(SwaggerConfig).Associates;      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.

Cheque out my other related articles ASP.NET MVC, Spider web API, Athwart, 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)
  • Get-go AngularJs Application using ASP.Cyberspace MVC, $http & $window Services, EF and Crud Implementation
  • Baby Steps towards ASP.Net five Web Application and encounter What's New

Hope y'all learnt something new from this article. Experience free to "Rate This Article", "Bookmark" and give suggestion in "Comments" section below.

History

  • fifteenth February, 2016: Initial version
  • 18th Feb, 2016: Updated commodity to include verbiage to customize Swagger UI using custom cascading style sheet (CSS) and also described how to included custom JavaScript

How To Display Restful Api Data On Ui Using Html, Css And Javascript,

Source: https://www.codeproject.com/Articles/1078249/RESTful-Web-API-Help-Documentation-using-Swagger-U

Posted by: mazurfident75.blogspot.com

0 Response to "How To Display Restful Api Data On Ui Using Html, Css And Javascript"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel