How is CRUD implemented?
sobes.tech AI
Answer from AI
CRUD stands for Create, Read, Update, Delete. These are the basic operations performed on data.
Create: Sending a POST request to the endpoint to create a new resource. The request body usually contains the data of the new object.
// Examples using Fetch API
fetch('/api/items', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name: 'New Item' }),
})
.then(response => response.json())
.then(data => console.log('Created:', data));
Read: Sending a GET request.
- Read all resources: GET request to the main collection endpoint.
- Read a specific resource: GET request to the endpoint with the resource ID.
// Read all
fetch('/api/items')
.then(response => response.json())
.then(data => console.log('All items:', data));
// Read specific
fetch('/api/items/123')
.then(response => response.json())
.then(data => console.log('Item 123:', data));
Update: Sending a PUT or PATCH request to the endpoint with the resource ID.
- PUT: full replacement of the existing resource.
- PATCH: partial update of the resource.
// Update (PUT)
fetch('/api/items/123', {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name: 'Updated Item' }),
})
.then(response => response.json())
.then(data => console.log('Updated:', data));
// Partial update (PATCH)
fetch('/api/items/123', {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ description: 'New Description' }),
})
.then(response => response.json())
.then(data => console.log('Patched:', data));
Delete: Sending a DELETE request to the endpoint with the resource ID.
fetch('/api/items/123', {
method: 'DELETE',
})
.then(response => {
if (response.ok) {
console.log('Deleted successfully');
} else {
console.error('Delete failed');
}
});
Connection with REST API:
CRUD operations are closely related to REST (Representational State Transfer) principles, where HTTP methods are used to perform these actions on resources:
| CRUD | HTTP Method |
|---|---|
| Create | POST |
| Read | GET |
| Update | PUT/PATCH |
| Delete | DELETE |
On the frontend, implementing CRUD involves sending these HTTP requests to the backend API and handling the responses received. Libraries like Axios, Fetch API, and frameworks/libraries for state and UI management (e.g., React, Vue, Angular) are often used.