consuming restful web services in php

48
1 Consuming RESTful Web Services in PHP Zoran Jeremić, PhD [email protected]

Upload: zoran-jeremic

Post on 14-May-2015

28.118 views

Category:

Technology


2 download

DESCRIPTION

Consuming RESTful Web services in PHP with cURL, AJAX and jQuery used at School of Business administration FON, Belgrade

TRANSCRIPT

Page 1: Consuming RESTful Web services in PHP

1

Consuming RESTful Web Services in PHP

Zoran Jeremić, PhD [email protected]

Page 2: Consuming RESTful Web services in PHP

2

Objectives

• Why build HTML client applications • Key REST principles • Technologies to build client applications • HTTP, JSON, AJAX • Consuming REST with PHP and cURL library • PHP and JSON • Consuming REST with jQuery • LAB: Client application for listing and commenting movies • Real world example: DEPTHS

Page 3: Consuming RESTful Web services in PHP

3

REST = "Representation State Transfer"

Dispatcher

WebApp

Cache (Resource)

Page 4: Consuming RESTful Web services in PHP

4

Key REST principles

• Give every “thing” an ID • Link things together • Use standard methods • Resources with multiple representations • Communicate statelessly

Page 5: Consuming RESTful Web services in PHP

5

Technologies

• Todays’s set of technologies used to empower RESTful paradigm: – HTTP as the basis, – PHP to add dynamic behaviour to HTML pages, – XML and JSON for data exchange, and – AJAX and jQuery for client-side programming (e.g. browser).

Page 6: Consuming RESTful Web services in PHP

6

TECHNICAL SOLUTION TECHNOLOGIES

Page 7: Consuming RESTful Web services in PHP

7

• Hypertext Transfer Protocol (HTTP) – A protocol for distributed, collaborative, hypermedia information systems. – Currently dominant version is HTTP/1.1.

• Massively used to deliver content over the Web – Web browsers and spiders are relying on HTTP.

• The protocol is not constrained to TPC/IP – It only presumes a reliable transport.

• Resources accessed by HTTP are identified by URIs (more specifically URLs), using the http URI schemes.

• HTTP functions as a request-response protocol in the client-server computing model.

HTTP Overview

Page 8: Consuming RESTful Web services in PHP

8

• HTTP request methods indicate the desired action to be performed on the identified resource:

– GET • Requests a representation of the specified resource. GET should not be used for operations

that cause side-effects (problematic with robots and crawlers). Those operations are called safe operations.

– POST • Submits data to be processed (e.g., from an HTML form) to the identified resource. The data

is included in the body of the request. – PUT

• Uploads a representation of the specified resource. – DELETE

• Deletes the specified resource.

HTTP Request methods

Page 9: Consuming RESTful Web services in PHP

9

JSON Overview

• JavaScript Object Notation (JSON) – A lightweight computer data interchange format.

• Represents a simple alternative to XML – A text-based, human-readable format for representing simple data structures and

associative arrays (called objects).

• Used by a growing number of services • JavaScript-friendly notation

– Its main application is in Ajax Web application programming.

• A serialized object or array • No namespaces, attributes etc. • No schema language (for description, verification)

Page 10: Consuming RESTful Web services in PHP

10

JSON Example

{ "firstName": "John", "lastName": "Smith", "age": 25, "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": "10021" }, "phoneNumbers": [ { "type": "home", "number": "212 555-1234" }, { "type": "fax", "number": "646 555-4567" } ], "newSubscription": false, "companyName": null }

Page 11: Consuming RESTful Web services in PHP

11

AJAX Overview

• Asynchronous JavaScript and XML (AJAX) – A group of interrelated web development techniques used on the client-side to create

interactive web applications – Web apps can fetch data from the server without refreshing the page

• AJAX is used to increase interactivity and dynamic of web pages

• Since the technological base is partially shared AJAX and RESTful

services make a good match – Enriching Web pages with the data operated through RESTful services

Page 12: Consuming RESTful Web services in PHP

12

AJAX

• Enable asynchronous communication between a web client and a server.

• A client is not blocked when an asynchronous request is sent to a server. It assigns an event handler to intercept the response instead.

• The technology is not limited to XML encoded data.

