DEV Community

oleg-melnic
oleg-melnic

Posted on

What is CRUD?

Create, Read, Update, and Delete (CRUD) are the four basic methods for a good functional model.

Create, Read, Update, Delete

When we create an API, we should provide four basic types of functionality to our model. The model should have the ability to create, read, update and remove resources. Program developers usually refer to these methods as the acronym CRUD. The model must be able to perform a maximum of these four functions in order to be complete. If an action cannot be described in any of these four operations, it should potentially be its own model.

The CRUD methods are common when building web applications because it provides a memorable basis for reminding developers how to build complete, usable models. For example, let’s imagine a system for tracking library books. In this hypothetical library, a database would be a books resource in which book objects would be stored. Let’s suppose this book object looks like this:

“book”: {
  "id": <Integer>,
  “title”: <String>,
  “author”: <String>
}
Enter fullscreen mode Exit fullscreen mode

To make this library system usable, we should be sure that there were clear mechanisms for completing the CRUD operations:
Create - is the method we use to add a new library book to the catalogue. The program that invokes the function would give values for title and author. When this function is called, a new entry corresponding to this new book should appear in the books resource. In addition, a new entry is assigned a unique id that can be used to access the resource later.
Read - is the method that we use to view all books in the catalogue. This function call would not change the books in the directory - it would simply get the resource and display the results. We would also have a function to extract a separate book for which we could supply the title, author or ISBN. One more time, this book will not be altered, only found.
Update — is the method we use to change information about a book. The program calling the function would supply the new values for title and author. After the function call, the corresponding entry in the books resource would contain the new fields supplied.
Delete — is the method we use to remove a library book from the catalogue. The program calling the function would supply one or more values (title and/or author) to identify the book, and then this book would be removed from the books resource. After this function is called, the books resource should contain all of the books it had before, except for the one just deleted.

CRUD and REST

In the REST environment, CRUD often corresponds to the HTTP methods POST, GET, PUT and DELETE respectively. These are the four basic elements of a persistent storage system.
In the remainder of the article, we will recommend the response standards and codes that developers usually follow when creating RESTful applications. Conventions may differ, so feel free to experiment with different return values and codes as you become comfortable with the CRUD conception.
Imagine that we’re working with a system that tracks dishes and the relevant prices for the restaurant. Let’s see how we should implement CRUD operations.

Create

We commonly use the HTTP POST method to create resources in the REST environment. POST creates a new resource of the specified type.
For example, imagine that we add a new product to the stored list of dishes for this restaurant, and the dish objects are stored in the dishes resource. If we wanted to create a new element, we would use the POST request:
Request:

POST http://www.best-restaurant.my/dishes/
Enter fullscreen mode Exit fullscreen mode

Body -

{
  "dish": {
    "name": “Meat Toast”,
    "price": 12
  }
}
Enter fullscreen mode Exit fullscreen mode

This creates a new item with a name value of “Meat Toast” and a price value of 12. After successful creation, the server should return a header with a link to the newly-created resource, along with an HTTP response code of 201 (CREATED).
Response:
Status Code - 201 (CREATED)
Body -

{
  "dish": {
    "id": 1463,
    "name": “Meat Toast”,
    "price": 12
  }
}
Enter fullscreen mode Exit fullscreen mode

From this response, we can see that the dish with the name “Meat Toast” and price 8 has been successfully created and added to the dishes resource.

Read

We use the GET method to read resources in the REST environment. Reading a resource should never change any information - it should only retrieve it. If you call GET for the same information 10 times in a row, you must receive the same response to the first call as the last one.
GET can be used to read an entire list of items:
Request:

GET http://www.best-restaurant.my/dishes/
Enter fullscreen mode Exit fullscreen mode

Response: Status Code - 200 (OK)
Body -

