Tag Archives: REST

Using cURL to test a REST service

When testing a REST service I tend to use cURL most of the time. It’s fast and pretty easy (when you write down all the options like I have here ;))

POST

curl -i -H "Accept: application/xml" -X POST -d "firstname=niklas&lastname=ottosson" http://127.0.0.1/students/student  

This will create (POST) a new student with firstname ‘niklas’ and lastname ‘ottosson’

PUT

curl -i -H "Accept: application/xml" -X PUT -d "mail=niklas@mailinator.com" http://127.0.0.1/students/student/82  

This will set (PUT) the mail address on student with id number 82

DELETE

curl -i -H "Accept: application/xml" -X DELETE http://127.0.0.1/students/student/82  

This will delete student with id number 82

GET

curl -i -H "Accept: application/xml" -X GET "http://127.0.0.1/students?firstname=niklas&lastname=ottosson"  

This will get us the student were firstname is ‘niklas’ and lastname ‘ottosson’ (quotes are needed for passing multiple parameters)

OPTIONS
-i – tells cURL to display the response header so we can examine it for errors
-H – tells cURL to send request headers. In this example we tell the system that we only want xml formated responses (“Accept: application/xml”)
-X – sets what REST function we want to use
-d “data1=foo&data2=bar” – is the data we want to send/save (only for PUT or POST)

Get PUT and DELETE data

REST is very popular as a web service technique and PHP (v5.1) has got great support for POST through the $_POST (and $_GET for that matter) but for PUT, DELETE and OPTIONS we have to do a little different.

To get the data from a PUT request we can use this technique:

if($_SERVER['REQUEST_METHOD'] == 'PUT') {  
    $data = file_get_contents('php://input');  
} 

This will put the data from the PUT request into the $data variable. If you want DELETE och OPTION just check for those request methods instead and use the same fetch method as above.