Rest WebAPI with OData

45
REST WEB SERVICES Mahek

Transcript of Rest WebAPI with OData

Page 1: Rest WebAPI with OData

REST WEB SERVICES Mahek

Page 2: Rest WebAPI with OData

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.

Page 3: Rest WebAPI with OData

RESTAURANT

Client

API

Serv

er

Kitchen

Page 4: Rest WebAPI with OData

WHY API’S?

Page 5: Rest WebAPI with OData

• We need a service for any device with front endo Easyo Simpleo Lightweighto All features of HTTP

• ReST-ful(Representational State Transfer) Services fulfill all the above needs.

Need of API’s

Page 6: Rest WebAPI with OData

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

Page 7: Rest WebAPI with OData

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.

Page 8: Rest WebAPI with OData

INTRODUCTION TO REST• Representationalo Clients possess the information necessary to identify, modify, and/or

delete a web resource.• Stateo All resource state information is stored on the client.

• Transfero Client state is passed from the client to the service through HTTP.

Page 9: Rest WebAPI with OData

INTRODUCTION TO RESTThe six characteristics of REST:

1. Uniform interface2. Decoupled client-server interaction3. Stateless4. Cacheable5. Layered6. Extensible through code on demand (optional)*Services that do not conform to the above required constraints are not strictly RESTful web services.

Page 10: Rest WebAPI with OData

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.)

Page 11: Rest WebAPI with OData

HTTP-REST REQUEST BASICS• A typical client GET request:

• A typical client POST request:POST /save HTTP/1.1 User-Agent: IEContent-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)

Page 12: Rest WebAPI with OData

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.)

Page 13: Rest WebAPI with OData

HTTP-REST RESPONSE BASICS• Sample Server Responses:

HTTP/1.1 500 Internal Server Error

HTTP/1.1 201 CreatedLocation: /view/7[CRLF]Some message goes here.

Response StatusHTTP/1.1 200 OKContent-Type: text/htmlContent-Length: 1337[CRLF]<html> <!-- Some HTML Content. --></html>

Response Headers

Response Body (content)

Response Status

Response Status

Response Header

Response Body

Response Status

Page 14: Rest WebAPI with OData

HTTP-REST VOCABULARYHTTP Methods supported by REST:• GET – Requests a resource at the request URLo 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 processingo 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

Page 15: Rest WebAPI with OData

HTTP-REST VOCABULARYA 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

Page 16: Rest WebAPI with OData

HTTP AND RESTA 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.

Page 17: Rest WebAPI with OData

ROUTING IN WEB APICharacteristics 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

Page 18: Rest WebAPI with OData

CREATING A WEB API FOR AN MVC 4 WEB APPLICATIONTo 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 Applicationo 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 requestso Derives from the ApiController base class

3. Add action methods to the controller class

Page 19: Rest WebAPI with OData

USING ROUTES AND CONTROLLERS IN WEB API’SRouting in ASP.NET MVC4 applications involves the following:• ASP.NET adds a default route to:

o Map a URL and a controllero 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 routingo Enable multiple versions of API to coexist in the same project

Page 20: Rest WebAPI with OData

DEMOImplementing Web API

Page 21: Rest WebAPI with OData

SECURITYBasically we require two techniques to make our WebApi more secure:o Authenticationo Authorizationo Maintaining Session

Page 22: Rest WebAPI with OData

SECURITYBasic Authenticationo 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. 

Page 23: Rest WebAPI with OData

BASIC AUTHENTICATION

Page 24: Rest WebAPI with OData

SECURITYToken Based Authorizationo 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

Page 25: Rest WebAPI with OData

TOKEN BASED AUTHORIZATION

Page 26: Rest WebAPI with OData

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. 

Page 27: Rest WebAPI with OData

CACHING• HTTP caches can store copies of responses • Useful for reducing:o Network traffico Server workloado Call latency

• Caches are a main factor for scalability on the web

Page 28: Rest WebAPI with OData

CACHE-HEADERS• Cache-Controlo no-cache (Default): Response may be cached, but revalidated on next

requesto no-store: Do not store a local copyo max-age: Set TTL, in secondso private: Do not store in proxies

• Expireso 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

Page 29: Rest WebAPI with OData

CACHING• ETag (entity tag) contains a resource’s version• Can be a hash, timestamp, version number, GUID, …• First time:

Clientsends a request

Server adds ETag header to response

Client caches response with

ETag

Page 30: Rest WebAPI with OData

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

Identical

Respond with HTTP 304

(Unmodified)

Different Respond with the updated resource

and Etag

Client caches response with

ETag

Page 31: Rest WebAPI with OData

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 serviceo REST is lightweight as compare to SOAPo Smaller learning curveo 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

Page 32: Rest WebAPI with OData

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.

Page 33: Rest WebAPI with OData

HOW ODATA WORKS• OData has four main parts:1. OData data model2. OData protocol3. OData client libraries4. OData service

Page 34: Rest WebAPI with OData

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.

Page 35: Rest WebAPI with OData

INTERNAL WORKING

Page 36: Rest WebAPI with OData

RESPONSE

Page 37: Rest WebAPI with OData

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

Page 38: Rest WebAPI with OData

QUERYING DATA• OData supports various kinds of query options for querying

data. • Example:

Page 39: Rest WebAPI with OData

DATA MODIFICATION• Creating a resourceRequest Response

Page 40: Rest WebAPI with OData

DATA MODIFICATION

• Deleting a resource Request : DELETE serviceRoot/People(‘Mahek’) Response: HTTP/1.1 204 No Content

Page 41: Rest WebAPI with OData

DATA MODIFICATION• Updating a resource Request Response

Page 42: Rest WebAPI with OData

DATA MODIFICATION• Relationships from one entity to another are represented

as navigation properties.• Example: Here two persons are related by friendship.

Page 43: Rest WebAPI with OData

DATA MODIFICATIONInvoking 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.

Page 44: Rest WebAPI with OData

ADVANCED FEATURES

• Singleton• Derived Entity Type• Batch

Page 45: Rest WebAPI with OData

THANK YOU……