SlideShare una empresa de Scribd logo
1 de 48
Descargar para leer sin conexión
Consuming RESTful Web Services
           in PHP

                            Zoran Jeremić, PhD
                     zoran.jeremic@gmail.com

                                                 1
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




                                                                2
REST = "Representation State Transfer"




        WebApp

                                           Cache
                                         (Resource)




       Dispatcher




                                                      3
Key REST principles



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




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




                                                                      5
TECHNICAL SOLUTION
TECHNOLOGIES


                     6
HTTP
Overview



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




                                                                                    7
HTTP
Request methods




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




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




                                                                                         9
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
}


                                                      10
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




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




                                                                             12
AJAX




       13
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.
                                                                               14
CONSUMING REST FROM PHP
WITH CURL

                          15
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!




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




                                                                              17
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:WINNTSYSTEM32 or
    C:WINDOWSSYSTEM).




                                                                             18
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()




                                              19
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'];




                                                         20
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);
?>
                                                                           21
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}




                                                                  22
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)
}
                                             23
CONSUMING REST WITH AJAX
AND JQUERY

                           24
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




                                                                25
jQuery Client - $.ajax()



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




                                   26
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); },
);


                                                                                               27
Lab

CLIENT APPLICATION FOR LISTING
AND COMMENTING MOVIES


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




                                                                                 29
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




                                                                 30
Lab: List all movies




                       31
Displaying movies list




                         32
cURL get client




                  33
Lab: Adding a new comment




                            34
Adding jQuery and jQuery UI libraries




                                        35
Create modal dialog




                      36
Form for adding comments




                           37
Processing form




                  38
cURL post client




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




                                                                 40
Get more data and present it in the list




                                           41
DEPTHS (Design Patterns Teaching Help System)

REAL WORLD EXAMPLE
                                More info and demo
                                http://learningdesignpatterns.org

                                                                    42
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
                                                                              43
Scenario of use




                  44
                       44
System Architecture




                      45
                           45
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
                                                                    46
47
     47
Consuming RESTful Web Services
           in PHP

                            Zoran Jeremić, PhD
                     zoran.jeremic@gmail.com

                                                 48

Más contenido relacionado

La actualidad más candente

Webservice for android ppt
Webservice for android pptWebservice for android ppt
Webservice for android pptsantosh lamba
 
PHP And Web Services: Perfect Partners
PHP And Web Services: Perfect PartnersPHP And Web Services: Perfect Partners
PHP And Web Services: Perfect PartnersLorna Mitchell
 
Restful web services with java
Restful web services with javaRestful web services with java
Restful web services with javaVinay Gopinath
 
RESTful Web Services with JAX-RS
RESTful Web Services with JAX-RSRESTful Web Services with JAX-RS
RESTful Web Services with JAX-RSCarol McDonald
 
Using Java to implement RESTful Web Services: JAX-RS
Using Java to implement RESTful Web Services: JAX-RSUsing Java to implement RESTful Web Services: JAX-RS
Using Java to implement RESTful Web Services: JAX-RSKatrien Verbert
 
Introduction to RESTful Webservices in JAVA
Introduction to RESTful Webservices  in JAVA Introduction to RESTful Webservices  in JAVA
Introduction to RESTful Webservices in JAVA psrpatnaik
 
Cwinters Intro To Rest And JerREST and Jersey Introductionsey
Cwinters Intro To Rest And JerREST and Jersey IntroductionseyCwinters Intro To Rest And JerREST and Jersey Introductionsey
Cwinters Intro To Rest And JerREST and Jersey Introductionseyelliando dias
 
RestFull Webservices with JAX-RS
RestFull Webservices with JAX-RSRestFull Webservices with JAX-RS
RestFull Webservices with JAX-RSNeil Ghosh
 
Best Practice in API Design
Best Practice in API DesignBest Practice in API Design
Best Practice in API DesignLorna Mitchell
 
