Building a RESTful User Management API
🎯 Introduction
In this article, you will combine routes, controllers, services, parameter validation, and a consistent response format to build a user management API with create, read, update, and delete operations. You will also call it from frontend code in a complete practical exercise.
🛠 Goals and Files
We will build a user management module with five RESTful endpoints:
| HTTP method | Path | Action |
|---|---|---|
| GET | /users | List users |
| GET | /users/:id | Get a user |
| POST | /users | Create a user |
| PUT | /users/:id | Update a user |
| DELETE | /users/:id | Delete a user |
The following files bring together the topics from each article:
app
├── router.js # Routes: register endpoints with router.resources
├── controller/user.js # Controller: read parameters, validate, call services, respond
├── service/user.js # Business logic: CRUD operations on an in-memory array
└── extend/helper.js # Extensions: consistent success / fail responses
config
├── config.default.js # Configuration: disable CSRF checks for debugging
└── plugin.js # Plugins: enable egg-validate
🛠 Service: Data Operations
Use a module-level in-memory array to simulate stored data and implement five methods:
const { Service } = require('egg');
// Simulate a database with a module-level array shared across requests; reset on restart
const users = [
{ id: 1, name: 'Ming', age: 18 },
{ id: 2, name: 'Hong', age: 20 },
];
let nextId = 3;
class UserService extends Service {
async findAll() {
return users;
}
async findById(id) {
return users.find(item => item.id === Number(id));
}
async create(data) {
const user = { id: nextId++, name: data.name, age: data.age };
users.push(user);
return user;
}
async update(id, data) {
const user = await this.findById(id);
if (!user) return null;
if (data.name !== undefined) user.name = data.name;
if (data.age !== undefined) user.age = data.age;
return user;
}
async remove(id) {
const index = users.findIndex(item => item.id === Number(id));
if (index === -1) return false;
users.splice(index, 1);
return true;
}
}
module.exports = UserService;
🛠 Controller: Coordination and Validation
The controller handles four tasks: reading parameters, validating them, calling services, and returning consistently formatted responses. It explicitly handles validation failures and missing resources:
const { Controller } = require('egg');
class UserController extends Controller {
// GET /users
async index() {
const { ctx } = this;
const users = await ctx.service.user.findAll();
ctx.helper.success(users);
}
// GET /users/:id
async show() {
const { ctx } = this;
const user = await ctx.service.user.findById(ctx.params.id);
if (!user) {
ctx.status = 404;
ctx.helper.fail('User not found');
return;
}
ctx.helper.success(user);
}
// POST /users
async create() {
const { ctx } = this;
try {
ctx.validate({
name: { type: 'string', required: true },
age: { type: 'number', required: true },
});
} catch (err) {
ctx.status = 422;
ctx.helper.fail('Missing or invalid parameters');
return;
}
const user = await ctx.service.user.create(ctx.request.body);
ctx.status = 201;
ctx.helper.success(user);
}
// PUT /users/:id
async update() {
const { ctx } = this;
try {
ctx.validate({
name: { type: 'string', required: false },
age: { type: 'number', required: false },
});
} catch (err) {
ctx.status = 422;
ctx.helper.fail('Invalid parameter format');
return;
}
const user = await ctx.service.user.update(ctx.params.id, ctx.request.body);
if (!user) {
ctx.status = 404;
ctx.helper.fail('User not found');
return;
}
ctx.helper.success(user);
}
// DELETE /users/:id
async destroy() {
const { ctx } = this;
const ok = await ctx.service.user.remove(ctx.params.id);
if (!ok) {
ctx.status = 404;
ctx.helper.fail('User not found');
return;
}
ctx.helper.success(null, 'User deleted successfully');
}
}
module.exports = UserController;
🛠 Router and Configuration
Register the routes in one line, then review the configuration:
module.exports = app => {
const { router, controller } = app;
router.get('/', controller.home.index);
router.resources('users', '/users', controller.user);
};
module.exports = {
validate: {
enable: true,
package: 'egg-validate',
},
};
module.exports = appInfo => {
const config = {};
config.keys = appInfo.name + '_my_secret_key';
// Disable CSRF checks for local learning; re-enable them before deployment
config.security = {
csrf: {
enable: false,
},
};
return config;
};
Reuse the success and fail helpers from the previous article; their implementations are not repeated here.
🛠 Starting and Testing the API
Start the server with npm run dev, then test all five endpoints with curl:
# List users
curl http://127.0.0.1:7001/users
# Create
curl -X POST http://127.0.0.1:7001/users \
-H 'Content-Type: application/json' \
-d '{"name":"Gang","age":22}'
# Get a user
curl http://127.0.0.1:7001/users/3
# Update
curl -X PUT http://127.0.0.1:7001/users/3 \
-H 'Content-Type: application/json' \
-d '{"age":23}'
# Delete
curl -X DELETE http://127.0.0.1:7001/users/3
After creating a user, retrieve the list to confirm that requests share the updated data. Missing parameters produce a 422 response with the standard error format. You can also use API clients such as Apifox or Postman for a more visual testing workflow.
🧱 Calling the API from the Frontend
With the API ready, use fetch to call it. Here are examples of listing and creating users:
const baseURL = 'http://127.0.0.1:7001';
// List users
const res = await fetch(baseURL + '/users');
const result = await res.json();
if (result.code === 0) {
console.log('User list:', result.data);
} else {
console.log('Request failed:', result.message);
}
// Create a user
const addRes = await fetch(baseURL + '/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Li', age: 21 }),
});
const addResult = await addRes.json();
console.log(addResult.message);
This shows the benefit of a consistent response format: the frontend can check code for every endpoint instead of using a different parsing strategy for each one.
egg-cors. For this learning example, you can run the code in an HTML file, with the appropriate CORS configuration when required.⚠️ Limitations of In-Memory Data
This implementation is sufficient for learning, but an in-memory array has two clear limitations:
- Data resets on restart: Newly added data disappears when the server restarts.
- Instances do not share data: In production, separate processes hold separate copies, which can become inconsistent.
For a real project, replace the array operations in the service with database operations. Because the business logic lives in the service layer, only this file needs to change; the controller stays the same. That is the value of a layered architecture.
❓ Questions and Answers
Q1: Why is required false in the update validation rules?
The update endpoint accepts a subset of fields, such as just the age, so each field is optional. The service updates only the supplied fields. This is commonly called a partial update.
Q2: Why return 200 after deletion?
Both 200 and 204 are common for successful RESTful deletions. We use 200 with the standard response structure so the frontend can read message. What matters is a consistent team convention.
Q3: Does adding pagination require major changes?
No. Accept page and pageSize in findAll and slice the array. Read those parameters from ctx.query in the controller, pass them to the service, and return the result using helper.page from the previous exercise.
Q4: Can I use this structure in a company project?
You can adopt the layered structure and conventions directly. Real applications also need a database, authentication and authorization, logging, and stricter validation. Add these advanced capabilities gradually on top of this foundation.
🧪 Exercise
Add pagination with GET /users?page=1&pageSize=10. Slice the array in the service and include the total count in the standard response format.
// Add a method to UserService
async findByPage(page, pageSize) {
// Write your code here
}
// Update the index method
async index() {
const { ctx } = this;
// Write your code here
}
🎉 You have completed the user management exercise and the Egg.js course! From scaffolding a project to using layers, plugins, and extensions, you now have the skills to build APIs with Egg.js. Next, try connecting a database with tools such as egg-mysql or egg-sequelize and applying this structure to a real project.
