CRUD stands for Create, Read, Update, Delete. These are the basic capabilities required when it comes to dealing with data in a storage system like a database.
From an API perspective, the following methods are used for each action:
Action | Method |
Create | POST |
Read | GET |
Update | PUT/PATCH |
Delete | DELETE |
Would you use a POST or a GET for search functionality?
Personally, I would always try to use GET over POST when it comes to search functionality, mainly for a couple of reasons:
- the URL constructed using parameters is easily re-usable, I can share my URL with another person and the results would be filtered the same way
- search engines “digest” searches using GET requests
- while GET is idempotent, POST is generally used for making changes on the Server-Side, like creating a new user
PUT vs Patch
While many developers still battle over which method should be used, the truth is that it all depends on the logic of your application. Sometimes it is good practice to use Patch, while some other times it just makes sense to use PUT.
PUT overwrites (replaces) the entire entity.
Patch overwrites only certain attributes.
Example:
I have created/added (POST) a new vehicle to my database. If I do a GET request I can see that my data in JSON looks like this:
{
"brand": "bmw",
"model": "X5",
"color": "yellow",
"price": 1000,
}
Now I want to change the color from yellow to blue. I can do that using PUT or Patch.
PUT: /vehicles/1
{
"brand": "bmw",
"model": "X5",
"color": "blue",
"price": 1000,
}
PATCH: /vehicles/1
{
"color": "yellow"
}
I would always use PATCH over PUT in scenarios like this. It is good practice to not overwrite the entire entity every time you want to perform a small change.
Conclusion
You now know what CRUD stands for. You should always try to use the correct method for the action you try to perform as there are good practices to follow and improve the code performance and maintainability within a project or a team.