Evolvable Web APIs

.Designing Evolvable Web APIs with ASP.NET


Designing Evolvable Web APIs with ASP.NET


Web page by Kevin Harris of Homer IL

Please contact Kevin Harris of Homer IL concerning this web site

"A Web API is a programmatic interface to a system that is accessed via standard HTTP methods and headers. A Web API can be accessed by a variety of HTTP clients, including browsers and mobile devices."

This page is a review of the book, with additional notes, as I read through the chapters. This book covers Microsoft's Web API (.NET 4.0) which is a framework for building RESTful web services which are based on HTTP and typically use the JSON data format. RESTful services are increasing in popularity as they are lightweight and scalable which allows them to also be accessed by lightweight mobile devices which have limited capabilities but support for HTTP. The other Microsoft service framework, Windows Communication Foundation (WCF), for Service-Oriented Architecture (SOA), is designed for building service-oriented applications for the enterprise and the web. WCF (.NET 3.0) is used to create heavyweight SOAP-based services which supports multiple protocols (TCP, HTTP, MSMQ, named pipes) and uses the more verbose XML data format. See the Learning WCF article for more information about WCF.

ASP.NET Web API is an open source project and can be obtained from nuget. The popular site ProgrammableWeb.com contains an API directory listing more than 15,000 web APIs, news and information about web APIs, and API University which provides free tutorials for web API developers.

Chapter 1: The Internet, the World Wide Web, and HTTP
Chapter 2: Web APIs

ASP.NET's Web API is a framework for building RESTful services. REST (Representational State Transfer) is an architectural style for networked hypermedia applications. RESTful services embrace the Web by using HTTP. RESTful services use HTTP verbs for all four CRUD operations and has gained widespread acceptance across the Web as a simpler alternative to SOAP. An analogy for REST vs SOAP is mailing a letter: with SOAP you use an envelope and with REST you use a postcard.

Terms

  • Representation - data that is returned from the resource.
  • Resource - anything that has a URI.
  • URI - URI can be thought of as a primary key for a resource. URIs are divided into two categories, URLs and URNs. URL (Universal Resource Locator) is an identifier that also refers to the means of accessing the resource. URN (Universal Resource Name) is simply a unique identifier for a resource.
  • Media Type - a format for passing information across the Internet between client and servers.



HTTP Methods (aka HTTP Verbs)

The set of common methods for HTTP/1.1 is defined in RFC 2616 at Method Definitions.

Http Methods (Verbs)
Verb CRUD Behavior
GET

Read

Retrieve whatever information (in the form of an entity) that is identified by the Request-URI.

The semantics of the GET method change to a "conditional GET" if the request message includes an If-Modified-Since, If-Unmodified-Since, If-Match, If-None-Match, or If-Range header field. A conditional GET method requests that the entity be transferred only under the circumstances described by the conditional header field(s).

The semantics of the GET method change to a "partial GET" if the request message includes a Range header field. A partial GET requests that only part of the entity be transferred.

The response to a GET request is cacheable if and only if it meets the requirements for HTTP caching

POST

Create

Is used to request that the origin server accept the entity enclosed in the request as a NEW subordinate of the resource identified by the Request-URI.

The action performed by the POST method might not result in a resource that can be identified by a URI. In this case, either 200 (OK) or 204 (No Content) is the appropriate response status.

If a resource has been created on the origin server, the response SHOULD be 201 (Created) and contain an entity which describes the status of the request and refers to the new resource, and a Location header.

Responses to this method are not cacheable, unless the response includes appropriate Cache-Control or Expires header fields.
PUT

Update

Requests that the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers to an already existing resource, the enclosed entity SHOULD be considered as a modified version of the one residing on the origin server. If the Request-URI does not point to an existing resource, and that URI is capable of being defined as a new resource by the requesting user agent, the origin server can create the resource with that URI.

