Sobes.tech
Intern

What is CRUD?

sobes.tech AI

Answer from AI

CRUD is an abbreviation that describes the main operations performed on data:

  • Create: Adding new data.
  • Read: Retrieving existing data.
  • Update: Modifying existing data.
  • Delete: Removing data.

In frontend development, these operations often correspond to HTTP methods when interacting with the backend via API:

CRUD Operation HTTP Method Description
Create POST Send data to create
Read GET Request data
Update PUT / PATCH Send data to update
Delete DELETE Request data deletion

Example of frontend implementation using JavaScript to interact with REST API:

// Suppose we have a user object and need to create it on the server
fetch('/api/users', {
  method: 'POST', // Create
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ name: 'New User', email: 'new.user@example.com' }),
})
  .then(response => response.json())
  .then(data => console.log('User created:', data))
  .catch(error => console.error('Error creating user:', error));

// Example of reading data
fetch('/api/users/1') // Read (for user with ID 1)
  .then(response => response.json())
  .then(data => console.log('User data:', data))
  .catch(error => console.error('Error fetching user:', error));

// Example of updating data
fetch('/api/users/1', {
  method: 'PUT', // Update
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ name: 'Updated User' }),
})
  .then(response => response.json())
  .then(data => console.log('User updated:', data))
  .catch(error => console.error('Error updating user:', error));

// Example of deleting data
fetch('/api/users/1', {
  method: 'DELETE', // Delete
})
  .then(response => {
    if (response.ok) {
      console.log('User deleted');
    } else {
      console.error('Error deleting user:', response.status);
    }
  })
  .catch(error => console.error('Error deleting user:', error));