Build a RESTful API for User CRUD Operations

Combine routing, middleware, and error handling to build a complete RESTful user CRUD API and handle cross-origin requests.

🎯 Introduction

This article brings the course together in a practical project. You will combine routes, routers, middleware, and error handling to build a structured user CRUD API from scratch, then resolve cross-origin issues so the frontend can communicate with it.


🧱 What Does RESTful Mean?

RESTful describes an API design style: URLs identify resources, and request methods describe operations. Take users as an example:

Request Method and URLMeaning
GET /usersGet the user list
GET /users/1Get details for user 1
POST /usersCreate a user
PUT /users/1Update user 1
DELETE /users/1Delete user 1

The paths consistently use /users, while the request method expresses the operation. As the API grows, this makes each endpoint easy to understand from its method and URL alone.

Real projects store data in a database. For now, we will use an in-memory array and focus on the complete API structure. Once you learn about databases, you can replace the array operations with database operations.

🛠 Set Up the Project Structure

Continue from the previous article's project. First, plan the directory structure:

express-demo
├── app.js            # Entry point: mount middleware and routes
├── routes
│   └── user.js       # All endpoints for the users module
└── package.json

Use a Router to move the user endpoints into routes/user.js, with an in-memory array standing in for a database:

routes/user.js
import { Router } from 'express';

const router = Router();

// Simulate a database with an in-memory array
let users = [
    { id: 1, name: 'Ming', age: 18 },
    { id: 2, name: 'Hong', age: 20 },
];

export default router;

🛠 Read Endpoints: List and Details

Define two GET endpoints: the list endpoint returns the entire array; the details endpoint uses a route parameter to find a user and returns 404 if none is found:

routes/user.js
// GET /users: list users
router.get('/', (req, res) => {
    res.json({ code: 0, data: users });
});

// GET /users/:id: get user details
router.get('/:id', (req, res) => {
    const id = Number(req.params.id);
    const user = users.find((item) => item.id === id);

    if (!user) {
        return res.status(404).json({ code: 404, message: 'User not found' });
    }

    res.json({ code: 0, data: user });
});

Remember that req.params.id is a string. Convert it with Number() before comparing it to numeric IDs.


🛠 Create Endpoint: POST

The client submits new user data in the request body. The server reads it, generates an ID, and adds the user to the array:

routes/user.js
// POST /users: create a user
router.post('/', (req, res) => {
    const { name, age } = req.body;

    if (!name) {
        return res.status(400).json({ code: 400, message: 'name is required' });
    }

    const newUser = {
        id: users.length + 1,
        name,
        age,
    };

    users.push(newUser);

    // Return 201 to indicate successful resource creation
    res.status(201).json({ code: 0, data: newUser });
});

🛠 Update and Delete Endpoints: PUT and DELETE

Both operations first look up the target user by ID and return 404 if the user does not exist:

routes/user.js
// PUT /users/:id: update a user
router.put('/:id', (req, res) => {
    const id = Number(req.params.id);
    const user = users.find((item) => item.id === id);

    if (!user) {
        return res.status(404).json({ code: 404, message: 'User not found' });
    }

    const { name, age } = req.body;

    user.name = name ?? user.name;
    user.age = age ?? user.age;

    res.json({ code: 0, data: user });
});

// DELETE /users/:id: delete a user
router.delete('/:id', (req, res) => {
    const id = Number(req.params.id);
    const index = users.findIndex((item) => item.id === id);

    if (index === -1) {
        return res.status(404).json({ code: 404, message: 'User not found' });
    }

    users.splice(index, 1);

    res.json({ code: 0, message: 'Deleted successfully' });
});

🛠 Entry Point: Put It All Together

The entry file, app.js, mounts middleware and routes and adds the 404 fallback and error handler:

app.js
import express from 'express';
import userRouter from './routes/user.js';

const app = express();

// Parse JSON request bodies
app.use(express.json());