If a new resource is created, the origin server MUST inform the user agent via the 201 (Created) response. If an existing resource is modified, either the 200 (OK) or 204 (No Content) response codes SHOULD be sent to indicate successful completion of the request. If the resource could not be created or modified with the Request-URI, an appropriate error response SHOULD be given that reflects the nature of the problem. The recipient of the entity MUST NOT ignore any Content-* (e.g. Content-Range) headers that it does not understand or implement and MUST return a 501 (Not Implemented) response in such cases.

Responses to this method are not cacheable.

The fundamental difference between the POST and PUT requests is reflected in the different meaning of the Request-URI. The URI in a POST request identifies the resource that will handle the enclosed entity. That resource might be a data-accepting process, a gateway to some other protocol, or a separate entity that accepts annotations. In contrast, the URI in a PUT request identifies the entity enclosed with the request -- the user agent knows what URI is intended and the server MUST NOT attempt to apply the request to some other resource. If the server desires that the request be applied to a different URI, it MUST send a 301 (Moved Permanently) response; the user agent MAY then make its own decision regarding whether or not to redirect the request.

If PUT is used for an update, it requires all fields on the entity be specified, regardless of how many change (Unlike PATCH).
PATCH

Update

A newer verb. It transmits a partial change to the entity identified by the URI where only identifiers and modified fields are specified.

See RFC 5789 - PATCH Method

The difference between the PUT and PATCH requests is reflected in the way the server processes the enclosed entity to modify the resource identified by the Request-URI. In a PUT request, the enclosed entity is considered to be a modified version of the resource stored on the origin server, and the client is requesting that the stored version be replaced. With PATCH, however, the enclosed entity contains a setof instructions describing how a resource currently residing on the origin server should be modified to produce a new version.

DELETE

Delete

Requests that the origin server DELETE the resource identified by the Request-URI.

A successful response SHOULD be 200 (OK) if the response includes an entity describing the status, 202 (Accepted) if the action has not yet been enacted, or 204 (No Content) if the action has been enacted but the response does not include an entity.

Responses to this method are not cacheable.

HEAD

N/A

Retrieves just the message headers identified by the URI. The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response.

OPTIONS

N/A

Represents a request for information about the communication options available on the request/response chain identified by the Request-URI. This method allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval.

Responses to this method are not cacheable.

TRACE

N/A

Requests that the server return the request it received. The server will return the entire request message in the body with a content-type of message.http. This is useful for diagnostics, as clients can see which proxies the request passed through and how the request may have been modified by intermediaries.



GET and POST are the two most common methods. GET is used to retrieve data and uses a query string for the key fields used to identify the data for retrieval. POST is used to submit data for processing and stores the data in the HTTP message body. Get requests can be cached, while POST requests can not be cached.

GET and POST
GET POST
Reload/Back Button Harmless Data will be re-submitted (Browser should alert the user)
Cached Can be cached Not cached
Data Stored in URL Stored in message body
Data Length Limited to length of URL (typically 2048 bytes) No restrictions. Binary data also allowed.



Safe and Idempotent HTTP Methods

A safe HTTP method does not modify anything at the server. GET and HEAD are safe methods. POST, PUT, and DELETE are unsafe methods.

An HTTP method is idempotent if the side effects of making the request one time is the same as making the request multiple times. For example x=4; is idempotent. While x++; is not idempotent. Any safe method is idempotent. PUT and DELETE are idempotent, POST is not.

Safe and Idempotent HTTP Methods
HTTP Method Safe Idempotent
GET

Yes

Yes

POST

No

No

PUT

No

Yes

PATCH

No

No

DELETE

No

Yes

HEAD

Yes

Yes

OPTIONS

Yes

Yes



HTTP Response Messages

After receiving and interpreting a request message, a server responds with an HTTP response message. Response methods are defined in RFC 2616 at Response.

Http Response Message Groups
Number Category Meaning
1xx Informational Request received, continuing process
2xx Success The action was successfully received, understood, and accepted
3xx Redirection Further action must be taken in order to complete the request
4xx Client Error The request contains bad syntax or cannot be fulfilled
5xx Server Error The server failed to fulfill an apparently valid request