JSON-RPC - JSON Remote Procedure Call
JSON-RPC - JSON Remote Procedure CallJSON-RPC - JSON Remote Procedure Call
JSON-RPC - JSON Remote Procedure CallPeter R. Egli
 
Making Java REST with JAX-RS 2.0
Making Java REST with JAX-RS 2.0Making Java REST with JAX-RS 2.0
Making Java REST with JAX-RS 2.0Dmytro Chyzhykov
 
REST & RESTful Web Service
REST & RESTful Web ServiceREST & RESTful Web Service
REST & RESTful Web ServiceHoan Vu Tran
 
Building Restful Applications Using Php
Building Restful Applications Using PhpBuilding Restful Applications Using Php
Building Restful Applications Using PhpSudheer Satyanarayana
 
Designing a RESTful web service
Designing a RESTful web serviceDesigning a RESTful web service
Designing a RESTful web serviceFilip Blondeel
 
Json-based Service Oriented Architecture for the web
Json-based Service Oriented Architecture for the webJson-based Service Oriented Architecture for the web
Json-based Service Oriented Architecture for the webkriszyp
 

La actualidad más candente (20)

Webservice for android ppt
Webservice for android pptWebservice for android ppt
Webservice for android ppt
 
Develop webservice in PHP
Develop webservice in PHPDevelop webservice in PHP
Develop webservice in PHP
 
PHP And Web Services: Perfect Partners
PHP And Web Services: Perfect PartnersPHP And Web Services: Perfect Partners
PHP And Web Services: Perfect Partners
 
Restful web services with java
Restful web services with javaRestful web services with java
Restful web services with java
 
RESTful Web Services
RESTful Web ServicesRESTful Web Services
RESTful Web Services
 
RESTful Web Services with JAX-RS
RESTful Web Services with JAX-RSRESTful Web Services with JAX-RS
RESTful Web Services with JAX-RS
 
Using Java to implement RESTful Web Services: JAX-RS
Using Java to implement RESTful Web Services: JAX-RSUsing Java to implement RESTful Web Services: JAX-RS
Using Java to implement RESTful Web Services: JAX-RS
 
ASP.NET WEB API
ASP.NET WEB APIASP.NET WEB API
ASP.NET WEB API
 
Introduction to RESTful Webservices in JAVA
Introduction to RESTful Webservices  in JAVA Introduction to RESTful Webservices  in JAVA
Introduction to RESTful Webservices in JAVA
 
Excellent rest using asp.net web api
Excellent rest using asp.net web apiExcellent rest using asp.net web api
Excellent rest using asp.net web api
 
Cwinters Intro To Rest And JerREST and Jersey Introductionsey
Cwinters Intro To Rest And JerREST and Jersey IntroductionseyCwinters Intro To Rest And JerREST and Jersey Introductionsey
Cwinters Intro To Rest And JerREST and Jersey Introductionsey
 
RestFull Webservices with JAX-RS
RestFull Webservices with JAX-RSRestFull Webservices with JAX-RS
RestFull Webservices with JAX-RS
 
Best Practice in API Design
Best Practice in API DesignBest Practice in API Design
Best Practice in API Design
 
JSON-RPC - JSON Remote Procedure Call
JSON-RPC - JSON Remote Procedure CallJSON-RPC - JSON Remote Procedure Call
JSON-RPC - JSON Remote Procedure Call
 
Making Java REST with JAX-RS 2.0
Making Java REST with JAX-RS 2.0Making Java REST with JAX-RS 2.0
Making Java REST with JAX-RS 2.0
 
REST & RESTful Web Service
REST & RESTful Web ServiceREST & RESTful Web Service
REST & RESTful Web Service
 
Building Restful Applications Using Php
Building Restful Applications Using PhpBuilding Restful Applications Using Php
Building Restful Applications Using Php
 
Designing a RESTful web service
Designing a RESTful web serviceDesigning a RESTful web service
Designing a RESTful web service
 
Web Services Tutorial
Web Services TutorialWeb Services Tutorial
Web Services Tutorial
 
