rest webapi with odata
TRANSCRIPT
REST WEB SERVICES Mahek
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.
RESTAURANT
Client
API
Serv
er
Kitchen
WHY API’S?
• 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
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
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.
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.
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.
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.)
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)
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.)
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
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
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
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.
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
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
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
DEMOImplementing Web API
SECURITYBasically we require two techniques to make our WebApi more secure:o Authenticationo Authorizationo Maintaining Session
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.
BASIC AUTHENTICATION
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
TOKEN BASED AUTHORIZATION
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.
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
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
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
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
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
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.
HOW ODATA WORKS• OData has four main parts:1. OData data model2. OData protocol3. OData client libraries4. OData service
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.
INTERNAL WORKING
RESPONSE
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
QUERYING DATA• OData supports various kinds of query options for querying
data. • Example:
DATA MODIFICATION• Creating a resourceRequest Response
DATA MODIFICATION
• Deleting a resource Request : DELETE serviceRoot/People(‘Mahek’) Response: HTTP/1.1 204 No Content
DATA MODIFICATION• Updating a resource Request Response
DATA MODIFICATION• Relationships from one entity to another are represented
as navigation properties.• Example: Here two persons are related by friendship.
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.
ADVANCED FEATURES
• Singleton• Derived Entity Type• Batch
THANK YOU……