Response Messages
Response Code HTTP Operation Response Body Contents Description

200

GET, PUT,DELETE

Resource

No error, operation successful.

201 Created

POST

Resource that was created

Successful creation of a resource.

202 Accepted

POST, PUT,DELETE

N/A

The request was received.

204 No Content

GET, PUT,DELETE

N/A

The request was processed successfully, but no response body is needed.

301 Moved Permanently

GET

XHTML with link

Resource has moved.

303 See Other

GET

XHTML with link

Redirection.

304 Not Modified

conditionalGET

N/A

Resource has not been modified.

400 Bad Request

GET, POST,PUT,DELETE

Error Message

Malformed syntax or a bad query.

401 Unauthorized

GET, POST,PUT,DELETE

Error Message

Action requires user authentication.

403 Forbidden

GET, POST,PUT,DELETE

Error Message

Authentication failure or invalid Application ID.

404 Not Found

GET, POST,PUT,DELETE

Error Message

Resource not found.

405 Not Allowed

GET, POST,PUT,DELETE

Error Message

Method not allowed on resource.

406 Not Acceptable

GET

Error Message

Requested representation not available for the resource.

408 Request Timeout

GET, POST

Error Message

Request has timed out.

409 Resource Conflict

PUT, PUT,DELETE

Error Message

State of the resource doesn't permit request.

410 Gone

GET, PUT

Error Message

The URI used to refer to a resource.

411 Length Required

POST, PUT

Error Message

The server needs to know the size of the entity body and it should be specified in the Content Length header.

412 Precondition failed

GET

Error Message

Operation not completed because preconditions were not met.

413 Request Entity Too Large

POST, PUT

Error Message

The representation was too large for the server to handle.

414 Request URI too long

POST, PUT

Error Message

The URI has more than 2k characters.

415 Unsupported Type

POST, PUT

Error Message

Representation not supported for the resource.

416 Requested Range Not Satisfiable

GET

Error Message

Requested range not satisfiable.

500 Server Error

GET, POST,PUT

Error Message

Internal server error.

501 Not Implemented

POST, PUT,DELETE

Error Message

Requested HTTP operation not supported.

502 Bad Gateway

GET, POST,PUT,DELETE

Error Message

Backend service failure (data store failure).

505

GET

Error Message

HTTP version not supported.





Intermediaries

Intermediaries are agents or components along the HTTP message path which inspect the HTTP request or response and may modify or replace it.An intermediary can immediately return a response, invoke some sort of process, or just let the HTTP message flow through. Types of intermediaries include:

  • proxy - an agent that handles making HTTP requests and receiving responses on behalf of the client.
  • gateway - received inbound HTTP messages and translates them to the server's underlying protocol. The gateway also takes out-bound messages and translates them to HTTP.
  • tunnel - creates a private channel between two connections without modifying any of the messages. One example is communicating using HTTPS through a firewall.

Chapter 3: ASP.NET Web API 101


"ASP.NET Web API used many of the good things in WCF: extensible, flexible hosting, client support together with the strong aspects of MVC: model binding, validation, testability, and support for convention over configuration."

WCF (SOAP) is good for allowing a single service to communicate with SIMILAR clients using many different protocols, whereas ASP.NET Web API (RESTful Services) is good for allowing many DISSIMILAR clients to across a single protocol (i.e. the ubiquitous HTTP protocol). SOAP requires programs to code/decode the SOAP messages. These programs require significant amounts of processing power and the programs do not, by default, exist on many clients. This makes SOAP less suitable for the explosion of mobile devices and tablets which are accessing the Internet. Web API used HTTP as both a transport and an application protocol which allows it to be used by most clients (even mobile devices and tablets) since native HTTP support is ubiquitous.