Json-based Service Oriented Architecture for the web
Json-based Service Oriented Architecture for the webJson-based Service Oriented Architecture for the web
Json-based Service Oriented Architecture for the web
 

Destacado

jQuery Mobile, Backbone.js, and ASP.NET MVC
jQuery Mobile, Backbone.js, and ASP.NET MVCjQuery Mobile, Backbone.js, and ASP.NET MVC
jQuery Mobile, Backbone.js, and ASP.NET MVCTroy Miles
 
Introduction to Mobile Game Programming with Cocos2d-JS
Introduction to Mobile Game Programming with Cocos2d-JSIntroduction to Mobile Game Programming with Cocos2d-JS
Introduction to Mobile Game Programming with Cocos2d-JSTroy Miles
 
What's this jQuery? Where it came from, and how it will drive innovation
What's this jQuery? Where it came from, and how it will drive innovationWhat's this jQuery? Where it came from, and how it will drive innovation
What's this jQuery? Where it came from, and how it will drive innovationMarakana Inc.
 
Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Troy Miles
 
jQuery Mobile Jump Start
jQuery Mobile Jump StartjQuery Mobile Jump Start
jQuery Mobile Jump StartTroy Miles
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP TutorialLorna Mitchell
 
PHP and Web Services
PHP and Web ServicesPHP and Web Services
PHP and Web ServicesBruno Pedro
 

Destacado (7)

jQuery Mobile, Backbone.js, and ASP.NET MVC
jQuery Mobile, Backbone.js, and ASP.NET MVCjQuery Mobile, Backbone.js, and ASP.NET MVC
jQuery Mobile, Backbone.js, and ASP.NET MVC
 
Introduction to Mobile Game Programming with Cocos2d-JS
Introduction to Mobile Game Programming with Cocos2d-JSIntroduction to Mobile Game Programming with Cocos2d-JS
Introduction to Mobile Game Programming with Cocos2d-JS
 
What's this jQuery? Where it came from, and how it will drive innovation
What's this jQuery? Where it came from, and how it will drive innovationWhat's this jQuery? Where it came from, and how it will drive innovation
What's this jQuery? Where it came from, and how it will drive innovation
 
Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1
 
jQuery Mobile Jump Start
jQuery Mobile Jump StartjQuery Mobile Jump Start
jQuery Mobile Jump Start
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP Tutorial
 
PHP and Web Services
PHP and Web ServicesPHP and Web Services
PHP and Web Services
 

Similar a Consuming RESTful Web services in PHP

ASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiTiago Knoch
 
JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011Shreedhar Ganapathy
 
API Testing. Streamline your testing process.
API Testing. Streamline your testing process.API Testing. Streamline your testing process.
API Testing. Streamline your testing process.Andrey Oleynik
 
Arabidopsis Information Portal, Developer Workshop 2014, Introduction
Arabidopsis Information Portal, Developer Workshop 2014, IntroductionArabidopsis Information Portal, Developer Workshop 2014, Introduction
Arabidopsis Information Portal, Developer Workshop 2014, IntroductionJasonRafeMiller
 
JSON based CSRF
JSON based CSRFJSON based CSRF
JSON based CSRFAmit Dubey
 
Fully Automate Application Delivery with Puppet and F5 - PuppetConf 2014
Fully Automate Application Delivery with Puppet and F5 - PuppetConf 2014Fully Automate Application Delivery with Puppet and F5 - PuppetConf 2014
Fully Automate Application Delivery with Puppet and F5 - PuppetConf 2014Puppet
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.pptWalaSidhom1
 
Big Data and Machine Learning with FIWARE
Big Data and Machine Learning with FIWAREBig Data and Machine Learning with FIWARE
Big Data and Machine Learning with FIWAREFernando Lopez Aguilar
 
WEB TECHNOLOGY Unit-5.pptx
WEB TECHNOLOGY Unit-5.pptxWEB TECHNOLOGY Unit-5.pptx
WEB TECHNOLOGY Unit-5.pptxkarthiksmart21
 
Restful webservices
Restful webservicesRestful webservices
Restful webservicesKong King
 
