Build a RESTful API

Combine @koa/router, koa-bodyparser, @koa/cors, and error handling to build a complete user CRUD API.

🎯 Introduction

By the end of this article, you will have a user CRUD API with route modules, request body parsing, CORS support, and centralized error handling, and you will be able to call it with fetch from the frontend. This project combines the previous five articles. The code is longer, but every piece should be familiar.


🧱 Project Structure and Dependencies

The final directory structure:

koa-demo/
├── app.js            Entry file that assembles all middleware
├── routes/
│   └── users.js      User routes
└── package.json

Install all dependencies. This article was written and verified with Node.js v22 LTS, using Koa 3.2.1, @koa/router 15.7.0, koa-bodyparser 4.4.1, and @koa/cors 5.0.0.

npm install koa @koa/router koa-bodyparser @koa/cors

@koa/cors provides CORS middleware. If your frontend runs on port 5173 and your API runs on port 3000, the browser restricts cross-origin requests. Registering this middleware allows them with one line of code.


🛠 User Routes: CRUD Operations

Use an in-memory array to simulate a database and implement five RESTful endpoints:

routes/users.js
import Router from '@koa/router';

const router = new Router({ prefix: '/users' });

// In-memory data simulating a database (resets when the server restarts)
let users = [
    { id: 1, name: 'Alex', age: 18 },
    { id: 2, name: 'Emma', age: 20 },
];
let nextId = 3;

// List users: GET /users
router.get('/', async (ctx) => {
    ctx.body = { code: 200, data: users };
});

// Get user details: GET /users/1
router.get('/:id', async (ctx) => {
    const user = users.find((u) => u.id === Number(ctx.params.id));

    if (!user) {
        ctx.throw(404, 'User not found');
    }

    ctx.body = { code: 200, data: user };
});

// Create a user: POST /users
router.post('/', async (ctx) => {
    const { name, age } = ctx.request.body;

    if (!name) {
        ctx.throw(400, 'name is required');
    }

    const user = { id: nextId++, name, age };
    users.push(user);

    ctx.status = 201; // Created successfully
    ctx.body = { code: 201, data: user };
});

// Update a user: PUT /users/1
router.put('/:id', async (ctx) => {
    const user = users.find((u) => u.id === Number(ctx.params.id));

    if (!user) {
        ctx.throw(404, 'User not found');
    }

    const { name, age } = ctx.request.body;
    if (name !== undefined) user.name = name;
    if (age !== undefined) user.age = age;

    ctx.body = { code: 200, data: user };
});

// Delete a user: DELETE /users/1
router.delete('/:id', async (ctx) => {
    const index = users.findIndex((u) => u.id === Number(ctx.params.id));

    if (index === -1) {
        ctx.throw(404, 'User not found');
    }

    users.splice(index, 1);
    ctx.body = { code: 200, message: 'User deleted successfully' };
});

export default router;

A few design choices:

  • Meaningful status codes: Return 201 when a resource is created, 404 when it cannot be found, and 400 for invalid parameters. The status code tells the client what happened.
  • In-place updates: The PUT endpoint uses !== undefined to update only fields provided by the frontend, leaving other values unchanged.
  • Delegate errors to ctx.throw: Routes focus on application logic instead of formatting error responses.

🧰 Entry File: Assemble the Middleware

app.js
import Koa from 'koa';
import bodyParser from 'koa-bodyparser';
import cors from '@koa/cors';
import usersRouter from './routes/users.js';

const app = new Koa();

// 1. Centralized error handling
app.use(async (ctx, next) => {
    try {
        await next();
    } catch (err) {
        ctx.status = err.status || 500;
        ctx.body = { code: ctx.status, message: err.message || 'Internal server error' };
        console.error('API error:', err);
    }
});

// 2. CORS and request body parsing
app.use(cors());
app.use(bodyParser());

// 3. Application routes
app.use(usersRouter.routes());
app.use(usersRouter.allowedMethods());

// 4. 404 fallback
app.use(async (ctx) => {
    ctx.status = 404;
    ctx.body = { code: 404, message: 'Endpoint not found' };
});

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

The order follows the previous article: error handling → general middleware (CORS and body parsing) → routes → 404 fallback. You can use this structure as a starting template for future Koa projects.


💡 Call the API from the Frontend

Now call the API with fetch. Assume the frontend runs in a Vite project on port 5173:

// List users
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: 'Sam', age: 22 }),
});

// Update the user with id 1
await fetch('http://localhost:3000/users/1', {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ age: 19 }),
});

// Delete the user with id 2
await fetch('http://localhost:3000/users/2', {
    method: 'DELETE',
});

If you forget to register @koa/cors, the browser console will show a CORS error mentioning Access-Control-Allow-Origin. This is a common obstacle when the frontend and backend run separately; now you know how to handle it.


❓ Questions and Answers

Q1: In-memory data disappears on restart. What should a production project use?

Production projects store data in a database such as MySQL or MongoDB. We use an in-memory array here to focus on Koa. Later, replace array operations with database queries while keeping the API structure the same.

Q2: What is the difference between PUT and PATCH?

PUT represents replacing an entire resource, while PATCH represents a partial update. Real projects do not always enforce this distinction strictly. Our example uses PUT to update only the supplied fields, a common practical approach.

Q3: Why does this example not check authentication?

Authentication commonly uses a solution such as JWT, implemented as separate middleware before the routes. It is an advanced topic. Once you understand this foundation, adding authentication means adding another middleware layer.

Q4: How do I register multiple route files?

Use the same approach for each module: export a router, then call app.use(xxxRouter.routes()) and app.use(xxxRouter.allowedMethods()) in app.js. With many modules, you can also use a loop to load them automatically.


🧪 Practice

  1. Following the users module, create routes/articles.js with article CRUD endpoints using the fields id, title, and content. Register it in app.js.
routes/articles.js
import Router from '@koa/router';

const router = new Router({ prefix: '/articles' });

// Write your code here

export default router;
  1. Add support for a ?keyword=xxx query parameter to the list endpoint, returning articles whose titles contain the keyword.

🎉 You have completed the Koa course! From hello world to a complete RESTful API, you now have the skills to build backend APIs with Koa independently. Try replacing the in-memory data with a real database to put your API to work!