Professional Documents
Culture Documents
We are now got an basic introduction of Web API. In this introduction we found some terms like HTTP,
REST etc. Now we will discuss about those terms.
HTTP Basics:
+. As ASP.NET Web API enables handling HTTP protocols in an efficient and fluent manner using .NET
framework so we need a deeper understanding about HTTP.
+. The term HTTP stands for Hypertext Transfer Protocol. Its a network protocol that handles
communications (through requests and responses) between web browser and web server and finally
Deliver the resources (files and data) on the web. Resources can be HTML files, images, query results or
anything else thats unambiguously identified by URL. In this case the browser is the HTTP client and
web server is the HTTP server.
+. Though HTTP is a communication protocol, so it has a set of standardized elements. Both server and
client will deal with them. Lets see those elements:
+>. Resources and URIs
+>. HTTP Methods
+>. Safe Methods
+>. Idempotent Methods
+>. HTTP Status Codes
given by a URI
$. From the CRUD perspective by using DELETE method we actually
delete (D of CRUD) data from the server.
+>. Safe methods
+.Some HTTP methods are defined as safe method because by these methods
has no any side effects except some minor terms like logging, caching, counting
user accesses.
+. GET method is one of the methods. It only retrieve resources from the server
and show them into the browser.
+. On the other hand POST, PUT, DELETE methods are used for take actions like
Insert/Update/Remove resources or resource contents from the server. So they
create side effects on the server. With those methods also can add some
external effects like sent an e-mail etc. For example after creating a new user
sent him/her a notification email etc.
Caution:
Although GET requests are called the safe method but there is no technically
limitation for this method. So you can write any code by using GET method that
changes the state of the resource i.e. you can insert new resource, update
existing resource or delete existing resource by using GET method. In restful
application you should strictly avoid that because it can causes problems for web
caching, search engine and other automated agents those are rely on the safety
on GET.
+>. Idempotent Methods
+. Multiple requests should have same effect as a single request.
+. The GET, PUT, DELETE are commonly used Idempotent Methods.
$. If you use GET method for a specific resource for several it will always result as
the first time called i.e. always call that resource. No changes can be made by
multiple calls. For example: http://www.example.com/About . This method
always calls the About resources from the server as it called during the first time
calls.
$. If you use PUT method to update a specific resource by a new resource it will
always update that resource as first time. Not any other resource will updated.
$. If you use DELETE method for delete any specific resource content it will only
remove that content. There is no chance to remove other content.
$. If you use POST method for insert any resource each time you post that
method it will create a new resource. So it will make side effect.
+>. HTTP Status codes
+.HTTP status codes are important part of HTTP protocol.
+. These codes are used to indicate whether a specific HTTP request successfully
completed or not.
+. Based on the result of responses HTTP status codes are divided into 5 categories
$. Informational (1xx)
$. Successful (2xx)
$. Redirects (3xx)
$. Client Errors (4xx)
$. Server Errors (5xx)
$. Informational (1xx)
=O .Indicates the provisional response that consist only the status line
and optional Headers.
=O. The status code line is terminated by an empty line.
=O. There are no required headers for this class of Status code.
$. Successful (2xx)
=O .Indicates that the clients request was successfully received
understood and accepted.
$. Redirects (3xx)
=O. Indicate that the client needs to take further action in order to
complete the request.
=O. This class of status code indicates that further action needs to be
taken by the user agent in order to fulfill the request.
=O. The action required may be carried out by the user agent without
interaction with the user (if and only if the second request is GET or
HEAD).
=O. A user agent should not automatically redirect a request more
than five times, since such redirections usually indicate an infinite loop.
$. Client Errors (4xx)
=O. If client done something wrong then uses this class of status codes.
=O. For all requests (except HEAD) the server should include a response
body
@. Explaining the error,
@. Whether the error is permanent or temporary and
@. Whether the response body should be shown to the user
=O. This class of status can be applied to any request method.
$. Server Errors (5xx)
=O. Uses when the server is responsible for any error
=O. Also uses when the server is not able to perform the request.
=O. For all request (except HEAD) the server should include a response
body
@. Explaining the error,
@. Whether the error is permanent or temporary and
@. Whether the response body should be shown to the user
=O. This class of status can be applied to any request method.
+. In following table we are giving some commonly used HTTP Status codes and their descriptions.
Status Code
Message
Description
Information (1xx)
100
Continue
Indicates that everything so far is OK and the client
should continue with the request or ignore it if it is
already finished.
Successful (2xx)
200
OK
Indicate that the request is OK (The standard response of
successful HTTP requests)
201
Created
The request has been fulfilled and a new resource is
created
202
Accepted
The request has been accepted for processing but the
processing yet to complete.
203
Non-Authoritative
The request successfully processed but the returning
Information
information may be from another resources
204
No Content
The request has been successfully completed but is not
returning any content.
205
Reset Content
The request has been successfully processed but not
206
Partial Content
Redirects (3xx)
301
Moved Permanently
Bad Request
Unauthorized
403
Access Denied
404
Not Found
409
Conflict
REST
+. REST stands for Representational State Transfer
+. REST was first introduced by Roy Fielding.
+. REST is an architectural pattern for creating Services.
+. Before discussing details about REST we will consider Service Oriented Architectures using SOAP
protocol. Then we will discuss about REST architectural style for distributed applications.
+. We will also see how we can improve SOA by moving from SOAP to a RESTful architecture.
Service Oriented Architecture and HTTP
+. In prior to REST we used ASMX web services or Windows Communication Foundation (WCF) with
service oriented Architecture.
+.Both ASMX web services and Windows communication foundation (WCF) used SOAP protocol.
+. SOAP stands for Simple Object Access Protocol.
+. SOAP is a specification for exchanging structured data i.e. XML using web services that was built on
the top of the HTTP protocol.
+. Though SOAP relies on HTTP so it also follows the request/response model where both request and
response are represented by XML document and which is called message.
+. Following code shows how a typical SOAP request message. This message represents a request to a
customer service. By this request message actually invokes a method with its parameter value.
<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
<soap:Body xmlns:m="http://www.example.org/customer">
<m:GetCustomer>
<m:CustomerName>Microsoft</m:CustomerName>
</m:GetCustomer>
</soap:Body>
</soap:Envelope>
+>.At the very beginning of the SOAP message consist the header information as follows:
<?xml version="1.0"?>
+>. Then it consists an Envelope. This Envelope constrains the message body as follows:
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
<soap:Body xmlns:m="http://www.example.org/customer">
<m:GetCustomer>
<m:CustomerName>Microsoft</m:CustomerName>
</m:GetCustomer>
</soap:Body>
</soap:Envelope>
+>. This service should invoke the GetCustomer method.
+>. The GetCustomer method require a parameter named CustomerName. The value of the
parameter is Microsoft.
+. Above SOAP message is POST to the server via HTTP protocol. In order to send this SOAP message to
the server we used HTTP POST method because according to the HTTP specification in order to send
new content from the client to server we need POST method.
+. The HTTP POST request in SOAP should be shown as follows:
POST /coustomerservice HTTP/1.1
Host: www.example.org
Content-Type: application/soap+xml; charset=utf-8
Content-Length: 332
+.After some database operations the service will return the customer object wrapped in a response
message as follows:
<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
<soap:Body xmlns:m="http://www.example.org/customer">
<m:GetCustomerResponse>
<m:CustomerId>123</m:CustomerId >
<m:CustomerName>Microsoft</m:CustomerName>
</m:GetCustomerResponse>
</soap:Body>
</soap:Envelope>
+>. The response message is also same as the request message.
+. The response Header of the SOAP response will look as follows:
HTTP/1.1 200 OK
Content-Type: application/soap+xml
charset=utf-8
Content-Length: 390
+. Now lets try it again. But in this case we will misspell the customer name. Our request should be as
follows:
<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
<soap:Body xmlns:m="http://www.example.org/customer">
<m:GetCustomer>
<m:CustomerName>Microsft</m:CustomerName>
</m:GetCustomer>
</soap:Body>
</soap:Envelope>
+>.Here everything is same as previous except we misspelled Microsoft as Microsft.
+. The HTTP POST request in SOAP should be as previous as shown as follows:
POST /coustomerservice HTTP/1.1
Host: www.example.org
Content-Type: application/soap+xml; charset=utf-8
Content-Length: 332
+. The response generated by the server will be as follows:
<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
<soap:Body xmlns:m="http://www.example.org/customer">
<soap:Fault>
<faultcode>soap:Server</faultcode>
<faultstring>Customer could not be found.</faultstring>
<detail />
</soap:Fault></soap:Body>
</soap:Envelope>
+>. In this case the server says that it couldnt find a customer with a name Microsft.
+. The response Header of this SOAP will be same as previous as follows:
HTTP/1.1 200 OK
Content-Type: application/soap+xml
charset=utf-8
Content-Length: 390
+. Here one point to be noted. That is in both cases it responses status 200 i.e. OK although in second
case it didnt found any data. So we can say that it is (SOAP) not the best way for handling SOA.
+. Thats all about how we have handled SOA prior to REST.
+>. We dont need to send a request body that consumes bandwidth unnecessarily and is
potentially slower.
+. Now lets check what responses we are getting from the server.
+>. For the first request its responses as follows:
HTTP/1.1 200 OK
+>.And for the second request its responses as follows:
HTTP/1.1 404 NOT FOUND
+>.Here is the basic difference between SOAP & REST protocol. In SOAP protocol for both cases
it returned same HTTP response status code and message but in REST it send exact status
message and code that it doesnt found any resources in the server. So client will properly
understand what are happening in the server.
+>. Now the question is it works properly (returned the exact response code in REST protocol)
for HTTP GET method but the question is would it be work when we want to create data on
the server?
+>. The answer is of course it will. Lets check following code:
$. Here we are creating new Customer using HTTP REST protocol as follows:
POST /customers/ HTTP/1.1
Content-Type: application/vnd.247app.customer+xml
Accept: application/vnd.247app.customer+xml
<customer xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.example.org">
<name>Apress</name>
<address>233 Spring Street</address>
<city>New York</city>
</customer>
vendor specific.
@+.247app is the name of our application
@+.customer+xml indicates that the resource is in XML format.
Note:
If we prefer JSON (JavaScript Object Notation) format then our media
definition would be as follows:
application/vnd.247app.customer+json
We only need to modify +json instead of +xml to tell the server or client on
which format we want to GET or SET our customer. Also we dont need to
attach /xml or /json to our URI because we already tied it to HTTP at the very
beginning.
If we want to provide a PNG image for our customer logo then we will set
content-type: application/png i.e. application/vnd.247app.customerlogo+png.
By this format we will tell our server that it should be stream a PNG image.
In this case our URI should be unchanged as follows:
/customer/{id}/ i.e. http://www.example.com/customer/{id}/
@. Then we defined another HTTP header named Accept as follows:
Accept: application/vnd.247app.customer+xml
By this header we tell the server which media type we want to get (within the
response) for our current request.
+>. Now we will check what responses we got from the sever.
$. Response after creating a Customer using HTTP REST protocol as follows:
HTTP/1.1 201 CREATED
Location: http://www.example.org/customer/42
<customer xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.example.org">
<id>42</id>
<name>Apress</name>
<address>233 Spring Street</address>
<city>New York</city>
<link rel="self" href="http://www.expample.org/customer/42" />
<link rel="previous" href="http://www.example.org/customer/41" />
</customer>
Here it returns 201 Created which is more specific than just only saying
everything is OK (200). This response says the customer has been CREATED
(201) based on the input POSTed to the server.
@.The next response header is
Location: http://www.expample.org/customer/42
It tells the client where to find the newly created customer so that the client
can store the information for later uses.
@. Then it contain the response body which is same media type that we were
requested i.e. application/vnd.247app.customer+xml media type.
Note:
We requested the media type during send request to sever by using Accept
header (that we discussed earlier) as follows:
Accept: application/vnd.247app.customer+xml
<customer xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.example.org">
<id>42</id>
<name>Apress</name>
<address>233 Spring Street</address>
<city>New York</city>
<link rel="self" href="
http://www.expample.org/customer/42" type="
application/vnd.247app.customer+xml" />
<link rel="previous" href="
http://www.example.org/customer/41" type="
application/vnd.247app.customer+xml"/>
</customer>
@+. It was assigned an ID on server
@+. The body contains the details of the customer i.e. id, name, address, city
etc.
@+. There are also two <link/> tag inside the body of the response. A client can
follow the links to navigate through an application by entering a single fixed
URI.
REST in Theory
+. REST stands for Representational State Transfer.
+. This term first introduced by Roy T. Fielding in the year-2000.
+. REST is an Architectural pattern for creating services.
+. It uses HTTP as an application protocol and hypermedia.
+. The REST pattern is aware about the eight facilities of distributed computing. Those are:
$. The network is reliable
$. Latency is zero
$. Bandwidth is infinite
$. The network is secure
$. Topology doesnt change
$. There is one administrator
$. Transport cost is zero
$. The network is homogeneous.
+. By ignoring those facilities one may add harmful effects on application. So REST defines six
constraints to deal with above eight facilities.
+. Following figure shows those (six) constraints and the benefits that a RESTful application get from
those constraints.
Constraints
Client/server
Stateless
Cacheable
Layered system
Code on demand (optional)
Uniform interface
Benefits
Evolve-ability, portability of clients, scalability
Reliability, visibility, scalability
Performance, efficiency, scalability
Manageability, scalability
Managing complexity, extensibility
Evolve-ability, visibility
+. Now well see how these six constraints achieve the benefits:
$.Client/server
+>. This is the first constraint.
+>. Client sends the request and the server responses the clients request.
+>. This constraint improves the separation of concerns by separating servers from the clients
so$+. Client doesnt have to deal with data storage
$+. Client can evolve independent of the server.
$+. Allows the client software to be ported to other platforms or programming
languages.
$+. Servers dont need to care about UI
$.Stateless
+>. This constraint states that the communication between the client and the server must be
stateless between requests which means that
$. We should not be store client related anything on the server.
$. Every request from the client should contain all the necessary informations to
process the request by the server.
$. This ensures that each request can be treated independently by the server.
$. All session states also should be stored on the client.
$. This constraint embraces reliability, visibility and scalability.
$. Cacheable
+>. Client can cache the responses that they receive from the servers.
+>. Some data thats provided by sever like list of products or the list of department of a
company doesnt change frequently. So we can cache them to client.
+>. When require those data we can use them from the cache at client. So it reduces a lot of
client/server interaction and we can avoid unnecessary processing.
+>. Caching helps us to improve the performance and the scalability of the application.
+>. To prevent client from caching unnecessary data must declare the response is cacheable or
not.
$. Layered System
+>.By adding intermediary servers, load balances or shared caches to the system we can
improves the overall scalability.
+>. Security might be improved by enforcing security policies.
+>. By thats way client wont be able to determine whether they are communicating with the
end server or not.
$. Code on Demand (optional)
+>. The server is able to send executable code to the client to modify or add functionality on
the client side
+>. The coding is introduced with Java applets and achieved by using client side JavaScript.
$. Uniform Interface
+>.The uniform interface constraint defines the interface between the client and the server.
+>. To understand the uniform interface constraint we need to understand what a resource is
and the HTTP verbs i.e. GET, PUT, POST and DELETE.
+>. In the context of REST API resources typically represent data- entities like product,
employee, customer etc. are all resources.
+>. The HTTP verb GET, PUT, POST or DELETE i.e. each request tells the API what to do with
the resource. Each resource is identified by a specific URI. Following table shows some typical
requests of API.
Resource
Verb
Outcome
/Employees
GET
Get the list of employees
/Employees/1
GET
Get the employee whose id = 1
/Employees
POST
Create a new employee
/Employee/1
PUT
Update the employee whose id = 1
/Employee/1
DELETE
Delete the employee whose id = 1
@. The resource here is employee.
/Employees:
@+. The typical URI might be http://www.example.com/Employees . This is a HTTP GET
method and retrieves the list of employee
/Employee/1:
@+. The typical URI might be http://www.example.com/Employee/1 . This is also a HTTP GET
method and retrieves the employee whose id = 1.
/Employees:
@+. The typical URI might be http://www.example.com/Employees . This is a HTTP POST
method and creates a new employee on the server.
/Employee/1:
@+. The typical URI might be http://www.example.com/Employee/1 . This is a HTTP PUT
method. Update the employee whose id = 1.
/Employee/1:
@+. The typical URI might be http://www.example.com/Employee/1 . This is a HTTP DELETE
method. Delete the employee whose id = 1.
This constraint consists following four concepts:
>>. Identification of Resources
>>. Manipulation of resources through these representations
>>. Self-descriptive messages
>>. Hypermedia as the engine of application state (HATEOAS)
>>. Identification of Resources
+. The resources of the application can be identified by the URI.
+. The resources which are sent by the server to client are separated from their
representations. For example severs sends an XML or JSON fragment to the client and
it represents as a resource like customer with its properties.
>>. Manipulation of resources through these representations
+.If a client holds a representation of a resource e.g. customer including metadata and
has appropriate permission it is able to modify or delete the resource on the server for
that representation.
>>. Self-descriptive messages
+. Each message includes enough information to describe how to process the message.
For example the Internet media type tells the client or server how to parse the
message. Another example is the indication of cache-ability in server side response.
>>. Hypermedia as the engine of application state (HATEOAS)
+.After hitting a fixed entry point URI the client navigates through the application by
dynamically generated hypermedia (hypertext with hyperlinks) which the client
receives within the representations of the resources from the server.
Richardson Maturity Model
+. In the section Shifting to RESTful Architecture we saw how contentiously improved the application
from a classical Service Oriented Architecture (SOA) using SOAP also known as Plain Old XML (POX) to
RESTful model.
+.The path from POX to Hypermedia (HATEOAS) (inside the application) are described in three step
model by Leonard Richardson as follows:
+>. Richardson Maturity Model describes the levels leading to a RESTful architecture.
$. Level-0: POX
$+. It is the beginning level of the architecture.
$+. It uses XML over the HTTP also known as SOAP.
$+. Here it messed up HTTP methods and status code and made no use of any
improvement.
$. Level-1: Resources
$+. Embrace the use of Resource by introducing the unambiguous URIs for
those Resources.
$+.For example assume that our resources are customer and customers. So
their URIs can be /customer and /customers.
$. Level-2: HTTP Methods
$+. Makes proper uses of HTTP methods and status codes both on client and
server.
$. Level-3: Hypermedia
$+. By adding hypermedia to the application the peak of REST is finally
reached.
Why should I care about REST at all?
+.During developing a distributed application (that deals with a huge number of platforms and
programming languages) REST is a valid option.
+. When required different client deployment also REST is the good choice.
+. REST is better when it comes to the hosting at cloud.
+. When any application need to deal with eventual available connectivity (for example upcoming
mobile devices that yet not entered into the market) RESTful implementation is very useful to dealing
with those issues because REST is completely platform independent. So you will easily avoid the
platform and version dependency by using REST.
So consider a RESTful application to have a network-based API instead of library based API.
+>. Lets take a look about what it mean by Model, View and Controller
$. Models:
$+. Models are the objects.
$+.Models are used to retrieve and store the model (data) from and to the database.
$+. Let's see an example:
There is an object (model) named "item" that fetches the data from the database and
performs an operation and then stores the updated data into the database.
$. View:
$+. View components show the User Interface (UI) of the applications that is created by
the model.
$. For example the view of the Items shows the drop down list and textboxes that
depend on the current state of the "item" object.
$. Controllers:
$+. In MVC, controllers are also called the components.
$+. These components manage the user interaction and choose a view for displaying
the UI.
$. The main work of the controller is It manages the query string values and transfers
these values to the models.
+>. So in a single word we can say$. Models retrieve the information and store the updated information in the database.
$. Views are used for only displaying the information,
$.Controllers is used for managing and responding to the user inputs and their interaction.
HttpClient
+. Http client is a class that provides a way to handle requests and response in .NET asynchronously on
the client side.
Note: A server could also be a client.
+. Before using HttpClient class lets look some new classes thats being uses within both the HttpClient
class and ASP.NET Web API framework.
Commonalities: HTTP in ASP.NET Web API and HttpClient
+. As we know HTTP is a network transfer protocol that handles the communication between servers
and clients.
+. We also know that HttpClient represents the client-side implementation .NET framework. and
ASP.NET Web API represents the server-side implementation.
+. But HTTP is not about servers or clients- its about both sides because its mainly exchange the
requests and responses. So regardless whether we are implementing an HttpClient or an Web API
service we need to be able to access the content of HTTP requests. To do so
+>. In client side in order to get data from the server or modify data on the server we need to
set the URI related to the server root, the HTTP headers and so on.
+>. On server side we need to access incoming requests so that we can understand what the
client wants to done i.e. creating a new data, delivering or modifying existing data or starting
a subsequent process e.g.- sending an e-mail.
+. So Microsoft introduced a .NET class that draws away that complexity. This class is
HttpRequestMessage.
+. Lets check the implementation and usages of HttpRequestMessage:
HttpRequestMessage:
+.In HTTP based scenario everything starts with an HTTP request.
+. This HTTP request sent from the client to server.
+.In HttpClient and ASP.NET Web API all HTTP requests are represented by HttpRequestMessage class.
+. In .NET framework this class is resides under the namespace System.Net.Http. It is available as
built-in from .NET framework 4.5. So prior to .NET framework 4.5 i.e. if one uses .NET framework 4.0
then he/she need to install it from NuGet package. In that case the installable NuGet package name is
Microsoft.Net.Http.
+. The implementation of HttpRequestMessage confirms the HTTP messages that are defined in RFC2616.
+. Following is the public signature of HttpRequestMessage class that resides inside System.Net.Http
namespace:
public class HttpRequestMessage : IDisposable
{
public HttpContent Content { get; set; }
public HttpRequestHeaders Headers { get; }
public HttpMethod Method { get; set; }
public IDictionary<string,object> Properties { get; }
public Uri RequestUri { get; set; }
public Version Version { get; set; }
public HttpRequestMessage();
public HttpRequestMessage(HttpMethod method, String requestUri);
public HttpRequestMessage(HttpMethod method, Uri requestUri);
protected virtual void Dispose(Boolean disposing);
public override string ToString();
public void Dispose();
}
$+. The only difference is that it takes request Uri as of type Uri instead of string. It allows the
access of the URI as a typed way.
+>. There also contains three extra methods. They are
$. Two Dispose methods
$+.Both Dispose methods are concern disposing the HttpRequestMessage instance.
$.ToString method
$+. Overridden method.
$+. Produces some useful information that can be used for debugging or tracing purposes.
+. Now we will check the sample instantiation of HttpRequestMessage class and writing the ToString output on
the console window:
private static void Main(string[] args)
{
var request = new HttpRequestMessage(HttpMethod.Get, new Uri("http://example.com"));
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html"));
Console.WriteLine(request.ToString());
Console.ReadLine();
}