Web Service and Mobile Integrated Day I
Web Service and Mobile Integrated Day IWeb Service and Mobile Integrated Day I
Web Service and Mobile Integrated Day IAnuchit Chalothorn
 
Designing RESTful APIs
Designing RESTful APIsDesigning RESTful APIs
Designing RESTful APIsanandology
 
Networked APIs with swift
Networked APIs with swiftNetworked APIs with swift
Networked APIs with swiftTim Burks
 
RESTful web service with JBoss Fuse
RESTful web service with JBoss FuseRESTful web service with JBoss Fuse
RESTful web service with JBoss Fuseejlp12
 
Synapseindia dot net development web applications with ajax
Synapseindia dot net development  web applications with ajaxSynapseindia dot net development  web applications with ajax
Synapseindia dot net development web applications with ajaxSynapseindiappsdevelopment
 
Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsRest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsCarol McDonald
 

Similar a Consuming RESTful Web services in PHP (20)

ASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiASP.NET Mvc 4 web api
ASP.NET Mvc 4 web api
 
JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011
 
API Testing. Streamline your testing process.
API Testing. Streamline your testing process.API Testing. Streamline your testing process.
API Testing. Streamline your testing process.
 
Arabidopsis Information Portal, Developer Workshop 2014, Introduction
Arabidopsis Information Portal, Developer Workshop 2014, IntroductionArabidopsis Information Portal, Developer Workshop 2014, Introduction
Arabidopsis Information Portal, Developer Workshop 2014, Introduction
 
JSON based CSRF
JSON based CSRFJSON based CSRF
JSON based CSRF
 
Fully Automate Application Delivery with Puppet and F5 - PuppetConf 2014
Fully Automate Application Delivery with Puppet and F5 - PuppetConf 2014Fully Automate Application Delivery with Puppet and F5 - PuppetConf 2014
Fully Automate Application Delivery with Puppet and F5 - PuppetConf 2014
 
Switch to Backend 2023
Switch to Backend 2023Switch to Backend 2023
Switch to Backend 2023
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
 
Big Data and Machine Learning with FIWARE
Big Data and Machine Learning with FIWAREBig Data and Machine Learning with FIWARE
Big Data and Machine Learning with FIWARE
 
Jones "Working with Scholarly APIs: A NISO Training Series, Session One: Foun...
Jones "Working with Scholarly APIs: A NISO Training Series, Session One: Foun...Jones "Working with Scholarly APIs: A NISO Training Series, Session One: Foun...
Jones "Working with Scholarly APIs: A NISO Training Series, Session One: Foun...
 
WEB TECHNOLOGY Unit-5.pptx
WEB TECHNOLOGY Unit-5.pptxWEB TECHNOLOGY Unit-5.pptx
WEB TECHNOLOGY Unit-5.pptx
 
Restful webservices
Restful webservicesRestful webservices
Restful webservices
 
Web Service and Mobile Integrated Day I
Web Service and Mobile Integrated Day IWeb Service and Mobile Integrated Day I
Web Service and Mobile Integrated Day I
 
Designing RESTful APIs
Designing RESTful APIsDesigning RESTful APIs
Designing RESTful APIs
 
Networked APIs with swift
Networked APIs with swiftNetworked APIs with swift
Networked APIs with swift
 
Ajax
AjaxAjax
Ajax
 
RESTful web service with JBoss Fuse
RESTful web service with JBoss FuseRESTful web service with JBoss Fuse
RESTful web service with JBoss Fuse
 
Synapseindia dot net development web applications with ajax
Synapseindia dot net development  web applications with ajaxSynapseindia dot net development  web applications with ajax
Synapseindia dot net development web applications with ajax
 
Rest
RestRest
Rest
 
Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsRest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.js
 

Más de Zoran Jeremic

T 4 testiranje softvera i upravljanje kvalitetom
 T 4 testiranje softvera i upravljanje kvalitetom T 4 testiranje softvera i upravljanje kvalitetom
T 4 testiranje softvera i upravljanje kvalitetomZoran Jeremic
 
