You are on page 1of 29

Web API 1.

0
By
Amareswar Rao

RESTful services/REST : Representational State Transfer


Introduction
HTTP is established and ubiquitous. As such, its well-suited
for many purposes, among which is creating an ASP.NET Web
API. These HTTP services are also known as Representational
State Transfer (RESTful services , or REST for short).

Web API is focused on using HTTP to expose your service

Web API builds upon the standard HTTP verbs,

Routing to define your URLs and

Content negotiation to exchange data with clients.


HTTP Methods

Status codes 200 (OK) 404 (Not Found)

201 (Created) 202 (Accepted)

400 (Bad Request) 204 (No Response)


HttpGet
HttpGet actions are usually the highest.

Retrieve all the items / retrieval by the key.

Checking for a valid result inside the method implementation and


throwing an HttpResponseException with an HttpStatusCode of
NotFound accomplishes this in a direct manner.

Although both would result in a 404, the unhandled 404 also


comes with an error message stating that it was unhandled to
provide an additional explanation.
HttpDelete
The most common way to accomplish the deletion of a record is to specify the
dataset key and use it to identify and delete the record.

its advisable to name any such operations with a prefix of Delete .

The first is a successfully processed request that has an HttpStatusCode of OK


(200).

A valid response is returned to the client, and information from the request can
be included.

The next outcome is an HttpStatusCode of Accepted (202), which indicates that


the request was processed and accepted, but is still pending.

The last outcome is an HttpStatusCode of No Response (204). Its important to


note that the method return type can directly aect this value.

When the type has a void return type, a value of 204 is automatically
transmitted back to the client.
HttpPost
Post operations should be named with a prefix of Post.

A method that maps to an HttpPost request can have various


return types (including void).

HTTP 1.1 protocol stipulates that when a resource is created,


the server responds with an HttpStatusCode of Created
(201).

If you dont specify otherwise, though, when the operation


is processed, the framework returns an HttpStatusCode of
OK (200),
A better implementation and one that would use the
System.Net.Http.HttpResponseMessage as the return type and would
provide information about the operation is the HttpResponseMessage.

This implementation returns a 201 status code and points to


the location of the newly created item.
HttpPut
The HttpPut is used for operations that correspond to upserts,
inserting for new records and updating for existing records.

An interesting side eect of supporting upserts is that the


method should be idempotent (that is, if you call the method
once or 100 times with the same data, there should be no
meaningful dierence in the side eects of calling it one or 100
times).

Any methods that execute update operations should use the


Put prefix.
Creating the model
ASP.NET Web API transparently handles sending your
model over HTTP.

It does so by serializing your models members to the


target format.

JavaScript Object Notation (JSON) and XML are two of


the best-known formats.

After the models information is serialized, the framework


will take the serialized data and insert it into the Body
element of the HTTP response message.
Creating the controller
The primary purpose of the controller is to handle
HTTP requests.

The controller implementation you create needs to


inherit from the ApiController class.

The members that manipulate the model types are


known as action methods , action handlers , or simply
actions .

No extra attributes are needed on a method to facilitate


it becoming an action; it simply needs to be a public
method defined as part of the controller instance.
Static class as data
source
http://localhost:PORTNUMBER/api/Account
http://localhost:PORTNUMBER/api/Account?accountId=1
Browser functionality and
support
the latest version of Chrome and Firefox displayed the
data as in-page XML,

whereas the latest version of Internet Explorer


prompted you to download JSON data.

The reason you sometimes get XML and sometimes get


JSON is because dierent values are sent in the Accept
header.
Specifically, its the application/xml portion of the header
thats causing the XML to come back for those versions of
those browsers.
Mapping URI space using
routing
A Routing Table is a class that
implements the
System.Web.Http.Routing.IHttpR
oute interface and performs the
simple task of mapping an
incoming HttpRequestMessage to
a specified controller and action.
Navigating to the URI executes an HTTP request that
starts the processing pipeline.

The request is received, and the Web API framework


tries to match it to one of the route templates defined in
the Routing Table.

If a match is found, the request is forwarded and


processed as expected;

if not, an HttpStatusCode of 404 is returned to the


client.
If a matching route is present:

To match the correct controller, the Web API adds the literal
Controller to the controller variable.

To match an action, the Web API examines the HTTP method


and tries to match it to an action whose name corresponds to the
HTTP method name.

By default, the action names used correspond to four specific


HTTP methods: GET, POST, PUT, and DELETE. Its important
to note, however, that this mechanism works specifically only for
these four methods. You can define and enable other HTTP
methods, but a dierent convention is used for processing.

Finally, placeholder variables in the route template are mapped


specifically to the corresponding action parameters.
HTTP Methods
HttpGet HttpDelete

HttpPost HttpPut
System.Web.Http.AcceptVerbsAttribute

There are cases for which you will want to define


multiple actions on a given method or to define an
action other than the four default ones. To support
these scenarios, use the
System.Web.Http.AcceptVerbsAttribute class.
ActionNameAttribute In
URI

http://localhost:PORTNUMBER/api/Controller/Customers/1

http://localhost:PORTNUMBER/api/Controller/Customers/GetCustomers/1
http://localhost:PORTNUMBER/data/Customer/SearchCustomers?
lastName=r (ERROR)

http://localhost:PORTNUMBER/data/Customer/FindCustomers?
lastName=r (No ERROR)

NonActions

Any Controller method defined with the public access modifier is accessible
by default. There are certainly times when you might need to have the
member typed with the public modifier but dont want it exposed to clients.
In these cases, simply annotate each such method with the NonAction
attribute, and it will be explicitly prevented from being invoked.
Appropriate formats for
responses
Request contains something called an Accept header , which
specifies the type of data that you as a client expect from the server

Accept: text/html,application/xhtml+xml,application/xml

By default, Web API works with both JSON and XML data.

Returning the correct format is done by an object called a media-


type formatter . These classes are capable of both reading and
writing objects to and from the HTTP message body.

The process of returning your data in the format requested by the


client is called content negotiation.
HTTP actions asynchronous
Asynchronous code is all about freeing your thread to
process other requests while the I/O is being processed.

This lets your server process more requests with fewer


threads.

CPU-bound work (not a good practice)

I/O-bound work (good practice)

I/O-bound work will free your thread to really work on


something else until your I/O work is done, and a thread
will be asked to continue working with it.
Behind the scenes, the compiler will translate your code
into a complex state machine that keeps track of all
asynchronous operations and exception handling to
make your code look as if it is synchronous.

You might also like