Web API

.Postman API Testing Tool for Chrome

Web page by Kevin Harris of Homer IL

Please contact Kevin Harris of Homer IL concerning this web site

Web API

ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. Web API is an ideal platform for building RESTful applications on the .NET Framework.


ASP.NET Web API is a framework for building RESTful applications in the .NET Framework. Web API was released with MVC 4 in late 2012 and requires .NET 4.0 or greater. Web API 2.0 was released with MVC 5 in late 2013. Web API has many similarities to MVC , however it is not linked to MVC. Web API can be used alone, or with either MVC or Web Forms. Graphic above is from Postman, a popular Chrome extension for Testing Web APIs.

Web API was built from the ground up around the HTTP protocol. It is more flexible and extensible and than previous ASP.NET methods of creating RESTful services. For many years Microsoft development was geared around SOAP based services with Windows Communication Foundation (WCF). WCF is a powerful, and very secure method of creating services which worked well for organizations, but contained too much overhead to be used efficiently with the explosion of mobile devices. Web API (i.e. RESTful services) is based purely on HTTP and provides a lightweight method for creating data and functionality services which can reach the largest number of modern devices. The advantages of WEB API over WCF include:

  1. Web API uses the established HTTP mechanisms and SSL that already exist in Internet devices. WCF SOAP requires the installation of special libraries which may not be available for all devices.

  2. Web API contains less overhead to process a REST request, which is very important for mobile devices.

  3. Web API typically transfers data in a JSON format which is easy for JavaScript to process as compared to the XML format used by SOAP messages in WCF. Also the JSON format is less verbose than XML reducing the number of bytes which are required in the requests/responses. This not only improves speed, but also can reduce cost when the data is transmitted thru cellular.

REST

REpresentational State Transfer (REST) is an architectural style for designing networked applications that exploits the existing technology and protocol of the Web. Web services which implement the REST architectural style are referred to as RESTful. REST is a lightweight alternative to more complicated communication mechanisms, such as SOAP, RPC, or CORBA. REST is not a standard or a specification, but as an architectural style the implementation is typically up to the developer. However there are formal design rules which must be adhered to in order for a service to be considered RESTful (see next paragraph). Additionally standards str being developed for the creation and consumption of RESTful services, such as OData

Roy Fielding described the REST style of services in his doctoral dissertation, see below for interview with Roy Fielding. His dissertation described services based on HTTP which provides loose coupling between the services and clients. REST make no assumptions about how the data is going to be consumed, so it is available to virtually any internet connected application regardless of its platform. The Create, Retreive, Update, Delete (CRUD) operations are central to REST and typically relates to the four HTTP verbs: Post, Get, Put, and Delete. The six characteristics, or constraints, which embody the REST architectural style are:

  1. Client-Server
  2. Stateless
  3. Cache
  4. Interface / Uniform Contract
  5. Layered System
  6. Code-On-Demand


Creating WEB API Projects in Visual Studio

In Visual Studio 2015 you can use the templates to scaffold an API project in several ways. You can select an empty project template and select only the Web API checkbox to build up the Web API (this is the method shown below). You can also select the WEB API template it will automatically select MVC and Web API. In this case the MVC component will contain help files which includes a Values controller which will display the service methods in a similar fashion as the WSDL file in WCF which allowed for discovery of the service interface methods.