T 3.8 design paterni (c)
 T 3.8 design paterni (c) T 3.8 design paterni (c)
T 3.8 design paterni (c)Zoran Jeremic
 
T 3.7 modelovanje ponasanja koriscenjem dijagrama aktivnosti
 T 3.7 modelovanje ponasanja koriscenjem dijagrama aktivnosti T 3.7 modelovanje ponasanja koriscenjem dijagrama aktivnosti
T 3.7 modelovanje ponasanja koriscenjem dijagrama aktivnostiZoran Jeremic
 
T 3.6 design paterni (b)
 T 3.6 design paterni (b) T 3.6 design paterni (b)
T 3.6 design paterni (b)Zoran Jeremic
 
T 3.5 modelovanje stanja koriscenjem uml statechart dijagrama
 T 3.5 modelovanje stanja koriscenjem uml statechart dijagrama T 3.5 modelovanje stanja koriscenjem uml statechart dijagrama
T 3.5 modelovanje stanja koriscenjem uml statechart dijagramaZoran Jeremic
 
T 3.4 modelovanje ponasanja koriscenjem uml dijagrama interakcija
 T 3.4 modelovanje ponasanja koriscenjem uml dijagrama interakcija T 3.4 modelovanje ponasanja koriscenjem uml dijagrama interakcija
T 3.4 modelovanje ponasanja koriscenjem uml dijagrama interakcijaZoran Jeremic
 
T 3.3 design paterni (a)
 T 3.3 design paterni (a) T 3.3 design paterni (a)
T 3.3 design paterni (a)Zoran Jeremic
 
T 3.2 definisanje strukture sistema koriscenjem uml dijagrama klasa
 T 3.2 definisanje strukture sistema koriscenjem uml dijagrama klasa T 3.2 definisanje strukture sistema koriscenjem uml dijagrama klasa
T 3.2 definisanje strukture sistema koriscenjem uml dijagrama klasaZoran Jeremic
 
T 3.1 definisanje zahteva koriscenjem use case dijagrama
 T 3.1 definisanje zahteva koriscenjem use case dijagrama T 3.1 definisanje zahteva koriscenjem use case dijagrama
T 3.1 definisanje zahteva koriscenjem use case dijagramaZoran Jeremic
 
T 3 uvod u modelovanje koriscenjem uml-a
 T 3 uvod u modelovanje koriscenjem uml-a T 3 uvod u modelovanje koriscenjem uml-a
T 3 uvod u modelovanje koriscenjem uml-aZoran Jeremic
 
T 2 zivotni ciklus i metodologije razvoja softvera
 T 2 zivotni ciklus i metodologije razvoja softvera T 2 zivotni ciklus i metodologije razvoja softvera
T 2 zivotni ciklus i metodologije razvoja softveraZoran Jeremic
 
T 1 uvod u softversko inzenjerstvo
 T 1 uvod u softversko inzenjerstvo T 1 uvod u softversko inzenjerstvo
T 1 uvod u softversko inzenjerstvoZoran Jeremic
 
Synergy of Performance-Based Model and Cognitive Trait Model in DP-ITS
Synergy of Performance-Based Model and Cognitive Trait Model in DP-ITSSynergy of Performance-Based Model and Cognitive Trait Model in DP-ITS
Synergy of Performance-Based Model and Cognitive Trait Model in DP-ITSZoran Jeremic
 
A Semantic-rich Framework for Learning Software Patterns
A Semantic-rich Framework for Learning Software PatternsA Semantic-rich Framework for Learning Software Patterns
A Semantic-rich Framework for Learning Software PatternsZoran Jeremic
 
Project-based Collaborative Learning Environment with Context-aware Education...
Project-based Collaborative Learning Environment with Context-aware Education...Project-based Collaborative Learning Environment with Context-aware Education...
Project-based Collaborative Learning Environment with Context-aware Education...Zoran Jeremic
 