WCF essentially uses HTTP as a transport protocol and uses only the POST HTTP method. It wraps the application details inside the HTTP body and custom "SOAPAction" header. The protocol elements (the way the client and server understand each other) have been pulled out of the HTTP elements and placed inside the XML residing in the request and response bodies. Web API uses the HTTP methods (e.g. POST, GET, PUT, DELETE) to communicate the application details. For example, the verbs are frequently used to define the CRUD operations associated with a database.

ASP.NET Web API is build around a small set of HTTP objects with HttpRequestMessage and HttpResponseMessage being two of the most notable. This allows usage of HTTP features, such as content negotiation and optimistic concurrency, which are not available with WCF. Content Negotiation is the process where the client and server communicate about the format of the data (i.e. Media Type) that will be used. The client can express its ordered degree of preferences using the "q" notation in the "Accept" headers. Optimistic Concurrency is a method of handling concurrent data interactions without locking the data. The stateless nature of HTTP makes locking infeasible for web interactions.

WebAPI Default Template

Below is a Web API project created with the ASP.NET 4.5.2 Web API template. Web API can go into any type of project (MVC, Console, Class Library, etc.), but the Web API template includes MVC so it can include an empty skeleton "ValuesController" class. You can also select an "Empty" project and add the Web API as a core reference to get have the Web API without MVC.

The Web API project includes a WebAPIConfig class in the App_Start folder which is called from the Application_Start method inside the global.asax. This is similar to the RouteConfig class which is used for configuring the MVC routes. However Web API provides a different set of extension methods for registering its routes than is used by MVC. Web API and MVC use completely different route classes and route collection types for their routes. This providers greater flexibility in hosting options and allows for Web API's self-hosting option.

.WebAPIConfig vs RouteConfig


WebAPIConfig vs RouteConfig

A valid ASP.NET Web API controller can be created by simply implementing the methods inside the IHttpController interface, but typically Web API controllers are created by deriving from the ApiController class. The ApiController class coordinates with other classes in the Web API object model to perform key tasks. As part of the Web API template, the ValuesController class shows the higher-level abstraction that can be built on top of the ApiController class.The Values Controller contains action methods whose names correspond to the HTTP verbs which are typically used to perform the database CRUD operations.

 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
using System.Collections.Generic;
using System.Web.Http;

namespace WebApplication1.Controllers
{
    [Authorize]
    public class ValuesController : ApiController
    {
        // GET api/values
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/values
        public void Post([FromBody]string value)
        {
        }

        // PUT api/values/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/values/5
        public void Delete(int id)
        {
        }
    }
}


ValuesController.cs

Error | ASP.NET Developer

Error

Error message

  • Warning: Cannot modify header information - headers already sent by (output started at /srv/disk9/1218369/www/kcshadow.net/aspnet/includes/common.inc:2748) in drupal_send_headers() (line 1232 of /srv/disk9/1218369/www/kcshadow.net/aspnet/includes/bootstrap.inc).
  • PDOException: SQLSTATE[42000]: Syntax error or access violation: 1142 INSERT command denied to user '1218369_b2cf'@'185.176.40.58' for table 'watchdog': INSERT INTO {watchdog} (uid, type, message, variables, severity, link, location, referer, hostname, timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9); Array ( [:db_insert_placeholder_0] => 0 [:db_insert_placeholder_1] => cron [:db_insert_placeholder_2] => Attempting to re-run cron while it is already running. [:db_insert_placeholder_3] => a:0:{} [:db_insert_placeholder_4] => 4 [:db_insert_placeholder_5] => [:db_insert_placeholder_6] => http://www.kcshadow.net/aspnet/?q=evolvable [:db_insert_placeholder_7] => [:db_insert_placeholder_8] => 54.162.171.242 [:db_insert_placeholder_9] => 1534728111 ) in dblog_watchdog() (line 160 of /srv/disk9/1218369/www/kcshadow.net/aspnet/modules/dblog/dblog.module).
The website encountered an unexpected error. Please try again later.