Using curl and PHP to talk to a REST service
Monday, September 15. 2008
Having recently written articles about curl and about writing a PHP REST server, I thought I'd complete the circle and put here a few notes on using PHP's curl wrapper as a Rest client. Also I had to look some of this up when I needed to actually do it so next time I need only look in one place!
If you don't know about PHP, Rest, or curl, then I recommend you do a little reading around each of those subjects before reading this as its unlikely to make much sense - I'm not including background on these topics as there are better resources elsewhere.
I've written about using curl before from the command line, but this example uses PHP's curl to access the service. This is just a simple example, but hopefully if you are doing something along these lines you can adapt for your needs.
In the example, we set the URL we'd like to call and initialise the curl object to point to that. Then we create an array of post data, and configure curl to use POST to make the request and to use our data array.
$service_url = 'http://example.com/rest/user/';
$curl = curl_init($service_url);
$curl_post_data = array(
"user_id" => 42,
"emailaddress" => 'lorna@example.com',
);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
$curl_response = curl_exec($curl);
curl_close($curl);
$xml = new SimpleXMLElement($curl_response);
We execute the request and capture the response. Health warning: by default curl will echo the response (for reasons that aren't clear to me), if you want to parse it then you will need to use the CURLOPT_RETURNTRANSFER flag to have curl return the response rather than a boolean indication of success - this fooled me completely for a while, I have no idea why it works this way. As you can see I've parsed the resulting XML and my script can then continue with the data it acquired. Depending what you need to do next, you can manipulate the SimpleXMLElement object as you need to.
If you're working with PHP and services, then hopefully this will get you started, if you have any questions or comments, then please add them below!
If you don't know about PHP, Rest, or curl, then I recommend you do a little reading around each of those subjects before reading this as its unlikely to make much sense - I'm not including background on these topics as there are better resources elsewhere.
I've written about using curl before from the command line, but this example uses PHP's curl to access the service. This is just a simple example, but hopefully if you are doing something along these lines you can adapt for your needs.
In the example, we set the URL we'd like to call and initialise the curl object to point to that. Then we create an array of post data, and configure curl to use POST to make the request and to use our data array.
$service_url = 'http://example.com/rest/user/';
$curl = curl_init($service_url);
$curl_post_data = array(
"user_id" => 42,
"emailaddress" => 'lorna@example.com',
);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
$curl_response = curl_exec($curl);
curl_close($curl);
$xml = new SimpleXMLElement($curl_response);
We execute the request and capture the response. Health warning: by default curl will echo the response (for reasons that aren't clear to me), if you want to parse it then you will need to use the CURLOPT_RETURNTRANSFER flag to have curl return the response rather than a boolean indication of success - this fooled me completely for a while, I have no idea why it works this way. As you can see I've parsed the resulting XML and my script can then continue with the data it acquired. Depending what you need to do next, you can manipulate the SimpleXMLElement object as you need to.
If you're working with PHP and services, then hopefully this will get you started, if you have any questions or comments, then please add them below!
Curl Cheat Sheet
Tuesday, August 19. 2008
I have a scribbled sheet on my desk, which is my "cheat sheet" for curl, its really short and I thought I'd put my notes here for safe-keeping. If you're visiting, then I hope they help you too.
Curl is a way of making web requests from the command line. I only do this under linux, and if you don't know why you'd want to do that, then you probably don't need to read any further (although, that would also make an interesting article!).
curl http://www.lornajane.net
Will give you the output that would be sent to your browser if you requested the main page of this site from there.
This is where it gets interesting, you can see the actual information being included with the HTTP request when you use the verbose switch.
curl -v http://www.lornajane.net
Try it - you see the headers and the client/server negotiation. Stuff like cache information, browser identification, and cookie information all gets transmitted in these headers.
Curl can make requests and include data with them. It can use GET as you'd expect, but POST, PUT and DELETE are all supported too.
curl -X GET "http://www.example.com?page=2&category=toys"
I've added the quotes because the ampersand confuses the command line
curl -X POST http://www.example.com/registration.php -d username=lornajane -d password=password -d phone=0123456789
PUT and DELETE can be done in the same way, just using the -X switch.
Actually, if you've got this far then you know what you're doing - use the curl manpage for information on the other switches. Curl can do more things than I think I would ever want to do, not just HTTP, and can spoof cookies and all sorts of other good things. Its especially good for testing web services as it allows clearer diagnosis of the exact behaviour and response. Don't tell anyone but I have also been known to vardump in the middle of webservices when debugging, and using curl lets you see the output "as it comes" - very handy!
Curl from command line
Curl is a way of making web requests from the command line. I only do this under linux, and if you don't know why you'd want to do that, then you probably don't need to read any further (although, that would also make an interesting article!).
curl http://www.lornajane.net
Will give you the output that would be sent to your browser if you requested the main page of this site from there.
Verbose output (-v)
This is where it gets interesting, you can see the actual information being included with the HTTP request when you use the verbose switch.
curl -v http://www.lornajane.net
Try it - you see the headers and the client/server negotiation. Stuff like cache information, browser identification, and cookie information all gets transmitted in these headers.
Using HTTP verbs (-X) and data (-d)
Curl can make requests and include data with them. It can use GET as you'd expect, but POST, PUT and DELETE are all supported too.
curl -X GET "http://www.example.com?page=2&category=toys"
I've added the quotes because the ampersand confuses the command line
curl -X POST http://www.example.com/registration.php -d username=lornajane -d password=password -d phone=0123456789
PUT and DELETE can be done in the same way, just using the -X switch.
Further Resources
Actually, if you've got this far then you know what you're doing - use the curl manpage for information on the other switches. Curl can do more things than I think I would ever want to do, not just HTTP, and can spoof cookies and all sorts of other good things. Its especially good for testing web services as it allows clearer diagnosis of the exact behaviour and response. Don't tell anyone but I have also been known to vardump in the middle of webservices when debugging, and using curl lets you see the output "as it comes" - very handy!
(Page 1 of 1, totaling 2 entries)


Comments
Mon, 05.01.2009 13:06
Doh! Interesting that you play piano, didn’t know that pi ece!
Mon, 05.01.2009 10:46
Daniel: I completely agree. I do like and use Zend Framewor k, but I already have books about it. When I buy a book on a subject, I don’t really want lots of ZF content. I can on ly assume that because its seen as a “buzz word”, people fee l the need to include it in any books current being wr [...]
Mon, 05.01.2009 10:41
Ubuntu User, Prasad, Joe – I’m pleased this was helpful, tha nks so much for dropping by and letting me know it worked ou t for you :)
Sun, 04.01.2009 23:25
Thanks for the tagging :) I responded (first time ever): htt p://www.urbanwide.com/2009/01/05/7-things/
Sun, 04.01.2009 06:42
You are my freakin’ hero! Thank you soooo much! mainMem.useN amedFile=FALSE fixed all my problems, my wife came back, I w on the lottery….. :) Thanks! Joe
Fri, 02.01.2009 23:33
I agree with your issues about some of the book turning into a mini ZF tutorial book. I feel that lately a lot of spa ce has been wasted on PHP books re-explaining MVC concepts, THEN introducing ZF (or another framework). Chalk it up to p ublishers not wanting to assume everyone reading the b [...]
Fri, 02.01.2009 00:44
All the best for Peru, and the rest of 2009!
Thu, 01.01.2009 23:33
Berry__: For normal people that is probably true but I add all sorts of clues which are different per-server, and still find myself regularly confused about which machine I’m logg ed in to …
Tue, 30.12.2008 15:23
Although I kinda like the colors for tabs, I think it’s over kill to have different colors on different servers. To be ho unest, I think the name of the machine you’re working on (on the left) is clear enough when working with it. The only thing I tend to dislike in screen, is that it’s rathe [...]