Semantically-enabled Project-based Collaborative Learning of Software Patterns
Semantically-enabled Project-based Collaborative Learning of Software PatternsSemantically-enabled Project-based Collaborative Learning of Software Patterns
Semantically-enabled Project-based Collaborative Learning of Software PatternsZoran Jeremic
 
A Semantic-rich Framework for Learning Software Patterns
A Semantic-rich Framework for Learning Software PatternsA Semantic-rich Framework for Learning Software Patterns
A Semantic-rich Framework for Learning Software PatternsZoran Jeremic
 
Project-based Collaborative Learning of Software Patterns
Project-based Collaborative Learning of Software PatternsProject-based Collaborative Learning of Software Patterns
Project-based Collaborative Learning of Software PatternsZoran Jeremic
 
A Semantic-rich Framework for Learning Software Patterns
A Semantic-rich Framework for Learning Software PatternsA Semantic-rich Framework for Learning Software Patterns
A Semantic-rich Framework for Learning Software PatternsZoran Jeremic
 

Más de Zoran Jeremic (20)

T 4 testiranje softvera i upravljanje kvalitetom
 T 4 testiranje softvera i upravljanje kvalitetom T 4 testiranje softvera i upravljanje kvalitetom
T 4 testiranje softvera i upravljanje kvalitetom
 
T 3.8 design paterni (c)
 T 3.8 design paterni (c) T 3.8 design paterni (c)
T 3.8 design paterni (c)
 
T 3.7 modelovanje ponasanja koriscenjem dijagrama aktivnosti
 T 3.7 modelovanje ponasanja koriscenjem dijagrama aktivnosti T 3.7 modelovanje ponasanja koriscenjem dijagrama aktivnosti
T 3.7 modelovanje ponasanja koriscenjem dijagrama aktivnosti
 
T 3.6 design paterni (b)
 T 3.6 design paterni (b) T 3.6 design paterni (b)
T 3.6 design paterni (b)
 
T 3.5 modelovanje stanja koriscenjem uml statechart dijagrama
 T 3.5 modelovanje stanja koriscenjem uml statechart dijagrama T 3.5 modelovanje stanja koriscenjem uml statechart dijagrama
T 3.5 modelovanje stanja koriscenjem uml statechart dijagrama
 
T 3.4 modelovanje ponasanja koriscenjem uml dijagrama interakcija
 T 3.4 modelovanje ponasanja koriscenjem uml dijagrama interakcija T 3.4 modelovanje ponasanja koriscenjem uml dijagrama interakcija
T 3.4 modelovanje ponasanja koriscenjem uml dijagrama interakcija
 
T 3.3 design paterni (a)
 T 3.3 design paterni (a) T 3.3 design paterni (a)
T 3.3 design paterni (a)
 
T 3.2 definisanje strukture sistema koriscenjem uml dijagrama klasa
 T 3.2 definisanje strukture sistema koriscenjem uml dijagrama klasa T 3.2 definisanje strukture sistema koriscenjem uml dijagrama klasa
T 3.2 definisanje strukture sistema koriscenjem uml dijagrama klasa
 
T 3.1 definisanje zahteva koriscenjem use case dijagrama
 T 3.1 definisanje zahteva koriscenjem use case dijagrama T 3.1 definisanje zahteva koriscenjem use case dijagrama
T 3.1 definisanje zahteva koriscenjem use case dijagrama
 
T 3 uvod u modelovanje koriscenjem uml-a
 T 3 uvod u modelovanje koriscenjem uml-a T 3 uvod u modelovanje koriscenjem uml-a
T 3 uvod u modelovanje koriscenjem uml-a
 
T 2 zivotni ciklus i metodologije razvoja softvera
 T 2 zivotni ciklus i metodologije razvoja softvera T 2 zivotni ciklus i metodologije razvoja softvera
T 2 zivotni ciklus i metodologije razvoja softvera
 
T 1 uvod u softversko inzenjerstvo
 T 1 uvod u softversko inzenjerstvo T 1 uvod u softversko inzenjerstvo
T 1 uvod u softversko inzenjerstvo
 
