REST Basics
Upcoming SlideShare
Loading in...5
×
 

REST Basics

on

  • 2,438 views

Mobile applications Development - Lecture 14 ...

Mobile applications Development - Lecture 14

REST Basics

This presentation has been developed in the context of the Mobile Applications Development course at the Computer Science Department of the University of L’Aquila (Italy).

http://www.di.univaq.it/malavolta

Statistics

Views

Total Views
2,438
Views on SlideShare
2,438
Embed Views
0

Actions

Likes
3
Downloads
101
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    REST Basics REST Basics Presentation Transcript

    • REST Ivano Malavolta ivano.malavolta@univaq.ithttp://www.di.univaq.it/malavolta
    • Roadmap• The REST Architectural Style• Resources• Representations• Actions• Security
    • RESTIt stands forREpresentational State TransferProposed by Roy Fieldingsin his PhD dissertation in 2000REST rules the architecture ofthe World Wide Web (HTTP)
    • Major players
    • REST Architectural StyleREST is not a technology, nor a frameworkREST is an Architectural Style a set of principles + constraintsThos constraints help us in developing applications that are “easy” to maintain and extend
    • REST Main ConstraintsA RESTful system should be client-• client-server• stateless – there should be no need for the service to keep users’ sessions – each request should be independent of others• it has to support a caching system• it has to be uniformly accessible – each resource must have a unique address and a valid point of access
    • The (static) Web as a RESTful system1. you type a URL into your browser to reach a specific HTML page2. the browser gets and displays the elements of the HTML page the browser is getting a representation of the current state of that resource
    • REST Overview In most cases, client-server comunication relies on HTTPhttp://bit.ly/JALve1
    • REST Main ActorsThese are the abstractions that make a RESTful system:• Resources• Representations• Actions
    • Roadmap• The REST Architectural Style• Resources• Representations• Actions• Security
    • ResourcesA resource is “everything” the service can provide everything”States and functions of a remote application are also considered as resourcesExample of resources:• title of a movie from IMDb• a Flash movie from YouTube• images from Flickr• order info from eBay• etc.
    • ResourcesIn general, a RESTful resource is anything that is addressable over the WebAddressable = anything that can be accessed and transferred between clients and servers a resource must have a unique address over the Web Under HTTP these are URIs
    • URIs Uniform Resource Identifierin a RESTful web service is a hyperlink to a resourceIt is the only means for clients and servers to exchange representations of resources ex. .../orderinfo?id=123
    • URIsThe URI is not meant to change over time it is the only means to locate a specific resourceURIs are also used to negotiate representations of a given resourceIn the url you give certain parameters that define which information you want the server to return to you (just like giving GET variables to a page)The server will respond you with a resource representation containing the information you’ve asked
    • URIsURIs are also used to link resources togetherex.
    • Roadmap• The REST Architectural Style• Resources• Representations• Actions• Security
    • RepresentationsThe representation of resources is what is sent back and forth between clients and serversSo, we never send or receive resources, only their representations
    • URL Uniform Resource LocatorA URL is a specialization of URI that defines the network location of a specific resourceUnlike a URI, the URL defines how the resource can be obtained es. http://some.domain.com/orderinfo?id=123
    • RepresentationsThe format of the representation is determined by the content- content-typeThe interaction of the representation on the resource is determined by the action (GET, SET, etc.)
    • Content-typesSince we are using HTTP to communicate, we can transfer any kind of information that can be passed between clients and serversex. text files, PDF documents, images, videos, etc.In any case, the data is streamed over TCP/IP and the browser knows how to interpret the binary streams because of the HTTP protocol response header Content- Type
    • Representation FormatsDifferent clients are able to consume different representations of the same resourceA representation can take various forms such as: forms,• image• a text file• an XML stream• a JSON streambut its resource has to be available through the same URI
    • Representation FormatsFor human-generated requests through a web browser, a representation is typically in the form of an HTML pageFor automated requests from other web services, readability is not as important and a more efficient representation can be used such as XML or JSON
    • Roadmap• The REST Architectural Style• Resources• Representations• Actions• Security
    • ActionsActions are used to operate on resourcesFor example, they can be used for – getting info about a movie – adding a photo to Flickr – deleting a file from a folderThe data transmitted to and from the resource is a representation of it
    • HTTP-based ActionsUnder HTTP, actions are standard HTTP request: GET POST PUT DELETEThey make up the uniform interface used for client/server data transfers
    • HTTP-based ActionsRESTful web services can also execute logic at the server level, but remembering that every result must be a resource representation
    • HTTP as Uniform InterfaceIn RESTful systems we focus on resource names whereas names, in traditional web systems we focussed on the actions to be performed on resources In RESTful systems we have four specific actions that we can take upon resources — Create, Retrieve, Update, and Delete (CRUD) In traditional web applications, we could have countless actions with no naming or implementation standards
    • The Classroom ExampleArtificial example of a web service handling students in some classroomLocation of the service = http://restfuljava.com/Resources are represented as XML streams
    • The Classroom Example: URIsStudent (identified by name): http://restfuljava.com/students/{name}List of students: http://restfuljava.com/students
    • The Classroom Example: RepresentationsStudent:<student> <name>Jane</name> <age>10</age> <link>/students/Jane</link></student>
    • The Classroom Example: RepresentationsStudents List:<students> <student> <name>Jane</name> <age>10</age> <link>/students/Jane</link> </student> <student> <name>John</name> <age>11</age> <link>/students/John</link> </student></students>
    • GETThe method GET is used to RETRIEVE resourcesIt cannot have side-effects it can be done repeatedly without changing the state of the resourceIt can also return only parts of the resource it can act as both a read operation and a query operation
    • GET Example
    • POSTThe method POST is used to CREATE resourcesUsually, the resource identity/URL is not known at creation time The URL of the newly created resource is usually created automatically by the server
    • POST Example
    • PUTThe method PUT is used to UPDATE resourcesRecurrent PUT workflow:1. we first GET the representation of the resource we need to update2. in the client we update the resource with the new value(s)3. we update the resource using a PUT request together with the representation as its payload
    • PUT Example The initial GET isomitted here
    • DELETEThe method DELETE is used to DELETE resourcesSimilarly to PUT, also in this case we need the URI of the resource being deleted
    • DELETE Example
    • A note on PUT and DELETEPUT and DELETE apply to the entire resource when doing a PUT or DELETE operation, the entire resource is replaced/deletedThe PUT and DELETE operations are atomic if two PUT/DELETE operations occur simultaneously, one of them will win and determine the final state of the resource
    • HTTP Status CodesRESTful services use these codes to return information about the response of the requests 1xx informational message 2xx success message 3xx redirects the client to another URL 4xx client-side error 5xx server-side error
    • Roadmap• The REST Architectural Style• Resources• Representations• Actions• Security
    • SecurityHere we will focus on securing user access to our servicesThere are three main methods:1. Custom token authentication Control access to resources2. HTTP Basic authentication Accessing services3. OAuth on behalf of users
    • Custom Token Authentication2-steps process1. The server generates a unique token for a registered API user2. The registered user sends the generated token for authentication with every request to the serviceThe token can be used to enable a specific user, to check if traffic limits have been exceeded, etc.
    • Pros and Cons+ The generation of an access token is independent of the web service+ It is a simple approach – while creating a user registration process, the server generates a unique token per accountAccess+ data exchange can be logged and verified – since access is controlled for each request- This method is not secure – The passed token can be copied and reused without authorization
    • How to send the token?The authentication token is sent with every request in two ways:1. it can be part of the URI2. it can be added to the HTTP request header
    • HTTP Basic authentication The client sends the (cleartext Base64 encoded) username and password pair in the HTTP header Authorization Username and password must be sent for every HTTP request for the authorization to be validatedhttp://bit.ly/JFGCQW
    • Pros and Cons+ clients must manage server authorization requests- in general, it is not secure - because usernames and passwords are only encoded using Base64 encoding, which can be easily deciphered+ this potential security hole can be solved by using HTTPS (SSL)
    • Client/server transactionIt can take 2 forms:1. a client makes a request to the server without authentication credentials – the server sends a response with an HTTP error code of 401 (unauthorized access) – we need to programmatically intercept the 401 response and then provide valid credentials to complete the original request2. a client makes a request to the server with authentication credentials from the beginning
    • Example of Request<input type="text" name=“u" id=“u" value="" /><input type="password" name=“p" id=“p" value="" />var username = $(#u).val();var password = MD5($(#p).val());$.ajax({ type: POST, url: ‘https://www.domain.com/login.php, data: { username: username, password: password }, success: function(result) { console.log(“logged in”); }});
    • Oauth 2.0OAuths authorization protocol is becoming the preferred authorization schemeIt is simple and easy tointegrate to RESTful servicesOpen source protocol pen
    • What are we talking about...http://slidesha.re/JdfBGy
    • OAuthyour Serviceapp provider
    • OAuth 2.0It is used for accessing web services on the behalf of the userOAuth is an authorization protocol that allows third- third-party web service creators (you) to get access to users data stored in a different web serviceThis can happen only with users consent and without a username and password exchange
    • OAuth 2.0Before OAuth, users needed to pass login information to multiple third party servicesWith OAuth, users don’t divulge their login information authorization is granted from the provider service, where both user’s data and credentials are stored the consumer service only receives an authorization token that is used to access data from the provider service
    • OAuth BasicsAuthentication• Need to log in to access parts of a website – ex: view user profile – post a photo – add a friend – view private messagesToken-Token-based Authentication• Logged-in user has a unique token used to access data from your app
    • Intuition behind OAuth
    • OAuth 2.0 Authentication flow the user your app Auth Server (ex. Facebook) The server hosting protected resources (ex. Facebook)http://tools.ietf.org/html/draft-ietf-oauth-v2-26
    • Example: Google+
    • Referenceshttp://bit.ly/JA1UPTCordova plugin for FB: http://bit.ly/JdjoUh