220 likes | 350 Views
RESTful applications. Norman White. REST . Representational state transfer Key concepts Client Server architecture built on transferring resources between clients and servers A representation of a resource is a document that captures the current or intended state of a resource
E N D
RESTful applications Norman White
REST • Representational state transfer • Key concepts • Client Server architecture built on transferring resources between clients and servers • A representation of a resource is a document that captures the current or intended state of a resource • Usually built on top of HTTP, but doesn’t have to be
REST Constraints • Client-Server – Uniform interface, clients not concerned with storage • Stateless – no client context stored on server between requests (Eg. Google Search results) • Cacheable- Clients can cache responses • Layered system – Client can not tell whether they are connected to and end server or an intermediary • Code on demand (optional) – Srvers can extend functionality of client by sending code to be executed on the client. (i.e. java, javascript) • Uniform Interface – between clients and servers
Interface Principles • Identification of resources • Individual resources are identified in request, for example using URI’s in web systems • Manipulation of Resources through these representations • When a client holds a representation of a resource (including metadata), it has info to modify or delete the resource • Self-descriptive messages • Each message has enough info to process it, including caching • Hypermedia as the engine of application state • Clients make state transitions only through actions that are identified by the server (i.e. hyperlinks)
Goals • Scalability • Generality of interfaces • Independent deployment of components • Intermediary components to reduce latency, enforce security and encapsulate legacy systems
From Fielding Thesis REST's client–server separation of concerns simplifies component implementation, reduces the complexity of connector semantics, improves the effectiveness of performance tuning, and increases the scalability of pure server components. Layered system constraints allow intermediaries—proxies, gateways, and firewalls—to be introduced at various points in the communication without changing the interfaces between components, thus allowing them to assist in communication translation or improve performance via large-scale, shared caching. REST enables intermediate processing by constraining messages to be self-descriptive: interaction is stateless between requests, standard methods and media types are used to indicate semantics and exchange information, and responses explicitly indicate cacheability.[10]
RESTful web services • Based on http • Uses GET, POST, PUT and DELETE as basic operations • GET • List / Retrieve information • Put • Replace object • Post • Create a new object • DELETE • Deletes an object
Use Cases for Mobile • RESTful web services make it easy for mobile apps to interact with remote data bases using AJAX requests. • Typically, information is passed back and forth as a JSON object, where the web service can provide the object when requested, as well as update it, delete it etc.
JSONJavaScript Object Notation • JSON stands for JavaScript Object Notation • JSON is lightweight text-data interchange format • JSON is language independent * • JSON is "self-describing" and easy to understand * JSON Parsers and libraries exist for most web programming languages
JSON Example • {"employees": [{ "firstName":"John" , "lastName":"Doe" }, { "firstName":"Anna" , "lastName":"Smith" }, { "firstName":"Peter" , "lastName":"Jones" }]}
JSON === Javascript object • JSON - Evaluates to JavaScript Objects • The JSON text format is syntactically identical to the code for creating JavaScript objects. • Because of this similarity, instead of using a parser, a JavaScript program can use the built-in eval() function and execute JSON data to produce native JavaScript objects. • Hence, we can move javascript objects between a server (RESTful) and a mobile app.
Example • <!DOCTYPE html><html><body><h2>JSON Object Creation in JavaScript</h2><p>Name: <span id="jname"></span><br /> Age: <span id="jage"></span><br /> Address: <span id="jstreet"></span><br /> Phone: <span id="jphone"></span><br /> </p> • <script>varJSONObject= {"name":"John Johnson","street":"Oslo West 555", "age":33,"phone":"555 1234567"};document.getElementById("jname").innerHTML=JSONObject.name document.getElementById("jage").innerHTML=JSONObject.agedocument.getElementById("jstreet").innerHTML=JSONObject.streetdocument.getElementById("jphone").innerHTML=JSONObject.phone</script></body></html>
But WAIT! What if I retrieve the object from a server? • I can issue a GET request to a server which returns a JSON Object as a string. • I can then either “eval” the object or use a JSON parser to create the object locally. • Once I have it, I can use it like any javascript object, do computations on it, display it in a div, … • And, the reverse is true. I can take a local mobile object (say input from the user, their location, the time, … ) and turn it into a JSON string which gets sent back to the server using PUT or POST.
JSON Syntax • JSON syntax is a subset of the JavaScript object notation syntax: • Data is in name/value pairs • Data is separated by commas • Curly braces hold objects • Square brackets hold arrays
JSON Values • JSON values can be: • A number (integer or floating point) • A string (in double quotes) • A Boolean (true or false) • An array (in square brackets) • An object (in curly brackets) • null
JSON Arrays • {"employees": [{ "firstName":"John" , "lastName":"Doe" }, { "firstName":"Anna" , "lastName":"Smith" }, { "firstName":"Peter" , "lastName":"Jones" }] • Is the same as (If I “eval” the JSON object) • var employees = [{ "firstName":"John" , "lastName":"Doe" }, { "firstName":"Anna" , "lastName":"Smith" }, { "firstName":"Peter" , "lastName": "Jones" }]; • Employees[0].lastName is “Doe”
PHP ExampleServer side • <?php//request data from the database//code here to connect to database and get the data you want/* Example JSON format{ "item1": "I love jquery4u", "item2": "You love jQuery4u", "item3": "We love jQuery4u"}*///return in JSON formatecho "{";echo "item1: ", json_encode($item1), "\n";echo "item2: ", json_encode($item2), "\n";echo "item3: ", json_encode($item3), "\n";echo "}";?>
$.getJson Description: Load JSON-encoded data from the server using a GET HTTP request jQuery.getJSON( url [, data ] [, success( data, textStatus, jqXHR ) ] ) url Type: String A string containing the URL to which the request is sent. data Type: PlainObject A plain object or string that is sent to the server with the request. success( data, textStatus, jqXHR ) Type: Function() A callback function that is executed if the request succeeds.
JQUERY getJSON function Json-data.php is a php page that returns Values for item1, item2, and item3 in a json object. $(document).ready(function(){ //attach a jQuery live event to the button $('#getdata-button').live('click', function(){ $.getJSON('json-data.php', function(data) { //alert(data); //uncomment this for debug //alert (data.item1+" "+data.item2+" "+data.item3); //further debug $('#showdata').html("<p>item1="+data.item1+" item2="+data.item2+" item3="+data.item3+"</p>"); }); });});
Conclusion • HTTP is actually a good basis for building web services • We can use JSON objects to move data between the client and the server • Just add PUT and DELETE to GET and POST • Many frameworks for providing RESTful web services (like Cherrypy in python) • Much simpler than SOAP, where each application defines it’s own semantics • Note, web services are not the same as web servers, since they don’t just return HTML • Many sites provide a web service API to get data. • (i.e Flickr)
Load pictures from Flicker • <!DOCTYPE html><html><head> <style>img{ height: 100px; float: left; }</style> <script src="http://code.jquery.com/jquery-1.5.js"></script></head><body> <div id="images"></div><script>$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", { tags: "jquery",tagmode: "any", format: "json"}, • function(data) { $.each(data.items, function(i,item){ $("<img/>").attr("src", item.media.m).appendTo("#images"); if ( i == 3 ) return false; }); });</script></body></html>