PhD Dissertation
PhD DissertationPhD Dissertation
PhD Dissertation
 
Synergy of Performance-Based Model and Cognitive Trait Model in DP-ITS
Synergy of Performance-Based Model and Cognitive Trait Model in DP-ITSSynergy of Performance-Based Model and Cognitive Trait Model in DP-ITS
Synergy of Performance-Based Model and Cognitive Trait Model in DP-ITS
 
A Semantic-rich Framework for Learning Software Patterns
A Semantic-rich Framework for Learning Software PatternsA Semantic-rich Framework for Learning Software Patterns
A Semantic-rich Framework for Learning Software Patterns
 
Project-based Collaborative Learning Environment with Context-aware Education...
Project-based Collaborative Learning Environment with Context-aware Education...Project-based Collaborative Learning Environment with Context-aware Education...
Project-based Collaborative Learning Environment with Context-aware Education...
 
Semantically-enabled Project-based Collaborative Learning of Software Patterns
Semantically-enabled Project-based Collaborative Learning of Software PatternsSemantically-enabled Project-based Collaborative Learning of Software Patterns
Semantically-enabled Project-based Collaborative Learning of Software Patterns
 
A Semantic-rich Framework for Learning Software Patterns
A Semantic-rich Framework for Learning Software PatternsA Semantic-rich Framework for Learning Software Patterns
A Semantic-rich Framework for Learning Software Patterns
 
Project-based Collaborative Learning of Software Patterns
Project-based Collaborative Learning of Software PatternsProject-based Collaborative Learning of Software Patterns
Project-based Collaborative Learning of Software Patterns
 
A Semantic-rich Framework for Learning Software Patterns
A Semantic-rich Framework for Learning Software PatternsA Semantic-rich Framework for Learning Software Patterns
A Semantic-rich Framework for Learning Software Patterns
 

Último

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 

Último (20)

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 

Consuming RESTful Web services in PHP

  • 1. Consuming RESTful Web Services in PHP Zoran Jeremić, PhD zoran.jeremic@gmail.com 1
  • 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 2
  • 3. REST = "Representation State Transfer" WebApp Cache (Resource) Dispatcher 3
  • 4. Key REST principles • Give every “thing” an ID • Link things together • Use standard methods • Resources with multiple representations • Communicate statelessly 4
  • 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). 5
  • 7. HTTP Overview • 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. 7
  • 8. HTTP Request methods • 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. 8
  • 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) 9
  • 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 } 10
  • 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 11
  • 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. 12
  • 13. AJAX 13
  • 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. 14
  • 15. CONSUMING REST FROM PHP WITH CURL 15
  • 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! 16
  • 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. 17
  • 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:WINNTSYSTEM32 or C:WINDOWSSYSTEM). 18
  • 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() 19
  • 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']; 20
  • 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); ?> 21
  • 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} 22
  • 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) } 23
  • 24. CONSUMING REST WITH AJAX AND JQUERY 24
  • 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 25
  • 26. jQuery Client - $.ajax() function findById(id) { $.ajax({ type: 'GET', url: rootURL + '/' + id, dataType: "json", success: function(data){ $('#btnDelete').show(); renderDetails(data); } }); } 26
  • 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); }, ); 27
  • 28. Lab CLIENT APPLICATION FOR LISTING AND COMMENTING MOVIES 28
  • 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. 29
  • 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 30
  • 31. Lab: List all movies 31
  • 34. Lab: Adding a new comment 34
  • 35. Adding jQuery and jQuery UI libraries 35
  • 37. Form for adding comments 37
  • 40. Lab: List additional data about each movie and users’ comments 40
  • 41. Get more data and present it in the list 41
  • 42. DEPTHS (Design Patterns Teaching Help System) REAL WORLD EXAMPLE More info and demo http://learningdesignpatterns.org 42
  • 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 43
  • 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 46
  • 47. 47 47
  • 48. Consuming RESTful Web Services in PHP Zoran Jeremić, PhD zoran.jeremic@gmail.com 48