Searches in a RESTful interface (GET or POST?)
When designing a RESTful API, the architectural semantics are considered vital to the overall design.
- GET – Get a list of some collection or retrieve some element
- PUT – Replace/ Update an element
- POST – Create a new element
- DELETE – Easy peasy, delete an element
However, all these beautiful semantics don’t seem to cover the “search” or “filter” mechanism.
Example: You want to search for some elements. And that too based on some parameters.
e.g. An employee with the following parameters= Age: 35, Salary: 100000, Height: 170, Weight: 130, ContractType: Regular
Now, there are two options:
- GET company-domain/Employees?age=35&salary=100000&height=170&weight=130&contractType=Regular
- POST company-domain/GetEmployee
You can choose either one and your application will work fine.
The interesting thing is, no matter which one you choose; you are violating the REST semantics.
- Using GET for search purposes.
- Using POST where you are not creating some element.
Alright, so what do we do ?
Well, a nice feature of GET is that a GET request will NOT modify anything in your application. This is called idempotency. And the service will be called Idempotent.
And since GET has some very strong advantages over other solutions,
GET will be the choice here.
Now, this is upto you to use a clever parameter structure.
The two parameter structures that I personally use are: