api-mockup-server
v4.0.0
Published
Simple restAPI JSON mockup server
Maintainers
Readme
API Mockup Server
Node server for simple rest API mockup with JSON format responses. Just define couple of routes with response data and start the server. Server will listen on default port 9933.
API Mockup Server may be useful during application development when for example back-end part is not ready yet and you want to work separately on front-end with mocked data, or you have a fully functional back-end part but you want to mockup only some of your rest APIs in order to simulate a problematic situation, bugs, edge cases, error responses, etc...
Installation
npm install api-mockup-server --saveQuick start
Create server.js file:
// server.js
// load API Mockup Server
const amServer = require('api-mockup-server');
// define some routes
const routes = [
{
active: true,
path: '/books/all',
method: 'GET',
status: 200,
data: [
{ id: 10, title: 'Robinson Crusoe' },
{ id: 20, title: 'Don Quixote' },
],
},
{
active: true,
path: '/books/:id',
method: 'GET',
status: 200,
data: {
id: 10,
title: 'Robinson Crusoe',
author: 'Daniel Defoe',
pages: 250,
},
},
{
active: true,
path: '/authors',
method: 'POST',
status: 400,
data: {
errorMsg: 'Author name is too long!',
},
},
];
// start the server
amServer({
port: 9933,
prefix: '/api',
routes,
});Then run with command:
node server.jsNow, you can make 3 requests:
- GET http://localhost:9933/api/books/all - server will response with HTTP status 200 and return static data with books list
- GET http://localhost:9933/api/books/7 - server will response with HTTP status 200 and return static data with book detail (regardless of provided id, in this case 7)
- POST http://localhost:9933/api/authors - server will response with HTTP status 400 and return static data with error message (regardless of provided POST request data)
Advanced server configuration
In bigger projects you don't want to store all of your routes and responses in one file. You can configure routes in separate file using routes param and responses in database param providing path to folder containing JSON files with response data.
If you want to mockup only some of rest APIs you can use API Mockup Server as a mockup layer between your running back-end server and frontend application. In this scenario you have to configure proxy server target with running back-end. If you use more then one target, API Mockup Server will ask you to choose one target via CLI interface on server start.
Note 1: You don't have to restart the server when you make changes in routes config (if path is defined) or data files. API Mockup Server will automatically reflect new configuration while running.
Note 2: Server will add x-api-mockup-server header to all mocked/proxied responses with some metadata. You can turn it off by setting mockHeader: false in server options.
FILE STRUCTURE:
/db <- database directory
/BOOKS_ALL.json <- response data file (all statuses)
/BOOK_DETAIL.json <- response data file (statuses !== 400)
/BOOK_DETAIL.400.json <- response data file (HTTP status 400)
paths.js <- routes definitions
server.js <- main server fileMain file with server configuration ./server.js:
// server.js
const amServer = require('api-mockup-server');
amServer({
port: 9933,
routes: './paths.js', // path to file with routes
database: './db', // path to directory with data files
prefix: '/api/v1',
encoding: 'utf8',
delay: {
min: 500, // delay mocked responses in milliseconds
max: 2500,
},
proxy: {
server: 'https://another.server.example',
},
});In routes configuration you can instead of data param define key param which is used to find corresponding JSON file with response data.
Add ./paths.js file in the same directory:
// paths.js
module.exports = [
{
active: true,
key: 'BOOKS_ALL', // response data file: ./db/POSTS_ALL.json
path: '/books/all',
method: 'GET',
status: 200,
callback: ({ params, query, body, data, req }) => {
// modify data
const date = new Date();
const timestamp = date.getTime();
const newData = data.map((item) => {
item._t = timestamp;
return item;
});
// return modified data
return newData;
},
},
{
active: true,
key: 'BOOK_DETAIL', // response data file: ./db/BOOK_DETAIL.json
prefix: '/api/v2',
path: '/books/:id',
method: 'GET',
status: 200,
applyIf: ({ params, query, body, req }) => {
// conditionally mocked if request URL param id = 10
// e.g.: /api/v2/books/10
return params.id === '10';
},
},
];According to used route keys you need to create corresponding files in database folder. If file is missing, route will have empty response.
Add ./db/BOOKS_ALL.json file:
[
{ "id": 10, "title": "Robinson Crusoe" },
{ "id": 20, "title": "Don Quixote" }
]Add ./db/BOOK_DETAIL.json file:
{
"id": 10,
"title": "Robinson Crusoe",
"author": "Daniel Defoe",
"pages": 250
}Add ./db/BOOK_DETAIL.400.json file:
{
"errorCode": 15,
"errorMsg": "Book ID has wrong format."
}Then run with command:
node server.jsServer will listen on port 9933 (according to your configuration).
Server configuration options
const amServer = require('api-mockup-server');
const serverConfigOptions = {
// configuration properties are defined in the table below
};
amServer(serverConfigOptions);Routes configuration options
You can specify routes in separate file and include it in server config.
Example:
module.exports = [
{
active: true,
path: '/books/all',
method: 'GET',
status: 200,
data: [
{ id: 10, title: 'Robinson Crusoe' },
{ id: 20, title: 'Don Quixote' },
],
},
{
active: true,
key: 'BOOK_UPDATE',
path: '/books/:bookId',
method: 'PUT',
status: 200,
applyIf: ({ params, query, body, req }) => {
// params - parameters from route path
// body - parameters from request payload (PUT/POST)
return params.bookId === '10' && body.bookGenre === 'novel';
},
},
{
active: false, // this route is disabled
key: 'SEARCH_AUTHORS',
prefix: '/v2',
path: '/authors',
method: 'POST',
status: 400,
},
];Proxy route interceptors
If you have configured proxy target you can intercept and modify data by omitting key and data params in route definition. (Param status is also not needed here - it will be ignored.)
Example:
module.exports = [
{
active: true,
path: '/user/:id',
method: 'GET',
callback: ({ data }) => {
// modify proxied data here, e.g:
data.fullName = `${data.firstName} ${data.lastName}`;
return data;
},
},
];This route will intercept and change data from proxy target for GET /user/:id requests.
CLI shortcuts
The server now supports interactive keyboard shortcuts in supported terminals. Shortcuts include:
q— Quit the serverr— List configured routest— Show configured proxy targetp— Show current portf— Show global prefixs— Suspend/resume mocking
License
MIT
