Code-based mock servers: Express.js routes, state and libraries
A mock generated from an OpenAPI document answers with examples. That covers most needs, but not all: sometimes the mock must remember what was created, check a token, answer differently on the third call, or behave like a system that has no description at all. For those cases APIGit runs your own JavaScript. A code-based mock server is an Express.js app, hosted for you, whose routes live in your repository and are versioned with it.
Code-based mock servers are available on the Team and Enterprise plans. If examples from your document are enough, a spec-based mock server needs no code and works on every plan; Spec-based or code-based helps you choose.
APIGit creates the Express.js app, loads apigit-mock/main.js from the commit you publish, and serves it at your mock server's URL in an isolated sandbox. You write routes; there is no server to set up.
Key Features of MockServer
- Express.js Wrapper: MockServer wraps around Express.js, making it familiar and easy to use for developers who already know Express.js.
- Pre-installed Libraries: Popular JavaScript libraries such as
lodash,moment,faker, and more are pre-installed, streamlining the creation of dynamic mock responses. - Supports Routes and Middleware: Define routes and middleware just like you would in an Express application.
- Stateful Data: Easily maintain data between requests using a global state variable, making it perfect for simulating real-world behavior.
- Modular Organization: Mock server scripts are modularly organized, similar to daily development practices, making it easy to manage and reuse code.
How MockServer Works
MockServer works by allowing you to define API routes using mock object. mock is a global Express.js app automatically created by the underlying apigit mock server framework. You can define routes using mock.[method], following the guidelines provided in the Express.js documentation.
Here's an overview of how MockServer simplifies creating APIs:
- Use
mock.[method](...)to define routes and request handlers. - Use standard Express.js methods like
reqandresto handle HTTP requests and responses. - Pre-installed libraries eliminate the need for manual installation, allowing you to focus on defining your mock logic.
Example: Defining Routes and Middleware
The following example shows how easy it is to create routes using MockServer:
// exampleAuthMiddleware, firstMiddleware and secondMiddleware come from the next
// section: define them above these routes
mock.get("/user/:name", function (req, res) {
return res.status(200).send("hello" + req.params.name);
});
mock.post('/test-urlencoded', (req, res) => {
console.log('Received x-www-form-urlencoded data:', req.body);
res.status(200).send({ message: 'Received x-www-form-urlencoded data', data: req.body });
});
mock.get('/testauth', exampleAuthMiddleware, (req, res) => {
res.status(200).send('This route is to demonstrate auth through middleware ');
});
mock.get('/testmd2', firstMiddleware, secondMiddleware, (req, res) => {
res.status(200).send('This route has multiple middlewares!');
});
// mock.define also adds the route to the list at GET /apigit-mockserver-routes
mock.define("/user/:name", "DELETE", function(req, res) {
// handle req
res.status(200).send("success");
});
mock.[method] is the native Express.js approach. mock.define(path, method, callback) defines a route that is also listed by GET /apigit-mockserver-routes. See Routes and Middleware.
Using Middleware with MockServer
Just like in Express.js, you can use middleware to process requests before they reach the final route handler:
const jwt = require('jsonwebtoken');
const exampleAuthMiddleware = (req, res, next) => {
const authHeader = req.headers['authorization'];
if (!authHeader) {
return res.status(401).send('Authorization header missing');
}
const token = authHeader.split(' ')[1];
if (!token) {
return res.status(401).send('Token missing');
}
try {
const SECRET_KEY = 'your-secret-key';
const decoded = jwt.verify(token, SECRET_KEY);
req.user = decoded;
next();
} catch (err) {
return res.status(403).send('Invalid token');
}
};
function firstMiddleware(req, res, next) {
console.log('First middleware');
next();
}
function secondMiddleware(req, res, next) {
console.log('Second middleware');
next();
}
mock.use((req, res, next) => {
console.log("middleware for all routes");
next();
});
mock.get('/testauth', exampleAuthMiddleware, (req, res) => {
res.status(200).send('This route is to demonstrate auth through middleware ');
});
mock.get('/testmd2', firstMiddleware, secondMiddleware, (req, res) => {
res.status(200).send('This route has multiple middlewares!');
});
The mock.use() function can be used to define middleware for all routes or specific paths, just like in an Express app.
Working with Requests and Responses
MockServer provides a simple way to interact with requests and responses using standard Express.js conventions. Below are some examples of common tasks:
Handling Route Parameters and Query Parameters
mock.get('/repository/:user/:repo', (req, res) => {
const { user, repo } = req.params;
res.json({
message: 'Repository Details',
user: user,
repo: repo
});
});
mock.get('/search', (req, res) => {
const { keyword, page, limit } = req.query;
res.json({
message: 'Search Parameters Received',
keyword: keyword || 'none',
page: page ? parseInt(page, 10) : 1,
limit: limit ? parseInt(limit, 10) : 10
});
});
Setting Response Status and Headers
mock.get('/not-found', (req, res) => {
res.status(404).json({
message: 'Resource not found',
code: 404
});
});
mock.get('/single-header', (req, res) => {
res.set('Content-Type', 'application/json');
res.set('X-Custom-Header', ['value1', 'value2']);
res.json({ message: 'Headers set successfully!' });
});
Using Pre-Installed Libraries
MockServer comes with popular JavaScript libraries pre-installed, so you can use them directly in your mock definitions:
const _ = require('lodash');
const moment = require('moment');
const { faker } = require('@faker-js/faker');
mock.get('/test-libs', (req, res) => {
const randomUser = {
id: faker.string.uuid(),
name: faker.person.fullName(),
email: faker.internet.email()
};
res.json({
currentDate: moment().format(),
activeUsers: _.filter([{ active: true }, { active: false }], { active: true }),
randomUser: randomUser
});
});
These libraries help you create rich, dynamic responses easily without the need for additional installations. If you need a library that is not listed, please reach out to APIGIT, and we will evaluate and add it quickly. The supported libraries include:
- @faker-js/faker (v9.9.0) - data generator
- ajv (v8.17.1) - JSON schema validation
- base64-js (v1.5.1) - Base64 encoding/decoding
- body-parser (v1.20.3) - request body parsing
- cookie-parser (v1.4.7) - cookie parsing
- cors (v2.8.5) - Cross-Origin Resource Sharing middleware
- jsonwebtoken (v9.0.2) - JWT creation and verification
- lodash (v4.17.21) - general utility
- moment (v2.30.1) - time and date handling
- uuid (v11.0.3) - UUID generator
- validator (v13.12.0) - validation helper
Stateful Data with MockServer
MockServer provides a state object, which allows you to store and retrieve data between requests, making it easy to simulate persistent state:
// Create a stateful list of users
mock.post('/users', (req, res) => {
if (!req.body.username) {
return res.status(400).json({ status: "error", details: "Missing username" });
}
state.users = state.users || [];
state.users.push(req.body);
return res.status(200).json({ status: "ok" });
});
Modular Mock Scripts with MockServer
To maintain cleaner and more organized code, MockServer supports splitting mock scripts into multiple files in a modular way, similar to everyday development practices. Typically, you would have a main.js file that defines all the routes, which then requires handler definitions from separate files. This allows you to create reusable, well-structured modules for route handlers, keeping your codebase maintainable.
For example:
- main.js: The main file that defines all routes and requires other files for the handler definitions. The handler modules are required at the beginning of the file for better readability and organization. For example, handlers like adding or deleting users can be defined in one file and exported together using
module.exports.
// main.js
// Require handler modules at the top
const { userPostHandler, userDeleteHandler } = require('./handlers/userHandlers');
// Define routes
mock.post('/user/:name', userPostHandler);
mock.delete('/user/:name', userDeleteHandler);
- handlers/userHandlers.js: A separate file that exports functions to handle different user-related requests, using
module.exportsto export them together.
// handlers/userHandlers.js
function userPostHandler(req, res) {
res.status(404).send('User not found');
}
function userDeleteHandler(req, res) {
res.status(200).send('User deleted successfully');
}
module.exports = {
userPostHandler,
userDeleteHandler
};
This modular approach helps you organize routes logically and enables reusability across different mock projects.
Run it on your machine
You do not have to publish to try a change. The apigit command line runs the same scripts locally:
apigit mock serve apigit-mock
It uses the same Express app, mock, state and libraries as the hosted mock, and loads the scripts again when you save a file. Locally state starts empty on every start and the script is not sandboxed. See Run a mock on your machine.
Reference
Everything in this post is documented in detail: code-based mock servers, routes and middleware, libraries and state.