SlideShare una empresa de Scribd logo
1 de 61
Descargar para leer sin conexión
Working with
Web Services
Who am I?

•   Lorna Mitchell
•   PHP Specialist
•   Developer, Writer, Consultant, Trainer
•   Personal site at lornajane.net
•   Twitter: @lornajane
•   PHPNW, PHPWomen


                                             2
Working with Web Services

•   Consuming existing services
•   Web services overview
•   Data types
•   Service types
•   Debugging
•   Using services from PHP


                                  3
What are Web Services?

• Machine-friendly applications
• Formatted data instead of a web page




                                         4
Why Do We Care?

• Web services let us exchange data
  – between systems
  – within systems
• Architecture looks like library or
  module boundary
• Sharing information between systems
  cleanly


                                        5
How do Web Services Work?

• Client/Server
• Sound familiar?
• Request and response, just like a web
  application
• Same theories apply




                                          6
When Things Go Wrong

• Errors will appear in response
• We may not expect them
• Apache logs
• Debug output and logging
• Verbose error-checking and logging
  from our app
• Graceful failure

                                       7
Data Formats




               8
JSON

•   JavaScript Object Notation
•   Natively read/write in most languages
•   Very simple! (we like simple)
•   Limitations
    – no data typing
    – no distinction between object and array



                                                9
Writing JSON from PHP
   1   <?php
   2
   3   $menu['starter'] = array( "prawn cocktail",
   4                             "soup of the day");
   5   $menu['main course'] = array( "roast chicken",
   6                                 "fish 'n' chips",
   7                                 "macaroni cheese");
   8   $menu['pudding'] = array( "cheesecake",
   9                             "treacle sponge");
  10
  11   echo json_encode($menu);



{"starter":["prawn cocktail","soup of the day"],"main 
course":["roast chicken","fish 'n' chips","macaroni 
cheese"],"pudding":["cheesecake","treacle sponge"]}
                                                           10
Reading JSON from PHP
    1 <?php
    2
    3 $json = '{"starter":["prawn cocktail","soup of the
day"],"main course":["roast chicken","fish 'n'
chips","macaroni cheese"],"pudding":["cheesecake","treacle
sponge"]}';
    4
    5 print_r(json_decode($json));




                                                             11
Reading JSON from PHP
stdClass Object
(
    [starter] => Array
        (
            [0] => prawn cocktail
            [1] => soup of the day
        )

    [main course] => Array
        (
            [0] => roast chicken
            [1] => fish 'n' chips
            [2] => macaroni cheese
        )

    [pudding] => Array
        (
            [0] => cheesecake
            [1] => treacle sponge
        )
                                     12
)
XML

•   eXtensible Markup Language
•   Familiar
•   Can give more detail than JSON
•   Native read/write in most languages




                                          13
Working with XML from PHP

• Lots of options
• SimpleXML
• DOM




                            14
SimpleXML Example
  1   <?php
  2
  3   $xml = <<< XML
  4   <?xml version="1.0" ?>
  5   <menus>
  6        <menu>Lunch</menu>
  7        <menu>Dinner</menu>
  8        <menu>Dessert</menu>
  9        <menu>Drinks</menu>
 10   </menus>
 11   XML;
 12
 13   $simplexml = new SimpleXMLElement($xml);
 14   var_dump($simplexml);



                                                 15
SimpleXML Example
object(SimpleXMLElement)#1 (1) {
  ["menu"]=>
  array(5) {
    [0]=>
    string(5) "Lunch"
    [1]=>
    string(6) "Dinner"
    [2]=>
    string(7) "Dessert"
    [3]=>
    string(6) "Drinks"
  }
}




                                   16
