14

I searched, but I didn't find an answer. I have a RESTful API to manage a basic CRUD. I'm trying to create an update method using PUT, but I can't retrieve the params values. I'm using Postman to make the requests, my request looks like:

URL

http://localhost/api/update/987654321

Params

id = 987654321
name = John Smith
age = 35

PHP

$app = new Slim();
$app->put('/update/:id', function( $id ) use( $app ){
    var_dump([
        'id' => $id,
        'name' => $app->request->put('name'),
        'age' => $app->request->put('age')
    ]);
});

My var_dump() result is:

array(3) {
  ["id"]=>
  string(9) "987654321"
  ["name"]=>
  NULL
  ["age"]=>
  NULL
}

What is wrong? Any idea?

bodruk
  • 3,242
  • 8
  • 34
  • 52
  • 1
    checkout the manual http://docs.slimframework.com/#Request-Body if you scroll down to the Request Variables section there is an example there. Alternatively you can take the parameters directly from the body and put into var by doing `parse_str(file_get_contents("php://input"),$post_vars);` – mic May 20 '14 at 13:47
  • I want to upload images in this request. Using ```POST``` to update is a bad pratice? – bodruk May 20 '14 at 13:49
  • 1
    sorry my comment wasn't about `POST` data, i copied the code from another site. However the PUT data is set in the body of the request just like with all other types of request apart from GET (although you might be able to attach a body string to a GET request, I've never tried it). You could do `parse_str($app->request->getBody(), $vars);` and do a var_dump on that to see your data. – mic May 20 '14 at 14:31

2 Answers2

23

I had the same problem. Firstly, I was sending PUT data with the Postman option to encode it as "form-data", that's why Slim wasn't getting the param values.

As it is explained in W3, the content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.

In our case, we have to send PUT data with the Postman option "x-www-form-urlencoded" (see explanation of "application/x-www-form-urlencoded" in W3).

Screenshot of the right Postman option selected

eloibm
  • 899
  • 2
  • 11
  • 27
  • 2
    Switched to x-www-form-urlencoded with postman to make it works ! Thanks for the well explained answer (w3 link)! – Quentin Klein Dec 28 '14 at 15:00
  • 1
    You just saved me hours of head bashing. Thank you! – Joel Jun 11 '15 at 13:45
  • I have a question, with x-www-form-urlencoded cannot upload file, it's only accept the string. How can I upload a file using PUT/PATCH method..? – Praditha Jun 24 '16 at 02:52
1

$app->request->put() is returning a null value...

so u can use try $app->request->params instead

Batanichek
  • 7,761
  • 31
  • 49