Skip to main content
REST API Design Tutorial
CHAPTER 06 Beginner

CRUD Operations in REST APIs

Updated: May 14, 2026
25 min read

# CHAPTER 6

CRUD Operations in REST APIs

1. Introduction

Almost every application ever built boils down to four fundamental database operations: Create, Read, Update, and Delete (CRUD). In REST API design, we systematically map these database interactions to our HTTP endpoints. In this chapter, we will bridge the gap between HTTP Requests and backend logic, illustrating exactly how a Server receives data from a Client, interacts with a Database, and returns the appropriate JSON response for each CRUD operation.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Map CRUD database operations directly to REST endpoints.
  • Parse incoming JSON request bodies for Create and Update operations.
  • Extract Path Parameters to identify resources for Read and Delete operations.
  • Construct standard JSON response structures for successful operations.

3. Beginner-Friendly Explanation

Imagine a digital contact book.
  • Read (GET): You want to see all your contacts, or just one specific contact's phone number.
  • Create (POST): You met a new friend and want to add their name and number to the book.
  • Update (PUT/PATCH): Your friend changed their phone number, and you need to correct their entry.
  • Delete (DELETE): You are no longer friends, so you erase them from the book entirely.

A REST API is simply a programmable wrapper around this contact book, allowing external applications to perform these four actions securely.

4. Setup: The In-Memory Database

For these examples, we will use Node.js/Express. Instead of connecting a real database, we will use a simple Javascript array to represent our data so we can focus entirely on the API logic.
javascript
12345678910
const express = require('express');
const app = express();
app.use(express.json()); // CRITICAL: Tells Express to parse incoming JSON!

// Our "Database"
let users = [
    { id: 1, name: "Alice", role: "admin" },
    { id: 2, name: "Bob", role: "user" }
];
let nextId = 3;

5. READ Operations (GET)

There are two types of read operations: getting the whole collection, or getting one item.

1. Get Collection:

javascript
123456789
// Endpoint: GET /api/users
app.get('/api/users', (req, res) => {
    // 1. Fetch all data from DB
    // 2. Return 200 OK with data
    res.status(200).json({
        status: "success",
        data: users
    });
});

2. Get Singleton:

javascript
123456789101112131415
// Endpoint: GET /api/users/1
app.get('/api/users/:id', (req, res) => {
    // Extract the ID from the URL (Path Parameter)
    const userId = parseInt(req.params.id);
    
    // Search the database
    const user = users.find(u => u.id === userId);
    
    // If not found, return 404!
    if (!user) {
        return res.status(404).json({ error: "User not found" });
    }
    
    res.status(200).json({ data: user });
});

6. CREATE Operations (POST)

To create a record, the client must send JSON data in the HTTP Request Body.
javascript
123456789101112131415161718192021
// Endpoint: POST /api/users
// Client sends: { "name": "Charlie", "role": "user" }
app.post('/api/users', (req, res) => {
    // 1. Extract data from the Request Body
    const { name, role } = req.body;
    
    // 2. Basic Validation (Chapter 9 covers this deeply)
    if (!name || !role) {
        return res.status(400).json({ error: "Name and role are required." });
    }
    
    // 3. Create the new database record
    const newUser = { id: nextId++, name: name, role: role };
    users.push(newUser);
    
    // 4. Return 201 Created AND the newly created object!
    res.status(201).json({
        message: "User created successfully",
        data: newUser
    });
});

7. UPDATE Operations (PUT / PATCH)

Updates require both the URL ID (to know *who* to update) and the Request Body (to know *what* to update).
javascript
123456789101112131415161718
// Endpoint: PUT /api/users/1
app.put('/api/users/:id', (req, res) => {
    const userId = parseInt(req.params.id);
    const { name, role } = req.body;
    
    // Find the user
    let userIndex = users.findIndex(u => u.id === userId);
    if (userIndex === -1) return res.status(404).json({ error: "User not found" });
    
    // Update the record
    users[userIndex].name = name || users[userIndex].name;
    users[userIndex].role = role || users[userIndex].role;
    
    res.status(200).json({
        message: "User updated",
        data: users[userIndex]
    });
});

8. DELETE Operations (DELETE)

Deletes only require the URL ID.
javascript
12345678910111213
// Endpoint: DELETE /api/users/1
app.delete('/api/users/:id', (req, res) => {
    const userId = parseInt(req.params.id);
    
    const userIndex = users.findIndex(u => u.id === userId);
    if (userIndex === -1) return res.status(404).json({ error: "User not found" });
    
    // Erase from database array
    users.splice(userIndex, 1);
    
    // Return 204 No Content. (No JSON body needed!)
    res.status(204).send();
});

9. Best Practices

  • Return the Created Object: When a client POSTs data to create a record, the database generates dynamic data (like an Auto-Increment ID, or a created_at timestamp). Always return the complete, newly generated object in the 201 Created response. The client needs that generated ID to interact with the object later!

10. Common Mistakes

  • Forgetting Body Parsers: If you try to run the POST code above, and req.body.name is always undefined, it is because the server does not know how to translate incoming raw HTTP text into a JSON object. In Express, you MUST include app.use(express.json()) at the top of your file to enable JSON parsing.

11. Exercises

  1. 1. Look at the POST and PUT examples. Which part of the HTTP request holds the data the client wants to save?
  1. 2. Why does the GET /api/users/:id endpoint not require reading the req.body?

12. Coding Challenges

  • Challenge: Conceptualize a new Express endpoint: PATCH /api/users/:id/ban. If this endpoint is hit, it finds the user by ID and sets a hypothetical isBanned property to true. Do you need a request body for this? Write out the logic conceptually.

13. MCQs with Answers

Question 1

When implementing a POST route to create a new resource, what is the industry-standard HTTP Status Code to return upon success, and what should the response body contain?

Question 2

When extracting the Resource ID from a URL (e.g., extracting "42" from /api/users/42), which object property in Express.js contains this data?

14. Interview Questions

  • Q: Walk me through the implementation of a full CRUD REST API for a "Products" table. Detail the HTTP Methods, the endpoint URLs, and how you extract the necessary data (Path Params vs Body) for each operation.
  • Q: Explain why the DELETE method typically returns a 204 No Content status code. What does this code explicitly signal to the frontend client?

15. FAQs

Q: Do I always have to build all 4 CRUD endpoints? A: No! You only build what your application requires. If you are building an API that outputs daily stock market prices, you might only build GET /api/stocks. The data is updated automatically by internal scripts, so exposing POST or DELETE endpoints to the public API would be a massive security flaw.

16. Summary

In Chapter 6, we bridged the theoretical concepts of REST with practical implementation. We demonstrated how to map standard CRUD database operations to Express.js endpoints. We learned how to extract Path Parameters (req.params) for targeted operations like GET Singleton and DELETE, and how to extract and parse JSON payloads (req.body) for POST and PUT operations. We also enforced the correct usage of status codes: 200 OK, 201 Created, 204 No Content, and 404 Not Found.

17. Next Chapter Recommendation

We have glossed over the exact mechanics of how data physically moves from Client to Server. Proceed to Chapter 7: Request and Response Handling.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·