xero
xero

Reputation: 4319

REST api request method input parameters

i've been researching/creating a REST api, in the backbone.js to php context.

i understand the concept of HTTP verbs and when they should be used

GET - select

POST - create

PUT - update

DELETE - delete

i also understand the concept of passing an identifier as a semantic url, e.g.

GET http://api/users/123

DELETE http://api/users/123

in these cases the "123" is the id the business logic will use to get/delete a user.

but what about the POST and PUT contexts? when sending a request to

PUT http://api/users/123

the api will update user id 123 with the supplied parameters, here's where my question arises.

i would assume the input parameters to update with would be sent as PUT parameters. in php syntax this is represented as: file_get_contents('php://input') (this is the same for delete requests.)

when testing this via backbone.js it works perfectly.

but when i try and create a new element with

POST http://api/users/

i would assume the input values would sent as POST parameters/ in php syntax this is represented as $_POST. but this does not work.

after some testing, and reading up on rails style REST apis (which is what the backbone docs suggest), i realized that all request variables are sent the same way. if i change my code to use file_get_contents('php://input') to get the request parameters for every request type, backbone works perfectly.

is this standard fair for REST apis? or just "rails flavored" ones?

Upvotes: 1

Views: 6380

Answers (1)

John Sheehan
John Sheehan

Reputation: 78104

PUT, POST, PATCH, etc (everything but GET and DELETE*) accept request bodies. Generally data is passed as either:

  • A URL encoded string of name/value pairs (exactly the same as a URL querystring) that is decoded and parsed by the server into $_POST (or similar depending on your web framework of choice). This typically relies on the presence of a Content-Type header set to application/x-www-form-urlencoded (browsers do this by default when forms are submitted). If you see the data in file_get_contents('php://input') but not $_POST it's very likely this header is not present or is set to another value. If you're using Chrome, you can see what headers and body the client is sending in the Network tab of the dev tools.

  • The other popular request body format is to use Content-Type: application/json and then write out a JSON string to the body. This can be accessed via file_get_contents('php://input') and then parsed with a JSON parser.

* Note on DELETE: it's a little unclear whether or not using a request body with DELETE is allowed or a good practice.

Upvotes: 1

Related Questions