CRUD Operations in REST APIs

Create, Read, Update, Delete

Last updated: 3/5/2025

1 hour
Medium

CRUD Operations in REST APIs

🌍 Introduction

CRUD stands for Create, Read, Update, and Deleteβ€”the four fundamental operations used to manage resources in a RESTful API.

Each CRUD operation is mapped to an HTTP method:

OperationHTTP MethodDescription
CreatePOSTAdd a new resource
ReadGETRetrieve an existing resource
UpdatePUT or PATCHModify an existing resource
DeleteDELETERemove a resource

In this lesson, you’ll learn:

  • How CRUD maps to RESTful APIs.
  • When to use POST, GET, PUT, PATCH, DELETE.
  • The structure of CRUD endpoints.

πŸ“Œ 1. Understanding CRUD Operations

βœ… 1️⃣ Create (POST)

Used to add new data to the server.

Example: Creating a new user

POST /users Content-Type: application/json
{ "name": "Alice Johnson", "email": "alice@example.com" }

Response:

{ "id": 1, "name": "Alice Johnson", "email": "alice@example.com" }

βœ” Uses 201 Created status code.
βœ” Data is sent in the request body.


βœ… 2️⃣ Read (GET)

Used to retrieve data from the server.

Example: Getting all users

GET /users

Response:

[ { "id": 1, "name": "Alice Johnson", "email": "alice@example.com" } ]

βœ” Uses 200 OK status code.
βœ” No request body needed.

Example: Getting a single user by ID

GET /users/1

βœ… 3️⃣ Update (PUT or PATCH)

Used to modify existing data.

  • PUT: Updates all fields.
  • PATCH: Updates specific fields.

Example: Updating a user with PUT

PUT /users/1 Content-Type: application/json
{ "name": "Alice Jane Johnson", "email": "alice@example.com" }

βœ” Uses 200 OK status code.
βœ” Replaces the entire resource.

Example: Updating only the email with PATCH

PATCH /users/1 Content-Type: application/json
{ "email": "alice.johnson@example.com" }

βœ” Uses 200 OK status code.
βœ” Modifies only the given fields.


βœ… 4️⃣ Delete (DELETE)

Used to remove a resource.

Example: Deleting a user

DELETE /users/1

Response:

{ "message": "User deleted successfully" }

βœ” Uses 204 No Content (if no response) or 200 OK.


πŸ“Œ 2. Designing CRUD Endpoints

A RESTful API follows a consistent structure:

ActionHTTP MethodEndpoint
Create a new userPOST/users
Get all usersGET/users
Get a user by IDGET/users/{id}
Update a userPUT or PATCH/users/{id}
Delete a userDELETE/users/{id}

βœ” Use plural nouns (/users instead of /user).
βœ” Use path parameters for specific resources (/users/{id}).
βœ” Follow HTTP method conventions (GET for reading, POST for creating, etc.).


πŸ“Œ 3. Implementing CRUD Operations in Express.js

Let's implement these operations using Node.js + Express.

πŸš€ Example: Setting Up CRUD Routes in Express.js

const express = require('express'); const app = express(); app.use(express.json()); // Middleware to parse JSON let users = []; // Temporary in-memory database // Create (POST) - Add a new user app.post('/users', (req, res) => { const newUser = { id: users.length + 1, ...req.body }; users.push(newUser); res.status(201).json(newUser); }); // Read (GET) - Get all users app.get('/users', (req, res) => { res.json(users); }); // Read (GET) - Get a user by ID app.get('/users/:id', (req, res) => { const user = users.find(u => u.id === parseInt(req.params.id)); if (!user) return res.status(404).json({ error: "User not found" }); res.json(user); }); // Update (PUT) - Update a user app.put('/users/:id', (req, res) => { let user = users.find(u => u.id === parseInt(req.params.id)); if (!user) return res.status(404).json({ error: "User not found" }); user = { ...user, ...req.body }; res.json(user); }); // Delete (DELETE) - Remove a user app.delete('/users/:id', (req, res) => { users = users.filter(u => u.id !== parseInt(req.params.id)); res.json({ message: "User deleted successfully" }); }); // Start the server const PORT = 3033; app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

βœ” Handles all CRUD operations.
βœ” Uses status codes correctly.
βœ” Includes basic error handling.


🎯 Summary

  • CRUD operations allow managing resources in an API.
  • Each HTTP method maps to a CRUD action (POST -> Create, GET -> Read, etc.).
  • Use structured endpoints (/users/{id}).
  • Implemented a full CRUD API using Express.js.

βœ… Next Lesson: Implementing a Simple CRUD API (Hands-on Project)

In the next lesson, you’ll build a complete CRUD API with data validation and error handling. πŸš€