Covers topics like RestApi, Authentication, Authorization, Cacheability, Advantage of RestApi over SOAP and some basics regarding Open Data Protocol(OData).
2. WHAT IS WEB API?
• API(Application Programming Interface) is a interface between two
software which allows interaction between each other.
• It is a messenger, which receives the request for services, send it to
the server and finally respond it to the client.
• E.g. Consider a restaurant where customer(Client), who orders the
food to the waiter(API), and kitchen room(Server) receives the order
and delivers the food.
5. • We need a service for any device with front end
o Easy
o Simple
o Lightweight
o All features of HTTP
• ReST-ful(Representational State Transfer) Services fulfill all the
above needs.
Need of API’s
6. INTRODUCTION TO REST
• It is an architectural pattern for developing web services as opposed
to a specification.
• REST architectures are realized by applying specific interaction
constraints such as performance, reliability, scalability, simplicity,
modifiability, visibility and portability.
• Web service API’s that adheres to REST architectural constraints are
RESTful Web API’s
7. INTRODUCTION TO REST
• REST web services communicate over the HTTP specification, using
HTTP vocabulary:
o Methods (GET, POST, etc.)
o HTTP URI syntax (paths, parameters, etc.)
o Media types (xml, json, html, plain text, etc)
o HTTP Response codes.
8. INTRODUCTION TO REST
• Representational
o Clients possess the information necessary to identify, modify, and/or delete a
web resource.
• State
o All resource state information is stored on the client.
• Transfer
o Client state is passed from the client to the service through HTTP.
9. INTRODUCTION TO REST
The six characteristics of REST:
1. Uniform interface
2. Decoupled client-server interaction
3. Stateless
4. Cacheable
5. Layered
6. Extensible through code on demand (optional)
*Services that do not conform to the above required constraints
are not strictly RESTful web services.
10. HTTP-REST REQUEST BASICS
• The HTTP request is sent from the client.
o Identifies the location of a resource.
o Specifies the verb, or HTTP method to use when accessing the
resource.
o Supplies optional request headers (name-value pairs) that
provide additional information the server may need when
processing the request.
o Supplies an optional request body that identifies additional data to
be uploaded to the server (e.g. form parameters, attachments, etc.)
11. HTTP-REST REQUEST BASICS
• A typical client GET request:
• A typical client POST request:
POST /save HTTP/1.1
User-Agent: IE
Content-Type: application/x-www-form-urlencoded
[CRLF]
name=x&id=2
Requested Resource (path and query string)
Request Headers
(no request body)
Requested Resource (typically no query string)
Request
Headers
Request Body (e.g. form parameters)
12. HTTP-REST RESPONSE BASICS
• The HTTP response is sent from the server.
o Gives the status of the processed request.
o Supplies response headers (name-value pairs) that provide
additional information about the response.
o Supplies an optional response body that identifies additional data
to be downloaded to the client (html, xml, binary data, etc.)
13. HTTP-REST RESPONSE BASICS
• Sample Server Responses:
HTTP/1.1 500 Internal Server Error
HTTP/1.1 201 Created
Location: /view/7
[CRLF]
Some message goes here.
Response StatusHTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 1337
[CRLF]
<html>
<!-- Some HTML Content. -->
</html>
Response Headers
Response Body (content)
Response Status
Response Status
Response Header
Response Body
Response Status
14. HTTP-REST VOCABULARY
HTTP Methods supported by REST:
• GET – Requests a resource at the request URL
o Should not contain a request body, as it will be discarded.
o May be cached locally or on the server.
o May produce a resource, but should not modify on it.
• POST – Submits information to the service for processing
o Should typically return the new or modified resource.
• PUT – Add a new resource at the request URL
• DELETE – Removes the resource at the request URL
• OPTIONS – Indicates which methods are supported
• HEAD – Returns meta information about the request URL
15. HTTP-REST VOCABULARY
A typical HTTP REST URL:
• The protocol identifies the transport scheme that will be used to process and respond to
the request.
• The host name identifies the server address of the resource.
• The path and query string can be used to identify and customize the accessed resource.
http://my.store.com/fruits/list?category=fruit&limit=20
protocol host name path to a
resource
query string
16. HTTP AND REST
A REST service framework provides a controller for routing HTTP
requests to a request handler according to:
• The HTTP method used (e.g. GET, POST)
• Supplied path information (e.g /service/listItems)
• Query, form, and path parameters
• Headers, cookies, etc.
17. ROUTING IN WEB API
Characteristics of routing in Web API:
• We can use API controller names and a naming convention for
actions to route Web API requests
• Alternatively we can use the following attributes to control the
mapping of HTTP requests (HTTP Verb+URL) to actions in the
controller:
• The HttpGet, HttpPut, HttpPost, or HttpDelete attributes
• The AcceptVerbs attribute
• The ActionName attribute
18. CREATING A WEB API FOR AN MVC 4
WEB APPLICATION
To create a Web API for a an MVC4 application:
1. Implement a Web API template in your project:
o In the New Project dialog box, click ASP.NET MVC 4 Web Application
o In the Select a Template box of the New ASP.NET MVC 4 Project dialog box, click Web
API
2. Add an MVC API controller class to the project:
o Hosts application code for handling requests
o Derives from the ApiController base class
3. Add action methods to the controller class
19. USING ROUTES AND CONTROLLERS
IN WEB API’S
Routing in ASP.NET MVC4 applications involves the following:
• ASP.NET adds a default route to:
o Map a URL and a controller
o Support the operations of the REST-style Web APIs
• We can modify the default route to include multiple actions in the
same HTTP method
• We can use the WebApiConfig class to:
o Modify the routing
o Enable multiple versions of API to coexist in the same project
21. SECURITY
Basically we require two techniques to make our WebApi more
secure:
o Authentication
o Authorization
o Maintaining Session
22. SECURITY
Basic Authentication
o Basic authentication is a mechanism, where an end user gets
authenticated through our service i.e. RESTful service with the help
of plain credentials such as user name and password.
o An end user makes a request to the service for authentication with
user name and password embedded in request header.
o Service receives the request and checks if the credentials are valid
or not, and returns the response accordingly, in case of invalid
credentials, service responds with 401 error code i.e. unauthorized.
24. SECURITY
Token Based Authorization
o Authorization part comes just after authentication, once
authenticated a service can send a token to an end user through
which user can access other resources.
o The token could be any encrypted key, which only server/service
understands and when it fetches the token from the request made by
end user, it validates the token and authorizes user into the system
o Token can have its own lifetime, and may expire accordingly
26. MAINTAINING SESSION
• We can maintain sessions using Token based Authorization.
• An authenticated user will be allowed to access resources for a
particular period of time, and can re-instantiate the request with an
increased session time delta to access other resource or the same
resource.
• We may need to implement login/logout for a user, to maintain
sessions for the user, to provide roles and permissions to their user,
all these features could be achieved using basic authentication and
token based authorization.
27. CACHING
• HTTP caches can store copies of responses
• Useful for reducing:
o Network traffic
o Server workload
o Call latency
• Caches are a main factor for scalability on the web
28. CACHE-HEADERS
• Cache-Control
o no-cache (Default): Response may be cached, but revalidated on next request
o no-store: Do not store a local copy
o max-age: Set TTL, in seconds
o private: Do not store in proxies
• Expires
o Default value: -1 (expired)
o Specify date of expiration (UTC, up to a year from today)
o max-age takes precedence
• While a resource is cached and hasn’t expired, no request is sent to
the server
29. CACHING
• ETag (entity tag) contains a resource’s version
• Can be a hash, timestamp, version number, GUID, …
• First time:
Client
sends a request
Server adds ETag
header to response
Client caches
response with ETag
30. CACHING
• ETag (entity tag) contains a resource’s version
• Can be a hash, timestamp, version number, GUID, …
• Subsequent calls:
Client sends a
request with ETag
Server compares
ETag to resource’s
version
Respond with
HTTP 304
(Unmodified)
Respond with the
updated resource
and Etag
Client caches
response with
ETag
31. REST SERVICES OVER SOAP
REST is easier to use for the most part and is more flexible. It has the following
advantages when compared to SOAP:
o No expensive tools require to interact with the Web service
o REST is lightweight as compare to SOAP
o Smaller learning curve
o Efficient (SOAP uses XML for all messages, REST can use smaller message formats)
o Fast (no extensive processing required)
o Closer to other Web technologies in design philosophy
32. ODATA
• Open Data protocol(OData) is an open protocol for sharing data.
• It is built upon AtomPub, itself an extension of Atom Publishing
Protocol.
• Odata is based on REST; therefore a simple web browser can view
the data exposed through an Odata service.
• It not only allows read access but also whole set of CRUD
operations.
33. HOW ODATA WORKS
• OData has four main parts:
1. OData data model
2. OData protocol
3. OData client libraries
4. OData service
34. REQUESTING RESOURCES
• As an example we use the service of an open trip management system.
• If a person named Russell White, who has formerly registered at Tripin,
would like to find out who are the other people in it.
37. REQUESTING RESOURCES
• By Individual resource
url: serviceRoot/People(‘Mahek’)
• By Individual property
url: serviceRoot/Airports(‘IGI’)/Name
• By Individual property Raw Value
url: serviceRoot/Airports(‘IGI’)/Name/$value
38. QUERYING DATA
• OData supports various kinds of query options for querying data.
• Example:
42. DATA MODIFICATION
• Relationships from one entity to another are represented as
navigation properties.
• Example: Here two persons are related by friendship.
43. DATA MODIFICATION
Invoking Function
• OData supports defining functions to represent complicated logic
which can be frequently used.
• Example
After having explored the TripPin OData service, Russell finds out
that it has a function called GetInvolvedPeople from which he can
find out the involved people of specific trip.