Page 13: Consuming RESTful Web services in PHP

13

AJAX

Page 14: Consuming RESTful Web services in PHP

14

AJAX: Building a Request (4 steps)

• Step 1: Creating a XML HTTP Request object var xmlhttp = new XMLHttpRequest();

• Step 2: Specifying where and how to retrieve the resource xmlhttp.open('GET', 'foo.php', true);

• Step 3: Setting a function to be called when the response is returned by

the server xmlhttp.onreadystatechange = function() { // Code to handle the response here }

• Step 4: Send the request

xmlhttp.send(null); - string argument used for POST

• Note: Between step 2 and 3, the order is not important.

Page 15: Consuming RESTful Web services in PHP

15

CONSUMING REST FROM PHP WITH CURL

Page 16: Consuming RESTful Web services in PHP

16

What is libcurl?

• libcurl is a free and easy-to-use client-side URL transfer library, supporting FTP, FTPS, TFTP, HTTP, HTTPS, TELNET, DICT, FILE and LDAP. libcurl supports SSL certificates, HTTP POST, HTTP PUT, FTP uploading, HTTP form based upload, proxies, cookies, user+password authentication (Basic, Digest, NTLM, Negotiate, Kerberos4), file transfer resume, http proxy tunneling and more!

Page 17: Consuming RESTful Web services in PHP

17

What is PHP/CURL Binding?

• PHP/CURL is a binding that uses libcurl. It means that the PHP team has written a glue layer for PHP that speaks to the underlying libcurl. That layer, the binding, is what we call PHP/CURL and that is what offers the functions named curl_* within the PHP language for you. The PHP/CURL binding is written, maintained and being provided by the PHP team.

Page 18: Consuming RESTful Web services in PHP

18

Installing the PHP/CURL binding in Window

• Activation of PHP/CURL on windows : removing a semicolon from the following line in php.ini: ;extension=php_curl.dll

• In order to enable SSL-based protocols (such as HTTPS and FTPS) in your Windows environment : copy libeay32.dll and ssleay32.dll from the DLL folder of the PHP/ binary package to the SYSTEM folder of your Windows machine. (Ex: C:\WINNT\SYSTEM32 or C:\WINDOWS\SYSTEM).

Page 19: Consuming RESTful Web services in PHP

19

How to use the CURL functions ?

1. initialize a CURL session using the curl_init() 2. set all options for the transfer via the curl_setopt() 3. execute the session with the curl_exec() 4. finish off your session using the curl_close()

Page 20: Consuming RESTful Web services in PHP

20

Simple example

Filling Out Forms <form method="post" action="form_processing_page.php"> <input type="text" name="name" /> <input type="text" name="color" /> </form> Processing form

$name = $_POST[‘name']; $color = $_POST[‘color'];

Page 21: Consuming RESTful Web services in PHP

21

Simple example

// specify the URL to request $url = 'http://www.example.com/form.php'; // set up data to send to the form $data = array('name' => $name, 'color' => $color); // create cURL session $ch = curl_init(); // set the URL curl_setopt($ch, CURLOPT_URL, $url); // return the response instead of printing curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // set request method to POST curl_setopt($ch, CURLOPT_POST, true); // set the data to send curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // send the request and store the response in $resp $resp= curl_exec($ch); // end the session curl_close($ch); ?>

Page 22: Consuming RESTful Web services in PHP

22

PHP and JSON

json_encode() <?php $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5); echo json_encode($arr); ?> output : {"a":1,"b":2,"c":3,"d":4,"e":5}

Page 23: Consuming RESTful Web services in PHP

23

PHP and JSON

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; var_dump(json_decode($json)); var_dump(json_decode($json, true)); Output: object(stdClass)#1 (5) { ["a"] => int(1) ["b"] => int(2) ["c"] => int(3) ["d"] => int(4) ["e"] => int(5) } array(5) { ["a"] => int(1) ["b"] => int(2) ["c"] => int(3) ["d"] => int(4) ["e"] => int(5) }

Page 24: Consuming RESTful Web services in PHP

24

CONSUMING REST WITH AJAX AND JQUERY

Page 25: Consuming RESTful Web services in PHP

25

Loading data from the service

