Skip to main content

Interface Development Example

Building a RESTful API can be achieved through the Express framework. The following is a detailed tutorial showing how to use Express to build a simple RESTful API. We will build a user management system that provides CRUD (create, read, update, delete) operations for users.

Step 1: Initialize the project

First, create a new project directory and initialize the Node.js project:

mkdir restful-api
cd restful-api
npm init -y

Step 2: Install dependencies

Install Express and other necessary middleware:

npm install express body-parser

Step 3: Set up the Express server

Create a file called server.js and set up a basic Express server:

server.js
const express = require('express');
const bodyParser = require('body-parser');

const app = express();
const port = 8080;

// Use body-parser middleware to parse the request body
app.use(bodyParser.json());

// Set up basic routing
app.get('/', (req, res) => {
res.json({ code: 200, msg: 'success', data: 'Welcome to the RESTful API' });
});

app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});

Step 4: Create User Data

For simplicity, we will use an in-memory array to store user data. Create a file called data.js:

data.js
let users = [
{ id: 1, name: 'Eave', email: 'eave@eaveluo.com' },
{ id: 2, name: 'Evan', email: 'evan@eaveluo.com' },
];

module.exports = users;

Step 5: Create CRUD operations

Add CRUD operations in the server.js file:

server.js
const express = require('express');
const bodyParser = require('body-parser');
const users = require('./data');

const app = express();
const port = 8080;

app.use(bodyParser.json());

// Get all users
app.get('/users', (req, res) => {
res.json({ code: 200, msg: 'success', data: users });
});

// Get a specific user
app.get('/users/:id', (req, res) => {
const user = users.find((u) => u.id === parseInt(req.params.id));
if (!user) return res.status(404).json({ code: 404, msg: 'User not found' });
res.json({ code: 200, msg: 'success', data: user });
});

// Create a new user
app.post('/users', (req, res) => {
const newUser = {
id: users.length + 1,
name: req.body.name,
email: req.body.email,
};
users.push(newUser);
res.status(201).json({ code: 201, msg: 'success', data: newUser });
});

// Update user
app.put('/users/:id', (req, res) => {
const user = users.find((u) => u.id === parseInt(req.params.id));
if (!user) return res.status(404).json({ code: 404, msg: 'User not found' });

user.name = req.body.name;
user.email = req.body.email;
res.json({ code: 200, msg: 'success', data: user });
});

// Delete user
app.delete('/users/:id', (req, res) => {
const userIndex = users.findIndex((u) => u.id === parseInt(req.params.id));
if (userIndex === -1)
return res.status(404).json({ code: 404, msg: 'User not found' });

const deletedUser = users.splice(userIndex, 1);
res.json({ code: 200, msg: 'success', data: deletedUser });
});

app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});

Step 6: Test the API

Use [test tools](/docs/back-end/web-api#Interface debugging tools) such as ApiFox or cURL to test the API. The following uses apifox test:

  1. Get all users:

202407161636304

  1. Get a specific user:

202407161639003

  1. Create a new user:

202407161639498

  1. Update user:

202407161639504

  1. Delete user:

202407161639081

Complete code

server.js
const express = require('express');

const bodyParser = require('body-parser');

const users = require('./data');

const app = express();

const port = 8080;

app.use(bodyParser.json());

// Get all users
app.get('/users', (req, res) => {
res.json({ code: 200, msg: 'success', data: users });
});

// Get a specific user
app.get('/users/:id', (req, res) => {
const user = users.find((u) => u.id === parseInt(req.params.id));
if (!user) return res.status(404).json({ code: 404, msg: 'User not found' });
res.json({ code: 200, msg: 'success', data: user });
});

// Create a new user
app.post('/users', (req, res) => {
// Verify request parameters
if (!req.body.name || !req.body.email) {
return sendResponse(res, 400, 'Invalid request body', null);
}
const newUser = {
id: users.length + 1,
name: req.body.name,
email: req.body.email,
};
users.push(newUser);
res.status(201).json({ code: 201, msg: 'success', data: newUser });
});

// Update user
app.put('/users/:id', (req, res) => {
const user = users.find((u) => u.id === parseInt(req.params.id));
if (!user) return res.status(404).json({ code: 404, msg: 'User not found' });

user.name = req.body.name;
user.email = req.body.email;
res.json({ code: 200, msg: 'success', data: user });
});

// Delete user
app.delete('/users/:id', (req, res) => {
const userIndex = users.findIndex((u) => u.id === parseInt(req.params.id));
if (userIndex === -1)
return res.status(404).json({ code: 404, msg: 'User not found' });

const deletedUser = users.splice(userIndex, 1);
res.json({ code: 200, msg: 'success', data: deletedUser });
});

app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
data.js
let users = [
{ id: 1, name: 'Eave', email: 'eave@eaveluo.com' },
{ id: 2, name: 'Evan', email: 'evan@eaveluo.com' },
];

module.exports = users;

This simple tutorial shows how to create a RESTful API using Express, including CRUD operations. You can expand on this by adding authentication, connecting to a database, and more.

Loading Comments...