views:

70

answers:

1

I'm writing an API and want to follow the REST approach. As I understand it, if I want to let API users update specific records a PUT http://server/specific_resource type request should be supported. Of course, they're not doing a GET and they'll need to pass along the new data and my question is how to do this (in my specific case only updating some of the fields of the specified record, but that's not so relevant here). There are two approaches I can think of: including the data in the request body (using curl: curl -X PUT -d "key=value" http://server/specific_resource) or in a query string (using curl: curl -X PUT http://server/specific_resource?key=value).

Unfortunately, regardless of the approach I take, it seems very hard to get the provided data. The problem seems to be that PHP only really completely understands two HTTP methods, GET and POST, with PUT considered to be for file uploads. If I include the data in the body then the only way to access it seems to be via an fopen('php://input') call. For instance, http_get_request_body() doesn't provide the data. Likewise, the information can't be found in the $_REQUEST superglobal. If I don't want to have to process the raw request body with fopen('php://input') then it appears that I must send the data as query string parameters, as the data will appear as elements of the $_GET superglobal (and so also $_REQUEST).

I'm specifically using CakePHP and it seems to only populate the form array of the params array in my controller method if the request was a POST. Query string parameters are put in params' url array regardless of the request method if used in the request URL. Not surprisingly, I'm not the only one who has run into this.

What is the solution that you'd suggest? Process the input stream? Use query string parameters? Just forget the PUT verb and use POST instead?

+1  A: 

Try this blog entry about parsing PUT data for a REST interface in PHP.

Paul Morgan
So your answer is, yes, use `PUT` and then parse the request body?
pr1001
Yes, you can use POST instead of PUT but if you don't use PUT you're not taking full advantage of a RESTful interface. Usually PUT is for updates to an existing resource (//server/resource) and POST is for creation of a new resource (//server).
Paul Morgan
Agreed, that's why I wanted to the PUT, I just wanted to make sure I'm not being overly dogmatic here.
pr1001