// Mount user routes
app.use('/users', userRouter);

// 404 fallback
app.use((req, res) => {
    res.status(404).json({ code: 404, message: 'Endpoint not found' });
});

// Centralized error handling
app.use((err, req, res, next) => {
    console.error('Error:', err.message);
    res.status(500).json({ code: 500, message: 'Something went wrong. Please try again later.' });
});

app.listen(3000, () => {
    console.log('Server running at http://localhost:3000');
});

Start the server with node --watch app.js, then test each operation:

# List users
curl http://localhost:3000/users

# Create a user
curl -X POST http://localhost:3000/users -H "Content-Type: application/json" -d "{\"name\":\"Hua\",\"age\":22}"

# Update a user
curl -X PUT http://localhost:3000/users/1 -H "Content-Type: application/json" -d "{\"age\":19}"

# Delete a user
curl -X DELETE http://localhost:3000/users/2

🪤 Cross-origin Requests and cors

The endpoints work, but a request from the frontend fails. The browser console shows an error mentioning something like Access-Control-Allow-Origin. This is a cross-origin issue.

Browsers enforce the same-origin policy: an origin is defined by its scheme, hostname, and port. A frontend at http://localhost:5173 and an API at http://localhost:3000 have different ports, so the request is cross-origin and the browser blocks access to the response unless the server permits it.

The same-origin policy is a browser security restriction that protects users. The server may have returned data normally, which is why curl can succeed while the browser reports an error.

The usual backend solution is to add CORS response headers that tell the browser cross-origin access is allowed. Rather than setting these headers manually, use the cors middleware. This course uses cors 2.8.6, tested with Node.js v22 and Express 5.2.1:

npm install cors
app.js
import express from 'express';
import cors from 'cors';
import userRouter from './routes/user.js';

const app = express();

// Allow cross-origin requests; register before routes
app.use(cors());

app.use(express.json());
app.use('/users', userRouter);

app.listen(3000);

The single line app.use(cors()) adds CORS response headers to all endpoints, allowing the frontend to access their responses in the browser.


💡 Call the API from the Frontend

Use fetch to call these endpoints just as you would any other backend API:

api.js
// Get the user list
const res = await fetch('http://localhost:3000/users');
const result = await res.json();

console.log(result.data); // Array of users

// Create a user
await fetch('http://localhost:3000/users', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({ name: 'Hua', age: 22 }),
});

Axios works too: point url at http://localhost:3000/users. You now have the complete flow working, from implementing an API to calling it from the frontend.


❓ Questions and Answers

Q1: Why does my data disappear after a restart?

The data lives in an in-memory array, which resets when the process restarts. This temporary approach is for practice. Real projects need a database for persistent storage.

Q2: What is the difference between PUT and POST?

In this API, POST creates a resource and PUT updates an existing resource. The PUT URL includes an ID, such as /users/1, to identify the target. POST generally omits the ID because the server generates it.

Q3: Does cors() without options allow all origins?

Yes. app.use(cors()) allows cross-origin access from any origin, which is convenient for local development. In production, configure an origin allowlist to permit only your frontend domains.

Q4: Is users.length + 1 a reliable way to generate user IDs?

It is sufficient for this exercise, but deleting a record from the middle can lead to duplicate IDs. Real projects use database-generated IDs or UUIDs rather than relying on array length.


🧪 Exercise

Following the users module, implement routes/book.js with three endpoints: GET /books (list), GET /books/:id (details), and POST /books (create). Each book has id and title fields. Mount the Router in app.js.

routes/book.js
import { Router } from 'express';

const router = Router();

// Write your code here

export default router;
app.js
// Write your code here: mount the book routes at /books

🎉 You have completed the Express course! From running your first server to working with routing, middleware, error handling, and a RESTful API, you now have the foundations to build backend APIs with Node.js independently. Next, explore a database such as MySQL or MongoDB and replace the in-memory array with persistent storage. Keep going!