• JSON is the data format of choice – JavaScript Object Notation

• Use the XMLHTTPRequest object – jQuery makes this very easy

• jQuery.ajax() – Perform an asynchronous HTTP (Ajax) request – Uses an options object that configure the Ajax request

• jQuery.getJSON() – Load JSON data using an asynchronous HTTP GET request

Page 26: Consuming RESTful Web services in PHP

26

jQuery Client - $.ajax()

function findById(id) { $.ajax({ type: 'GET', url: rootURL + '/' + id, dataType: "json", success: function(data){ $('#btnDelete').show(); renderDetails(data); } }); }

Page 27: Consuming RESTful Web services in PHP

27

jQuery client - getJSON()

$.getJSON( url, [data], [callback], [type] ) • url: (String) The URL of the page to load. • data (Optional): (Map) Key/value pairs that will be sent to the server. • callback (Optional): (Function) A function to be executed whenever the data is

loaded successfully. • type (Optional): (String) Type of data to be returned to callback function: “xml”, “html”,

“script”, “json”, “jsonp”, or “text”. $.getJSON( "http://some-remote-site", "{key:value}", function(data) { alert(data); }, “json"); $.getJSON( "http://some-remote-site", function(data) { alert(data); }, );

Page 28: Consuming RESTful Web services in PHP

28

CLIENT APPLICATION FOR LISTING AND COMMENTING MOVIES

Lab

Page 29: Consuming RESTful Web services in PHP

29

Lab: Client application for listing and commenting movies

• Create client application that uses RESTful web service to get list of all movies and present it as a list (movie title and release date).

• User can add comment for each movie • User can see additional information about each movie (its genre and

comments added by other users.

Page 30: Consuming RESTful Web services in PHP

30

Lab:RESTful services of web application “movieweb”

• RESTful Web services providing data for client application • List all movies

– GET http://localhost:8080/moviesweb/rest/movies

• Adding new comment – POST http://localhost:8080/moviesweb/rest/comments

• List additional data about each movie and users’ comments – GET http://localhost:8080/moviesweb/rest/movies/movieid

Page 31: Consuming RESTful Web services in PHP

31

Lab: List all movies

Page 32: Consuming RESTful Web services in PHP

32

Displaying movies list

Page 33: Consuming RESTful Web services in PHP

33

cURL get client

Page 34: Consuming RESTful Web services in PHP

34

Lab: Adding a new comment

Page 35: Consuming RESTful Web services in PHP

35

Adding jQuery and jQuery UI libraries

Page 36: Consuming RESTful Web services in PHP

36

Create modal dialog

Page 37: Consuming RESTful Web services in PHP

37

Form for adding comments

Page 38: Consuming RESTful Web services in PHP

38

Processing form

Page 39: Consuming RESTful Web services in PHP

39

cURL post client

Page 40: Consuming RESTful Web services in PHP

40

Lab: List additional data about each movie and users’ comments

Page 41: Consuming RESTful Web services in PHP

41

Get more data and present it in the list

Page 42: Consuming RESTful Web services in PHP

42

REAL WORLD EXAMPLE DEPTHS (Design Patterns Teaching Help System)

More info and demo http://learningdesignpatterns.org

Page 43: Consuming RESTful Web services in PHP

43

Personal Learning Environment - DEPTHS

• Provides users with personal learning environment for project-based collaborative learning

• Semantic Web • Integration of data from different and heterogeneous sources, tools and

services. – Moodle LMS, ArgoUML, Facebook, Twitter

• Educational services for recommendation of relevant peers. • Modeling the semantics of one’s presence in the online world.

43

Page 44: Consuming RESTful Web services in PHP

44

Scenario of use

44

Page 45: Consuming RESTful Web services in PHP

45

System Architecture

45

Page 46: Consuming RESTful Web services in PHP

46

Educational services in OP4L

• Context-aware learning services – Semantic annotation and indexing service – Web resource finding – Discovery of relevant internally produced resources – Experts, teachers and peers recommendation

46

Page 47: Consuming RESTful Web services in PHP

47 47

Page 48: Consuming RESTful Web services in PHP

48

Consuming RESTful Web Services in PHP

Zoran Jeremić, PhD [email protected]