I'm currently designing and implementing a RESTful API in PHP. However, I have been unsuccessful implementing my initial design.
GET /users # list of users
GET /user/1 # get user with id 1
POST /user # create new user
PUT /user/1 # modify user with id 1
DELETE /user/1 # delete user with id 1
So far pretty standard, right?
My problem is with the first one GET /users
. I was considering sending parameters in the request body to filter the list. This is because I want to be able to specify complex filters without getting a super long url, like:
GET /users?parameter1=value1¶meter2=value2¶meter3=value3¶meter4=value4
Instead I wanted to have something like:
GET /users
# Request body:
{
"parameter1": "value1",
"parameter2": "value2",
"parameter3": "value3",
"parameter4": "value4"
}
which is much more readable and gives you great possibilities to set complex filters.
Anyway, file_get_contents('php://input')
didn't return the request body for GET
requests. I also tried http_get_request_body()
, but the shared hosting that I'm using doesn't have pecl_http
. Not sure it would have helped anyway.
I found this question and realized that GET probably isn't supposed to have a request body. It was a bit inconclusive, but they advised against it.
So now I'm not sure what to do. How do you design a RESTful search/filtering function?
I suppose I could use POST
, but that doesn't seem very RESTful.
The best way to implement a RESTful search is to consider the search itself to be a resource. Then you can use the POST verb because you are creating a search. You do not have to literally create something in a database in order to use a POST.
For example:
Accept: application/json
Content-Type: application/json
POST http://example.com/people/searches
{
"terms": {
"ssn": "123456789"
},
"order": { ... },
...
}
You are creating a search from the user's standpoint. The implementation details of this are irrelevant. Some RESTful APIs may not even need persistence. That is an implementation detail.