Using Web API 5.2.3, I selected an empty project template and only the Web API checkbox so I could build up the Web API (without including MVC. I then created a new api controller.

.Add Web API Controller in Visual Studio 2015


Add Web API Controller in Visual Studio 2015

Choose a Web API 2 Controller - Empty and the scaffolding creates a new file containing a class in the Controllers folder. Change the class to derive from ApiController, instead of Controller, and add the data access logic. A readme.txt file is also generated which contains the following instructions:

Visual Studio has added the full set of dependencies for ASP.NET MVC 5 to project 'CathySite.WebAPI'. 

The Global.asax.cs file in the project may require additional changes to enable ASP.NET MVC.

1. Add the following namespace references:

    using System.Web.Mvc;
    using System.Web.Routing;
    using System.Web.Optimization;

2. If the code does not already define an Application_Start method, add the following method:

    protected void Application_Start()
    {
    }

3. Add the following lines to the end of the Application_Start method:

    AreaRegistration.RegisterAllAreas();
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    BundleConfig.RegisterBundles(BundleTable.Bundles);


Data and Code for the Web API

.Data Diagram


Diagram for Data Used for the Web API

The diagram above shows the data for the API which consists of the grocery table with two related tables: category and frequency. The code for the Web API is shown below. Note that eager loading must be used instead of lazy loading, so you can not return an IQueryable type. To ensure eager loading is used, the LINQ statement must contain the "Include" methods for each related table. Also the "ToList" method must be used. Additionally, the Object Context must remain open, so the return statement can not be inside a "Using" statement. The context will be automatically closed when upon exit of the method.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
using System.Collections.Generic;
using CathySite.DAL.Models;
using System.Web.Http;
using System.Linq;
using System.Data.Entity;

namespace CathySite.WebAPI.Controllers
{
    public class GroceryController : ApiController
    {
        public List<grocery> GetAllGroceries()
        {
            var context = new CathySiteEntities();
            return context.groceries.Include(g => g.category).Include(g => g.frequency).ToList();
        }
    }
}


GroceryController.cs

Testing the Web API

To test the Web API on the development server, right-click the Web API project, select "Debug" and then "Start New Instance". The local host will display a 403.14 - Forbidden page as shown below.

.Forbidden Page Displays When Debugging Web API


Forbidden Page Displays When Debugging Web API

Once the Web API is running on the development server, you can test it with a program or a Web API tool such as Postman, and shown below.

.Postman Accessing Web API


Postman Accessing Web API on Local Server

Postman can show the results in various formats: JSON, XML, HTML, Text with various modes: Pretty, Raw, Preview. Below is the grocery data returned from the Web API show in JSON with a Pretty view mode in Postman.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
[
  {
    "category": {
      "ID": 1,
      "Name": "Food"
    },
    "frequency": {
      "ID": 1,
      "Name": "Very Frequent"
    },
    "ID": 7,
    "Need": null,
    "Quantity": 1,
    "Item": "Bread",
    "Brand": "Any",
    "Type": "White",
    "Price": null,
    "CategoryID": 1,
    "FrequencyID": 1,
    "PriceDate": null
  },
  {
    "category": {
      "ID": 1,
      "Name": "Food"
    },
    "frequency": {
      "ID": 2,
      "Name": "Frequent"
    },
    "ID": 2,
    "Need": true,
    "Quantity": 1,
    "Item": "Paper Towels",
    "Brand": "Bounty",
    "Type": "Absorbent",
    "Price": 0,
    "CategoryID": 1,
    "FrequencyID": 2,
    "PriceDate": null
  },
  {
    "category": {
      "ID": 1,
      "Name": "Food"
    },
    "frequency": {
      "ID": 2,
      "Name": "Frequent"
    },
    "ID": 5,
    "Need": null,
    "Quantity": 1,
    "Item": "Milk",
    "Brand": "Any",
    "Type": "Whole",
    "Price": 0,
    "CategoryID": 1,
    "FrequencyID": 2,
    "PriceDate": null
  },
  {
    "category": {
      "ID": 1,
      "Name": "Food"
    },
    "frequency": {
      "ID": 2,
      "Name": "Frequent"
    },
    "ID": 6,
    "Need": null,
    "Quantity": 12,
    "Item": "Eggs",
    "Brand": "Any",
    "Type": "Large",
    "Price": 0,
    "CategoryID": 1,
    "FrequencyID": 2,
    "PriceDate": null
  },
  {
    "category": {
      "ID": 1,
      "Name": "Food"
    },
    "frequency": {
      "ID": 2,
      "Name": "Frequent"
    },
    "ID": 8,
    "Need": null,
    "Quantity": 1,
    "Item": "Butter",
    "Brand": "Land O' Lakes",
    "Type": "Tub",
    "Price": null,
    "CategoryID": 1,
    "FrequencyID": 2,
    "PriceDate": null
  },
  {
    "category": {
      "ID": 1,
      "Name": "Food"
    },
    "frequency": {
      "ID": 3,
      "Name": "Infrequent"
    },
    "ID": 1,
    "Need": true,
    "Quantity": 2,
    "Item": "Peanut Butter",
    "Brand": "Skippy",
    "Type": "Crunchy",
    "Price": 0,
    "CategoryID": 1,
    "FrequencyID": 3,
    "PriceDate": "2015-12-31T00:00:00"
  },
  {
    "category": {
      "ID": 3,
      "Name": "Household"
    },
    "frequency": {
      "ID": 2,
      "Name": "Frequent"
    },
    "ID": 4,
    "Need": true,
    "Quantity": 1,
    "Item": "Toilet Paper",
    "Brand": "Angel Soft",
    "Type": null,
    "Price": 0,
    "CategoryID": 3,
    "FrequencyID": 2,
    "PriceDate": null
  }
]


Web API Data Shown in Postman as JSON with Pretty View Mode

Deploying Web API

To deploy the Web API to a production server, right-click on the Web API project and select "publish". Set up the publishing profile. An example profile is shown below. Note the Web API publish requires prior publishing of the Data Access Layer (DAL) project.

.Publishing Profile for Web API


Publishing Profile for Web API

Once on the production server, the Web API can be verified by running a programs, or Postman, to access the data. The publish can also be verified by inspecting the Web API's DLL date in the bin folder on the production server.



References

.Roy T Fielding


Roy Fielding Interview about Disseratation

Roy Fielding is one of the principal authors of the HTTP specification, an authority on computer network architecture and co-founder of the Apache HTTP Server project. His doctoral dissertation, at the University of California Irvine, describes Representational State Transfer (REST) as an architectural style for the Web. Roy Fielding discusses the development of this disseration in the Roy T. Fielding: Understanding the REST Style IEEE Computer Society Computing Conversations video.

Web API Design Jumpstart video on Channel 9 with Christoper Harrison and Jeremy Likness. 5 hours of content broken down into 6 modules. Includes security, validation, error handling, configurations, and advanced designs.

ASP.NET Web API provides free access to the Pluralsight Web API training video Introduction to the ASP.NET Web API.

The Web Concepts video REST API Concepts and Examples is an interesting short video which shows the use of Web API consoles, such as Apigee API Providers, to use various web APIs. It also references the site