SimpleXML Example
    1 <?php
    2
    3 $simplexml = simplexml_load_string('<?xml
version="1.0" ?><menus/>');
    4 $simplexml->addChild('menu','Lunch');
    5 $simplexml->addChild('menu','Dinner');
    6 $simplexml->addChild('menu','Drinks');
    7 $simplexml->addChild('menu','Dessert');
    8
    9 echo $simplexml->asXML();




                                                  17
SimpleXML Example
<?xml version="1.0"?>
<menus>
    <menu>Lunch</menu>
    <menu>Dinner</menu>
    <menu>Dessert</menu>
    <menu>Drinks</menu>
</menus>




                           18
Serialised PHP

• Native to PHP
• Useful for values in database
• Can also use to move data between
  PHP applications




                                      19
Serialising Data in PHP
   1   <?php
   2
   3   $menu['starter'] = array( "prawn cocktail",
   4                             "soup of the day");
   5   $menu['main course'] = array( "roast chicken",
   6                                 "fish 'n' chips",
   7                                 "macaroni cheese");
   8   $menu['pudding'] = array( "cheesecake",
   9                             "treacle sponge");
  10
  11   echo serialize($menu);

a:3:{s:7:"starter";a:2:{i:0;s:14:"prawn
cocktail";i:1;s:15:"soup of the day";}s:11:"main
course";a:3:{i:0;s:13:"roast chicken";i:1;s:14:"fish'n'
chips";i:2;s:15:"macaroni cheese";}s:7:"pudding";a:2:
{i:0;s:10:"cheesecake";i:1;s:14:"treacle sponge";}}
                                                           20
Unserialising Data in PHP
    1 <?php
    2
    3 $serialised = 'a:3:{s:7:"starter";a:2:{i:0;s:14:"prawn
cocktail";i:1;s:15:"soup of the day";}s:11:"main
course";a:3:{i:0;s:13:"roast chicken";i:1;s:14:"fish 'n'
chips";i:2;s:15:"macaroni cheese";}s:7:"pudding";a:2:
{i:0;s:10:"cheesecake";i:1;s:14:"treacle sponge";}}';
    4
    5 var_dump(unserialize($serialised));




                                                          21
Unserialising Data in PHP
array(3) {
  ["starter"]=>
  array(2) {
    [0]=>
    string(14) "prawn cocktail"
    [1]=>
    string(15) "soup of the day"
  }
  ["main course"]=>
  array(3) {
    [0]=>
    string(13) "roast chicken"
    [1]=>
    string(14) "fish 'n' chips"
    [2]=>
    string(15) "macaroni cheese"
  }
  ["pudding"]=>
  array(2) {
    [0]=>
    string(10) "cheesecake"
    [1]=>
    string(14) "treacle sponge"
  }                                22
}
Service Types
Service Types

• SOAP
• *-RPC
  – XML-RPC
  – JSON-RPC
• REST




                24
SOAP

•   Just "soap"
•   Defined XML format
•   Also includes definition for error format
•   Wrappers available for most languages
•   Optionally uses a WSDL to describe the
    service
    – Web Service Description Language


                                            25
Example WSDL
<?xml version ='1.0' encoding ='UTF-8' ?>
  <definitions name='MyClass'     targetNamespace='urn:MyClassInventory'      xmlns:tns='urn:MyClassInventory'    xmlns:soap='http://schemas.xmlsoap.org/wsdl/soap/'   xmlns:xsd='
http://www.w3.org/2001/XMLSchema'        xmlns:soapenc='http://schemas.xmlsoap.org/soap/encoding/'       xmlns:wsdl='http://schemas.xmlsoap.org/wsdl/'
xmlns='http://schemas.xmlsoap.org/wsdl/'>
  <message name='getAccountStatusRequest'>
   <part name='accountID' type='xsd:string'/>
  </message>
  <message name='getAccountStatusResponse'>
   <part name='accountID' type='xsd:string'/>
   <part name='counter' type='xsd:float' />
  </message>
  <portType name='MyClassPortType'>
   <operation name='getAccountStatus'>
     <input message='tns:getAccountStatusRequest'/>
     <output message='tns:getAccountStatusResponse'/>
   </operation>
  </portType>
  <binding name='MyClassBinding' type='tns:MyClassPortType'>
   <soap:binding style='rpc'
     transport='http://schemas.xmlsoap.org/soap/http'/>
   <operation name='getAccountStatus'>
     <soap:operation soapAction='urn:xmethods-delayed-quotes#getAccountStatus'/>
     <input>
       <soap:body use='encoded' namespace='urn:xmethods-delayed-quotes'             encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'/>
     </input>
     <output>
       <soap:body use='encoded' namespace='urn:xmethods-delayed-quotes'
        encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'/>
     </output>
   </operation>
  </binding>
  <service name='MyClassService'>
   <port name='MyClassPort' binding='tns:MyClassBinding'>
     <soap:address location='http://rivendell.local:10002/MyClassServiceServer.php'/>
   </port>
  </service>
  </definitions>




                                                                                                                                                                                 26
WSDL tips

• Read from end to beginning
  1.Service location and name
  2.Method names and bindings
  3.Details of request/response messages
  4.Variable names and data types used for
    each request/response
  5.Data type definitions
  6.Namespace information

                                             27
PHP SOAP Client Example
  1   <?php
  2
  3   ini_set('soap.wsdl_cache_enabled','0');
  4
  5   require_once('lib/Snapshot.php');
  6
  7   $wsdl = "Service.wsdl";
  8   $client = new SoapClient($wsdl, $params);
  9
 10   $output = $client->requestShot(
 11       'http://www.php.net','', 300, 400);




                                                  28
Troubleshooting SOAP

• Check request
  – $client->getLastRequest()
• Check request headers
  – $client->getLastRequestHeaders()
• Check WSDL
• Data types can be an issue between
  different client/server languages

                                       29
HTTP Debugging Tools

• cURL
  – http://curl.haxx.se/
• Wireshark
  – http://www.wireshark.org/
• Charles
  – http://www.charlesproxy.com/



                                   30
cURL

•   cURL is a command-line tool
•   Simple but powerful
•   Specify HTTP verb
•   Observe full request/response headers
•   Handle cookies




                                       31
cURL Cheat Sheet

•   curl http://localhost
•   -v to show request/response
•   -I to show response headers
•   -X to specify HTTP method
•   -d to add a data field
•   -c to store cookies in a cookiejar
•   -b to use a cookiejar with request

                                         32
Wireshark Examples




                     33
Wireshark Examples




                     34
Wireshark Examples




                     35
Wireshark Examples




                     36
RPC Services

• Remote Procedure Call
• Similar to library
• Call function with arguments




                                 37
Example RPC services

• Using Flickr's XML-RPC
• Test method: just echoes back to user
• XML formatted data




                                      38
Flickr Echo Example: XML
<?xml version="1.0"?>
<methodCall>
  <methodName>flickr.test.echo</methodName>
  <params>
    <param>
      <value>
        <struct>
           <member>
             <name>api_key</name>
             <value>....</value>
           </member>
        </struct>
      </value>
    </param>
  </params>
</methodCall>

                                              39
RPC from PHP: curl
  1   <?php
  2
  3   // $xml is existing SimpleXMLElement Object
  4   $url = 'http://api.flickr.com/services/xmlrpc/';
  5   $ch = curl_init($url);
  6
  7   curl_setopt($ch, CURLOPT_POST, 1);
  8   curl_setopt($ch, CURLOPT_POSTFIELDS, $xml->asXML());
  9
 10   $response = curl_exec($ch);
 11   curl_close($ch);




                                                             40
RPC from PHP: pecl_http
  1   <?php
  2
  3   $url = 'http://api.flickr.com/services/xmlrpc/';
  4
  5   // procedural method
  6   $response = http_post_data($url, $xml->asXML());
  7
  8   // alternative method
  9   $request = new HTTPRequest($url, HTTP_METH_POST);
 10   $request->setRawPostData($xml->asXML());
 11   $request->send();
 12   $response = $request->getResponseBody();
 13
 14   var_dump($response);



                                                          41
Flickr Response
<?xml version="1.0" encoding="utf-8" ?>
<methodResponse>
  <params>
    <param>
      <value>
        <string>&lt;api_key&gt;54rt346&lt;/api_key&gt;
        </string>
      </value>
    </param>
  </params>
</methodResponse>




                                                         42
Wrapping RPC

• RPC is a library-like interface
• Can easily wrap existing libraries to
  call like this
• Can wrap an interface to an RPC
  service to look like a library




                                          43
Wrapping RPC Example
  1   <?php
  2
  3   class Handler
  4   {
  5    function __call($method, $args) {
  6       $ch = curl_init('http://localhost');
  7       $data['method'] = $method;
  8       foreach($args as $a) $data[$a] = $a;
  9
 10       curl_setopt($ch, CURLOPT_POST,1);
 11       curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
 12       $response = curl_exec($ch); curl_close($ch);
 13
 14       var_dump($response);
 15    }
 16   }
 17   $h = new Handler();
 18   $h->dance('cat','dog','rabbit','penguin');         44
 19
Troubleshooting RPC

• Break down into smallest steps
• Can you get a response from the
  service?
• Can you log in?
• Is there an error?
• Try to debug the details of the
  request/response

                                    45
REST

• REpresentational State Transfer
• Not a protocol
• More like a philosophy




                                    46
REST Overview

• A series of concepts
• Generally uses HTTP (HyperText
  Transfer Protocol)
• URLs are resource locations
• Verbs tell the service what to do
• Status codes indicate what the
  outcome was

                                      47
HTTP Status Codes

    Code      Meaning
    200       OK
    302       Found
    301       Moved
    401       Not Authorised
    403       Forbidden
    404       Not Found
    500       Internal Server Error
                                      48
REST CRUD

       Action     HTTP Verb


       Retrieve   GET

       Create     POST

       Update     PUT

       Delete     DELETE



                              49
REST Examples

• GET
  – http://localhost/users
  – http://localhost/users/harry
• POST
  – http://localhost/users
• PUT
  – http://localhost/users/harry
• DELETE
  – http://localhost/users/harry
                                   50
REST from PHP: GET
  1 <?php
  2
  3 $result = file_get_contents('http://localhost/users');
  4 var_dump($result);




                                                        51
REST from PHP: GET
  1 <?php
  2
  3 $ch = curl_init('http://localhost/users');
  4
  5 curl_exec($ch);


• Health Warning!
  – curl will echo output
  – use CURLOPT_RETURNTRANSFER to
    capture it instead


                                                 52
REST from PHP: POST
  1   <?php
  2
  3   $ch = curl_init('http://localhost/users');
  4
  5   $data = array ("name" => "Cho Chang",
  6               "house" => "Ravenclaw");
  7
  8   curl_setopt($ch, CURLOPT_POST, 1);
  9   curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
 10
 11   curl_exec($ch);




                                                     53
REST from PHP: DELETE
  1   <?php
  2
  3   $ch = curl_init('http://localhost/users/ginny');
  4
  5   curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
  6
  7   curl_exec($ch);




                                                           54
REST from PHP: PUT
  1   <?php
  2
  3   $ch = curl_init('http://localhost/users/cho');
  4
  5   $data = array ("name" => "Cho Chang",
  6               "house" => "Ravenclaw"
  7               "age" => 15);
  8
  9   curl_setopt($handle, CURLOPT_CUSTOMREQUEST, 'PUT');
 10   curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
 11
 12   curl_exec($ch);
 13




                                                            55
Troubleshooting REST

• Does resource exist?
• Is there a status code?
• What does the response body look
  like?
• Intercept web traffic
• Use command line curl



                                     56
Working with Web Services
Working with Web Services

•   Consuming existing services
•   Web services overview
•   Data types
•   Service types
•   Debugging
•   Using services from PHP


                                  58
Top tips

• If your app can't talk to the service,
  can you get closer to the service?
• If you control both server and client,
  add debug output
• Use proxies to record what happens
• Start with the lowest common
  denominator and work up


                                           59
Questions?
Thankyou!

   Twitter: @lornajane
Website: http://lornajane.net

Más contenido relacionado

La actualidad más candente

Introducere in web
Introducere in webIntroducere in web
Introducere in webAlex Eftimie
 
RestMQ - HTTP/Redis based Message Queue
RestMQ - HTTP/Redis based Message QueueRestMQ - HTTP/Redis based Message Queue
RestMQ - HTTP/Redis based Message QueueGleicon Moraes
 
"The little big project. From zero to hero in two weeks with 3 front-end engi...
"The little big project. From zero to hero in two weeks with 3 front-end engi..."The little big project. From zero to hero in two weeks with 3 front-end engi...
"The little big project. From zero to hero in two weeks with 3 front-end engi...Fwdays
 
PHP BASIC PRESENTATION
PHP BASIC PRESENTATIONPHP BASIC PRESENTATION
PHP BASIC PRESENTATIONkrutitrivedi
 
神に近づくx/net/context (Finding God with x/net/context)
神に近づくx/net/context (Finding God with x/net/context)神に近づくx/net/context (Finding God with x/net/context)
神に近づくx/net/context (Finding God with x/net/context)guregu
 
Using ngx_lua in UPYUN
Using ngx_lua in UPYUNUsing ngx_lua in UPYUN
Using ngx_lua in UPYUNCong Zhang
 
Umleitung: a tiny mochiweb/CouchDB app
Umleitung: a tiny mochiweb/CouchDB appUmleitung: a tiny mochiweb/CouchDB app
Umleitung: a tiny mochiweb/CouchDB appLenz Gschwendtner
 
Creating And Consuming Web Services In Php 5
Creating And Consuming Web Services In Php 5Creating And Consuming Web Services In Php 5
Creating And Consuming Web Services In Php 5Michael Girouard
 
Roll Your Own API Management Platform with nginx and Lua
Roll Your Own API Management Platform with nginx and LuaRoll Your Own API Management Platform with nginx and Lua
Roll Your Own API Management Platform with nginx and LuaJon Moore
 
Oracle database - Get external data via HTTP, FTP and Web Services
Oracle database - Get external data via HTTP, FTP and Web ServicesOracle database - Get external data via HTTP, FTP and Web Services
Oracle database - Get external data via HTTP, FTP and Web ServicesKim Berg Hansen
 
PHP - PDO Objects
PHP - PDO ObjectsPHP - PDO Objects
PHP - PDO ObjectsAJINKYA N
 
Consuming RESTful services in PHP
Consuming RESTful services in PHPConsuming RESTful services in PHP
Consuming RESTful services in PHPZoran Jeremic
 
PHP, RabbitMQ, and You
PHP, RabbitMQ, and YouPHP, RabbitMQ, and You
PHP, RabbitMQ, and YouJason Lotito
 
A new way to develop with WordPress!
A new way to develop with WordPress!A new way to develop with WordPress!
A new way to develop with WordPress!David Sanchez
 
The state of your own hypertext preprocessor
The state of your own hypertext preprocessorThe state of your own hypertext preprocessor
The state of your own hypertext preprocessorAlessandro Nadalin
 
Lua tech talk
Lua tech talkLua tech talk
Lua tech talkLocaweb
 

La actualidad más candente (20)

Introducere in web
Introducere in webIntroducere in web
Introducere in web
 
PHP7 Presentation
PHP7 PresentationPHP7 Presentation
PHP7 Presentation
 
RestMQ - HTTP/Redis based Message Queue
RestMQ - HTTP/Redis based Message QueueRestMQ - HTTP/Redis based Message Queue
RestMQ - HTTP/Redis based Message Queue
 
"The little big project. From zero to hero in two weeks with 3 front-end engi...
"The little big project. From zero to hero in two weeks with 3 front-end engi..."The little big project. From zero to hero in two weeks with 3 front-end engi...
"The little big project. From zero to hero in two weeks with 3 front-end engi...
 
PHP BASIC PRESENTATION
PHP BASIC PRESENTATIONPHP BASIC PRESENTATION
PHP BASIC PRESENTATION
 
Psr 7 symfony-day
Psr 7 symfony-dayPsr 7 symfony-day
Psr 7 symfony-day
 
神に近づくx/net/context (Finding God with x/net/context)
神に近づくx/net/context (Finding God with x/net/context)神に近づくx/net/context (Finding God with x/net/context)
神に近づくx/net/context (Finding God with x/net/context)
 
Using ngx_lua in UPYUN
Using ngx_lua in UPYUNUsing ngx_lua in UPYUN
Using ngx_lua in UPYUN
 
Umleitung: a tiny mochiweb/CouchDB app
Umleitung: a tiny mochiweb/CouchDB appUmleitung: a tiny mochiweb/CouchDB app
Umleitung: a tiny mochiweb/CouchDB app
 
Creating And Consuming Web Services In Php 5
Creating And Consuming Web Services In Php 5Creating And Consuming Web Services In Php 5
Creating And Consuming Web Services In Php 5
 
Roll Your Own API Management Platform with nginx and Lua
Roll Your Own API Management Platform with nginx and LuaRoll Your Own API Management Platform with nginx and Lua
Roll Your Own API Management Platform with nginx and Lua
 
Fatc
FatcFatc
Fatc
 
Oracle database - Get external data via HTTP, FTP and Web Services
Oracle database - Get external data via HTTP, FTP and Web ServicesOracle database - Get external data via HTTP, FTP and Web Services
Oracle database - Get external data via HTTP, FTP and Web Services
 
PHP - PDO Objects
PHP - PDO ObjectsPHP - PDO Objects
PHP - PDO Objects
 
Consuming RESTful services in PHP
Consuming RESTful services in PHPConsuming RESTful services in PHP
Consuming RESTful services in PHP
 
PHP, RabbitMQ, and You
PHP, RabbitMQ, and YouPHP, RabbitMQ, and You
PHP, RabbitMQ, and You
 
A new way to develop with WordPress!
A new way to develop with WordPress!A new way to develop with WordPress!
A new way to develop with WordPress!
 
The state of your own hypertext preprocessor
The state of your own hypertext preprocessorThe state of your own hypertext preprocessor
The state of your own hypertext preprocessor
 
Lua tech talk
Lua tech talkLua tech talk
Lua tech talk
 
Ip lab
Ip labIp lab
Ip lab
 

Similar a Working with web_services

Building and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsBuilding and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsOhad Kravchick
 
Facebook的缓存系统
Facebook的缓存系统Facebook的缓存系统
Facebook的缓存系统yiditushe
 
4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebookguoqing75
 
Dirty Secrets of the PHP SOAP Extension
Dirty Secrets of the PHP SOAP ExtensionDirty Secrets of the PHP SOAP Extension
Dirty Secrets of the PHP SOAP ExtensionAdam Trachtenberg
 
Consuming RESTful Web services in PHP
Consuming RESTful Web services in PHPConsuming RESTful Web services in PHP
Consuming RESTful Web services in PHPZoran Jeremic
 
Intravert Server side processing for Cassandra
Intravert Server side processing for CassandraIntravert Server side processing for Cassandra
Intravert Server side processing for CassandraEdward Capriolo
 
NYC* 2013 - "Advanced Data Processing: Beyond Queries and Slices"
NYC* 2013 - "Advanced Data Processing: Beyond Queries and Slices"NYC* 2013 - "Advanced Data Processing: Beyond Queries and Slices"
NYC* 2013 - "Advanced Data Processing: Beyond Queries and Slices"DataStax Academy
 
HackU PHP and Node.js
HackU PHP and Node.jsHackU PHP and Node.js
HackU PHP and Node.jssouridatta
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applicationselliando dias
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHPprabhatjon
 
анатолий шарифулин Mojolicious финальная версия
анатолий шарифулин Mojolicious   финальная версияанатолий шарифулин Mojolicious   финальная версия
анатолий шарифулин Mojolicious финальная версияrit2010
 
анатолий шарифулин Mojolicious
анатолий шарифулин Mojoliciousанатолий шарифулин Mojolicious
анатолий шарифулин Mojoliciousrit2010
 

Similar a Working with web_services (20)

Building and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsBuilding and Scaling Node.js Applications
Building and Scaling Node.js Applications
 
Facebook的缓存系统
Facebook的缓存系统Facebook的缓存系统
Facebook的缓存系统
 
4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook
 
Dirty Secrets of the PHP SOAP Extension
Dirty Secrets of the PHP SOAP ExtensionDirty Secrets of the PHP SOAP Extension
Dirty Secrets of the PHP SOAP Extension
 
Consuming RESTful Web services in PHP
Consuming RESTful Web services in PHPConsuming RESTful Web services in PHP
Consuming RESTful Web services in PHP
 
Intravert Server side processing for Cassandra
Intravert Server side processing for CassandraIntravert Server side processing for Cassandra
Intravert Server side processing for Cassandra
 
NYC* 2013 - "Advanced Data Processing: Beyond Queries and Slices"
NYC* 2013 - "Advanced Data Processing: Beyond Queries and Slices"NYC* 2013 - "Advanced Data Processing: Beyond Queries and Slices"
NYC* 2013 - "Advanced Data Processing: Beyond Queries and Slices"
 
Php hacku
Php hackuPhp hacku
Php hacku
 
Os Pruett
Os PruettOs Pruett
Os Pruett
 
Php summary
Php summaryPhp summary
Php summary
 
HackU PHP and Node.js
HackU PHP and Node.jsHackU PHP and Node.js
HackU PHP and Node.js
 
Php101
Php101Php101
Php101
 
Phphacku iitd
Phphacku iitdPhphacku iitd
Phphacku iitd
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applications
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
 
анатолий шарифулин Mojolicious финальная версия
анатолий шарифулин Mojolicious   финальная версияанатолий шарифулин Mojolicious   финальная версия
анатолий шарифулин Mojolicious финальная версия
 
анатолий шарифулин Mojolicious
анатолий шарифулин Mojoliciousанатолий шарифулин Mojolicious
анатолий шарифулин Mojolicious
 
PHP for hacks
PHP for hacksPHP for hacks
PHP for hacks
 
Php Mysql
Php Mysql Php Mysql
Php Mysql
 
REST API for your WP7 App
REST API for your WP7 AppREST API for your WP7 App
REST API for your WP7 App
 

Más de Lorna Mitchell

Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP TutorialLorna Mitchell
 
Best Practice in API Design
Best Practice in API DesignBest Practice in API Design
Best Practice in API DesignLorna Mitchell
 
Git, GitHub and Open Source
Git, GitHub and Open SourceGit, GitHub and Open Source
Git, GitHub and Open SourceLorna Mitchell
 
Business 101 for Developers: Time and Money
Business 101 for Developers: Time and MoneyBusiness 101 for Developers: Time and Money
Business 101 for Developers: Time and MoneyLorna Mitchell
 
Things I wish web graduates knew
Things I wish web graduates knewThings I wish web graduates knew
Things I wish web graduates knewLorna Mitchell
 
Teach a Man To Fish (phpconpl edition)
Teach a Man To Fish (phpconpl edition)Teach a Man To Fish (phpconpl edition)
Teach a Man To Fish (phpconpl edition)Lorna Mitchell
 
Tool Up Your LAMP Stack
Tool Up Your LAMP StackTool Up Your LAMP Stack
Tool Up Your LAMP StackLorna Mitchell
 
Understanding Distributed Source Control
Understanding Distributed Source ControlUnderstanding Distributed Source Control
Understanding Distributed Source ControlLorna Mitchell
 
Best Practice in Web Service Design
Best Practice in Web Service DesignBest Practice in Web Service Design
Best Practice in Web Service DesignLorna Mitchell
 
Coaching Development Teams: Teach A Man To Fish
Coaching Development Teams: Teach A Man To FishCoaching Development Teams: Teach A Man To Fish
Coaching Development Teams: Teach A Man To FishLorna Mitchell
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation TutorialLorna Mitchell
 
Implementing OAuth with PHP
Implementing OAuth with PHPImplementing OAuth with PHP
Implementing OAuth with PHPLorna Mitchell
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHPLorna Mitchell
 
Could You Telecommute?
Could You Telecommute?Could You Telecommute?
Could You Telecommute?Lorna Mitchell
 

Más de Lorna Mitchell (20)

OAuth: Trust Issues
OAuth: Trust IssuesOAuth: Trust Issues
OAuth: Trust Issues
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP Tutorial
 
Best Practice in API Design
Best Practice in API DesignBest Practice in API Design
Best Practice in API Design
 
Git, GitHub and Open Source
Git, GitHub and Open SourceGit, GitHub and Open Source
Git, GitHub and Open Source
 
Business 101 for Developers: Time and Money
Business 101 for Developers: Time and MoneyBusiness 101 for Developers: Time and Money
Business 101 for Developers: Time and Money
 
Things I wish web graduates knew
Things I wish web graduates knewThings I wish web graduates knew
Things I wish web graduates knew
 
Teach a Man To Fish (phpconpl edition)
Teach a Man To Fish (phpconpl edition)Teach a Man To Fish (phpconpl edition)
Teach a Man To Fish (phpconpl edition)
 
Join In With Joind.In
Join In With Joind.InJoin In With Joind.In
Join In With Joind.In
 
Tool Up Your LAMP Stack
Tool Up Your LAMP StackTool Up Your LAMP Stack
Tool Up Your LAMP Stack
 
Going Freelance
Going FreelanceGoing Freelance
Going Freelance
 
Understanding Distributed Source Control
Understanding Distributed Source ControlUnderstanding Distributed Source Control
Understanding Distributed Source Control
 
Best Practice in Web Service Design
Best Practice in Web Service DesignBest Practice in Web Service Design
Best Practice in Web Service Design
 
Coaching Development Teams: Teach A Man To Fish
Coaching Development Teams: Teach A Man To FishCoaching Development Teams: Teach A Man To Fish
Coaching Development Teams: Teach A Man To Fish
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation Tutorial
 
Implementing OAuth with PHP
Implementing OAuth with PHPImplementing OAuth with PHP
Implementing OAuth with PHP
 
Web Services Tutorial
Web Services TutorialWeb Services Tutorial
Web Services Tutorial
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHP
 
Example Presentation
Example PresentationExample Presentation
Example Presentation
 
Could You Telecommute?
Could You Telecommute?Could You Telecommute?
Could You Telecommute?
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 

Working with web_services

  • 2. Who am I? • Lorna Mitchell • PHP Specialist • Developer, Writer, Consultant, Trainer • Personal site at lornajane.net • Twitter: @lornajane • PHPNW, PHPWomen 2
  • 3. Working with Web Services • Consuming existing services • Web services overview • Data types • Service types • Debugging • Using services from PHP 3
  • 4. What are Web Services? • Machine-friendly applications • Formatted data instead of a web page 4
  • 5. Why Do We Care? • Web services let us exchange data – between systems – within systems • Architecture looks like library or module boundary • Sharing information between systems cleanly 5
  • 6. How do Web Services Work? • Client/Server • Sound familiar? • Request and response, just like a web application • Same theories apply 6
  • 7. When Things Go Wrong • Errors will appear in response • We may not expect them • Apache logs • Debug output and logging • Verbose error-checking and logging from our app • Graceful failure 7
  • 9. JSON • JavaScript Object Notation • Natively read/write in most languages • Very simple! (we like simple) • Limitations – no data typing – no distinction between object and array 9
  • 10. Writing JSON from PHP 1 <?php 2 3 $menu['starter'] = array( "prawn cocktail", 4 "soup of the day"); 5 $menu['main course'] = array( "roast chicken", 6 "fish 'n' chips", 7 "macaroni cheese"); 8 $menu['pudding'] = array( "cheesecake", 9 "treacle sponge"); 10 11 echo json_encode($menu); {"starter":["prawn cocktail","soup of the day"],"main  course":["roast chicken","fish 'n' chips","macaroni  cheese"],"pudding":["cheesecake","treacle sponge"]} 10
  • 11. Reading JSON from PHP 1 <?php 2 3 $json = '{"starter":["prawn cocktail","soup of the day"],"main course":["roast chicken","fish 'n' chips","macaroni cheese"],"pudding":["cheesecake","treacle sponge"]}'; 4 5 print_r(json_decode($json)); 11
  • 12. Reading JSON from PHP stdClass Object ( [starter] => Array ( [0] => prawn cocktail [1] => soup of the day ) [main course] => Array ( [0] => roast chicken [1] => fish 'n' chips [2] => macaroni cheese ) [pudding] => Array ( [0] => cheesecake [1] => treacle sponge ) 12 )
  • 13. XML • eXtensible Markup Language • Familiar • Can give more detail than JSON • Native read/write in most languages 13
  • 14. Working with XML from PHP • Lots of options • SimpleXML • DOM 14
  • 15. SimpleXML Example 1 <?php 2 3 $xml = <<< XML 4 <?xml version="1.0" ?> 5 <menus> 6 <menu>Lunch</menu> 7 <menu>Dinner</menu> 8 <menu>Dessert</menu> 9 <menu>Drinks</menu> 10 </menus> 11 XML; 12 13 $simplexml = new SimpleXMLElement($xml); 14 var_dump($simplexml); 15
  • 16. SimpleXML Example object(SimpleXMLElement)#1 (1) { ["menu"]=> array(5) { [0]=> string(5) "Lunch" [1]=> string(6) "Dinner" [2]=> string(7) "Dessert" [3]=> string(6) "Drinks" } } 16
  • 17. SimpleXML Example 1 <?php 2 3 $simplexml = simplexml_load_string('<?xml version="1.0" ?><menus/>'); 4 $simplexml->addChild('menu','Lunch'); 5 $simplexml->addChild('menu','Dinner'); 6 $simplexml->addChild('menu','Drinks'); 7 $simplexml->addChild('menu','Dessert'); 8 9 echo $simplexml->asXML(); 17
  • 18. SimpleXML Example <?xml version="1.0"?> <menus> <menu>Lunch</menu> <menu>Dinner</menu> <menu>Dessert</menu> <menu>Drinks</menu> </menus> 18
  • 19. Serialised PHP • Native to PHP • Useful for values in database • Can also use to move data between PHP applications 19
  • 20. Serialising Data in PHP 1 <?php 2 3 $menu['starter'] = array( "prawn cocktail", 4 "soup of the day"); 5 $menu['main course'] = array( "roast chicken", 6 "fish 'n' chips", 7 "macaroni cheese"); 8 $menu['pudding'] = array( "cheesecake", 9 "treacle sponge"); 10 11 echo serialize($menu); a:3:{s:7:"starter";a:2:{i:0;s:14:"prawn cocktail";i:1;s:15:"soup of the day";}s:11:"main course";a:3:{i:0;s:13:"roast chicken";i:1;s:14:"fish'n' chips";i:2;s:15:"macaroni cheese";}s:7:"pudding";a:2: {i:0;s:10:"cheesecake";i:1;s:14:"treacle sponge";}} 20
  • 21. Unserialising Data in PHP 1 <?php 2 3 $serialised = 'a:3:{s:7:"starter";a:2:{i:0;s:14:"prawn cocktail";i:1;s:15:"soup of the day";}s:11:"main course";a:3:{i:0;s:13:"roast chicken";i:1;s:14:"fish 'n' chips";i:2;s:15:"macaroni cheese";}s:7:"pudding";a:2: {i:0;s:10:"cheesecake";i:1;s:14:"treacle sponge";}}'; 4 5 var_dump(unserialize($serialised)); 21
  • 22. Unserialising Data in PHP array(3) { ["starter"]=> array(2) { [0]=> string(14) "prawn cocktail" [1]=> string(15) "soup of the day" } ["main course"]=> array(3) { [0]=> string(13) "roast chicken" [1]=> string(14) "fish 'n' chips" [2]=> string(15) "macaroni cheese" } ["pudding"]=> array(2) { [0]=> string(10) "cheesecake" [1]=> string(14) "treacle sponge" } 22 }
  • 24. Service Types • SOAP • *-RPC – XML-RPC – JSON-RPC • REST 24
  • 25. SOAP • Just "soap" • Defined XML format • Also includes definition for error format • Wrappers available for most languages • Optionally uses a WSDL to describe the service – Web Service Description Language 25
  • 26. Example WSDL <?xml version ='1.0' encoding ='UTF-8' ?> <definitions name='MyClass' targetNamespace='urn:MyClassInventory' xmlns:tns='urn:MyClassInventory' xmlns:soap='http://schemas.xmlsoap.org/wsdl/soap/' xmlns:xsd=' http://www.w3.org/2001/XMLSchema' xmlns:soapenc='http://schemas.xmlsoap.org/soap/encoding/' xmlns:wsdl='http://schemas.xmlsoap.org/wsdl/' xmlns='http://schemas.xmlsoap.org/wsdl/'> <message name='getAccountStatusRequest'> <part name='accountID' type='xsd:string'/> </message> <message name='getAccountStatusResponse'> <part name='accountID' type='xsd:string'/> <part name='counter' type='xsd:float' /> </message> <portType name='MyClassPortType'> <operation name='getAccountStatus'> <input message='tns:getAccountStatusRequest'/> <output message='tns:getAccountStatusResponse'/> </operation> </portType> <binding name='MyClassBinding' type='tns:MyClassPortType'> <soap:binding style='rpc' transport='http://schemas.xmlsoap.org/soap/http'/> <operation name='getAccountStatus'> <soap:operation soapAction='urn:xmethods-delayed-quotes#getAccountStatus'/> <input> <soap:body use='encoded' namespace='urn:xmethods-delayed-quotes' encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'/> </input> <output> <soap:body use='encoded' namespace='urn:xmethods-delayed-quotes' encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'/> </output> </operation> </binding> <service name='MyClassService'> <port name='MyClassPort' binding='tns:MyClassBinding'> <soap:address location='http://rivendell.local:10002/MyClassServiceServer.php'/> </port> </service> </definitions> 26
  • 27. WSDL tips • Read from end to beginning 1.Service location and name 2.Method names and bindings 3.Details of request/response messages 4.Variable names and data types used for each request/response 5.Data type definitions 6.Namespace information 27
  • 28. PHP SOAP Client Example 1 <?php 2 3 ini_set('soap.wsdl_cache_enabled','0'); 4 5 require_once('lib/Snapshot.php'); 6 7 $wsdl = "Service.wsdl"; 8 $client = new SoapClient($wsdl, $params); 9 10 $output = $client->requestShot( 11 'http://www.php.net','', 300, 400); 28
  • 29. Troubleshooting SOAP • Check request – $client->getLastRequest() • Check request headers – $client->getLastRequestHeaders() • Check WSDL • Data types can be an issue between different client/server languages 29
  • 30. HTTP Debugging Tools • cURL – http://curl.haxx.se/ • Wireshark – http://www.wireshark.org/ • Charles – http://www.charlesproxy.com/ 30
  • 31. cURL • cURL is a command-line tool • Simple but powerful • Specify HTTP verb • Observe full request/response headers • Handle cookies 31
  • 32. cURL Cheat Sheet • curl http://localhost • -v to show request/response • -I to show response headers • -X to specify HTTP method • -d to add a data field • -c to store cookies in a cookiejar • -b to use a cookiejar with request 32
  • 37. RPC Services • Remote Procedure Call • Similar to library • Call function with arguments 37
  • 38. Example RPC services • Using Flickr's XML-RPC • Test method: just echoes back to user • XML formatted data 38
  • 39. Flickr Echo Example: XML <?xml version="1.0"?> <methodCall> <methodName>flickr.test.echo</methodName> <params> <param> <value> <struct> <member> <name>api_key</name> <value>....</value> </member> </struct> </value> </param> </params> </methodCall> 39
  • 40. RPC from PHP: curl 1 <?php 2 3 // $xml is existing SimpleXMLElement Object 4 $url = 'http://api.flickr.com/services/xmlrpc/'; 5 $ch = curl_init($url); 6 7 curl_setopt($ch, CURLOPT_POST, 1); 8 curl_setopt($ch, CURLOPT_POSTFIELDS, $xml->asXML()); 9 10 $response = curl_exec($ch); 11 curl_close($ch); 40
  • 41. RPC from PHP: pecl_http 1 <?php 2 3 $url = 'http://api.flickr.com/services/xmlrpc/'; 4 5 // procedural method 6 $response = http_post_data($url, $xml->asXML()); 7 8 // alternative method 9 $request = new HTTPRequest($url, HTTP_METH_POST); 10 $request->setRawPostData($xml->asXML()); 11 $request->send(); 12 $response = $request->getResponseBody(); 13 14 var_dump($response); 41
  • 42. Flickr Response <?xml version="1.0" encoding="utf-8" ?> <methodResponse> <params> <param> <value> <string>&lt;api_key&gt;54rt346&lt;/api_key&gt; </string> </value> </param> </params> </methodResponse> 42
  • 43. Wrapping RPC • RPC is a library-like interface • Can easily wrap existing libraries to call like this • Can wrap an interface to an RPC service to look like a library 43
  • 44. Wrapping RPC Example 1 <?php 2 3 class Handler 4 { 5 function __call($method, $args) { 6 $ch = curl_init('http://localhost'); 7 $data['method'] = $method; 8 foreach($args as $a) $data[$a] = $a; 9 10 curl_setopt($ch, CURLOPT_POST,1); 11 curl_setopt($ch, CURLOPT_POSTFIELDS, $data); 12 $response = curl_exec($ch); curl_close($ch); 13 14 var_dump($response); 15 } 16 } 17 $h = new Handler(); 18 $h->dance('cat','dog','rabbit','penguin'); 44 19
  • 45. Troubleshooting RPC • Break down into smallest steps • Can you get a response from the service? • Can you log in? • Is there an error? • Try to debug the details of the request/response 45
  • 46. REST • REpresentational State Transfer • Not a protocol • More like a philosophy 46
  • 47. REST Overview • A series of concepts • Generally uses HTTP (HyperText Transfer Protocol) • URLs are resource locations • Verbs tell the service what to do • Status codes indicate what the outcome was 47
  • 48. HTTP Status Codes Code Meaning 200 OK 302 Found 301 Moved 401 Not Authorised 403 Forbidden 404 Not Found 500 Internal Server Error 48
  • 49. REST CRUD Action HTTP Verb Retrieve GET Create POST Update PUT Delete DELETE 49
  • 50. REST Examples • GET – http://localhost/users – http://localhost/users/harry • POST – http://localhost/users • PUT – http://localhost/users/harry • DELETE – http://localhost/users/harry 50
  • 51. REST from PHP: GET 1 <?php 2 3 $result = file_get_contents('http://localhost/users'); 4 var_dump($result); 51
  • 52. REST from PHP: GET 1 <?php 2 3 $ch = curl_init('http://localhost/users'); 4 5 curl_exec($ch); • Health Warning! – curl will echo output – use CURLOPT_RETURNTRANSFER to capture it instead 52
  • 53. REST from PHP: POST 1 <?php 2 3 $ch = curl_init('http://localhost/users'); 4 5 $data = array ("name" => "Cho Chang", 6 "house" => "Ravenclaw"); 7 8 curl_setopt($ch, CURLOPT_POST, 1); 9 curl_setopt($ch, CURLOPT_POSTFIELDS, $data); 10 11 curl_exec($ch); 53
  • 54. REST from PHP: DELETE 1 <?php 2 3 $ch = curl_init('http://localhost/users/ginny'); 4 5 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE'); 6 7 curl_exec($ch); 54
  • 55. REST from PHP: PUT 1 <?php 2 3 $ch = curl_init('http://localhost/users/cho'); 4 5 $data = array ("name" => "Cho Chang", 6 "house" => "Ravenclaw" 7 "age" => 15); 8 9 curl_setopt($handle, CURLOPT_CUSTOMREQUEST, 'PUT'); 10 curl_setopt($ch, CURLOPT_POSTFIELDS, $data); 11 12 curl_exec($ch); 13 55
  • 56. Troubleshooting REST • Does resource exist? • Is there a status code? • What does the response body look like? • Intercept web traffic • Use command line curl 56
  • 57. Working with Web Services
  • 58. Working with Web Services • Consuming existing services • Web services overview • Data types • Service types • Debugging • Using services from PHP 58
  • 59. Top tips • If your app can't talk to the service, can you get closer to the service? • If you control both server and client, add debug output • Use proxies to record what happens • Start with the lowest common denominator and work up 59
  • 61. Thankyou! Twitter: @lornajane Website: http://lornajane.net