{
  "dishes": [
    {
      "id": 1,
      "name": “Some Rolls”,
      "price": 4
    },
    {
      "id": 2,
      "name": “Mozzarella”,
      "price": 8
    },
    ...
    {
      "id": 1463,
      "name": “Meat Toast”,
      "price": 12
    },
    {
      "id": 1584,
      "name": “Muesli”,
      "price": 3
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

GET requests can also be used to read a specific item when its id is specified in the request:
Request:

GET http://www.best-restaurant.my/dishes/1463
Enter fullscreen mode Exit fullscreen mode

Response: Status Code - 200 (OK) Body -

{
  "id": 1463,
  "name": “Meat Toast”,
  "price": 12
}
Enter fullscreen mode Exit fullscreen mode

After this request, no information has been changed in the database. The item with id 1463 has been retrieved from the dishes resource, and not modified. When there are no errors, GET will return the HTML or JSON of the desired resource, along with a 200 (OK) response code. If there is an error, it most often will return a 404 (NOT FOUND) response code.

Update

PUT is the HTTP method used to update information in the system.
For example, if the price of Avocado Toast has been raised, we should go into the database and update that information. We can do this with a PUT request.
Request:

PUT http://www.best-restaurant.my/dishes/1463
Enter fullscreen mode Exit fullscreen mode

Body -

{
  "dish": {
    "name": “Meat Toast”,
    "price": 10
  }
}
Enter fullscreen mode Exit fullscreen mode

This request should change the item with id 1463 to have the attributes supplied in the request body. This dish with id 1463 should now still have the name “Avocado Toast”, but the price value should now be 10, as it used to be 12.
Response: Status Code - 200 (OK) Body - not necessary
The response includes a Status Code of 200 (OK) to signify that the operation was successful, but it need not return a response body.

Delete

The CRUD operation Delete corresponds to the HTTP method DELETE. It is used to remove a resource from the system.
Let’s say that the world avocado deficit has reached a critical point, and we can no longer afford to serve this modern delicacy at all. We should go into the database and delete the item that corresponds to “Avocado Toast”, which we know has an id of 1463.
Request:

DELETE http://www.best-restaurant.my/dishes/1463
Enter fullscreen mode Exit fullscreen mode

After the successful operation, we receive a response code of 204 (NO CONTENT) with no response body. The dishes resource should no longer contain the dish object with id 1463.

Response: Status Code - 204 (NO CONTENT) Body - None

Calling GET on the dishes resource after this DELETE call would return the original list of dishes with the {"id": 1463, "name": “Meat Toast”, "price": 10} entry removed. All other dish objects in the dishes resource should remain unchanged. If we tried to call a GET on the item with id 1463, which we just deleted, we would receive a 404 (NOT FOUND) response code and the state of the system should remain unchanged.
Calling DELETE on a resource that does not exist should not change the state of the system. The call should return a 404 response code (NOT FOUND) and do nothing.

CRUD Practice

Create, Read, Update, and Delete methods are fundamental components of a usable storage model. You have already seen above a couple of examples of how the CRUD concept can help us to design systems. Now, try using CRUD to list out routes for a new example model. Imagine that we are creating a system that tracks workout classes, including the name of each class, who teaches it, and the duration of the class. An example class object would look like this:

{
  "class": {
    "id": 1    
    "name": “Hard Work”,
    “trainer”: “Bob Smeet”,
    "duration": 2.25
   }
}
Enter fullscreen mode Exit fullscreen mode

All of the classes are stored in a classes resource at www.force-academy.com/classes.
For each CRUD operation, write out answers to the following questions:
• What routes would you need to implement to provide your workout class model with this CRUD functionality and what are their corresponding HTTP methods?
• What effect would each route have on the database?
• What response body would each route return?
• What response code would each route return?

CRUD Practice Answers

1) Create
Route: POST /classes
Effect on Database: Adds the class provided in the request body to the database
Response Body{ "class": The Newly-Created Class }
Success Response Code: 201
2) Read (All Classes)
Route: GET /classes
Effect on Database: None
Response Body{ "classes": [ Array of All Saved Classess ] }
Success Response Code: 200
3) Read (One Class)
Route: GET /classes/:id
Effect on Database: None
Response Body{ "class": The class with the specified ID }
Success Response Code: 200
4) Update
Route: PUT /classes/:id
Effect on Database: Updates the class with the specified ID to have the class information provided in the request body
Response Body{ "class": The updated class now saved in the database }
Success Response Code: 200
5) Delete
Route: DELETE /classes/:id
Effect on Database: Removes the class with the specified ID from the database
Response Body: None
Success Response Code: 204
As you get more practice with designing storage systems, incorporating CRUD operations into your models will become easier and easier.

Top comments (0)