api-mockup-server

3.1.2 • Public • Published

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 --save

Quick 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: 20,
      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.js

Now, you can make 3 requests:

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: You have to restart the server when you make changes in configuration files (server setup and routes config) while server is running (except of JSON data files in database folder, which are loaded dynamically during request processing).

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 file

Main 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: (req, res, data) => {
      // modify returned data
      const date = new Date();
      const timestamp = date.getTime();
      return data.map((item) => {
        item._t = timestamp;
        return item;
      });
    },
  },
  {
    active: true,
    key: 'BOOK_DETAIL', // response data file: ./db/BOOK_DETAIL.json
    path: '/books/:id',
    method: 'GET',
    status: 200,
    applyIf: (req, params, data) => {
      // conditionally mocked if request URL param id = 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.js

Server 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);
Parameter Type Description Default
port
(optional)
number The port on which mock server will listen. 9933
database
(optional)
string Directory name or path to directory in which are stored JSON data files with responses.
Example: "./db"
"database"
prefix
(optional)
string Api route prefix.
Example: "/api/v1"
""
encoding
(optional)
string Response text encoding. "utf8"
cors
(optional)
boolean Cross-Origin Resource Sharing policy.
Set to false if you don't wont it.
true
delay
(optional)
Object Mocked response delay. Random delay will be generated between min and max values in milliseconds. If not set response will by served with additional delay.
Example: { min: 500, max: 2500 }


If you want to define exact response time set min and max params to the same value.
Example: { min: 1000, max: 1000 }

{ min: 0, max: 0}
routes
(mandatory)
string | Array Definitions of API routes. It could be array or path to definition file. More config options below.
Example: "./routes.js"
Example:
[
  {
    active: true,
    path: '/movies',
    method: 'GET',
    status: 200,
    key: 'MOVIES_ALL'
  },
  {
    active: false,
    path: '/movies/:movieId',
    method: 'DELETE',
    status: 400,
    key: 'DELETE_MOVIE'
  }
]
[]
proxy
(optional)
Object Proxy server configuration. Undefined or not active routes will be redirected to proxy target. If server is defined as an array, on the start the interactive CLI will ask you to choose from given list of server addresses.
Examples:
{ 
  server: "http://localhost:3000"
}
{
  server: [
    'http://localhost:3000',
    'http://api.server.example',
    'http://api2.server.example'
  ]
}
null

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: (req, params, data) => {
      // params - parameters from route path
      // data - parameters from request payload (PUT/POST)
      return params.bookId === '10' && data.bookGenre === 'novel';
    },
  },
  {
    active: false, // this route is disabled
    key: 'SEARCH_AUTHORS',
    path: '/authors',
    method: 'POST',
    status: 400,
  },
];
Parameter Type Description Default
active
(optional)
boolean ON/OFF switch. If it's not set as true rule will be omitted. false
path
(mandatory)
string Route path. See more details in ExpressJS 4.x Request documentation.
Examples:
"/movies/:movieId"
"/movies/list/:genre?"
"/comments/:year/:month"
""
method
(optional)
string HTTP method. Available methods: GET, POST, PUT, DELETE, HEAD, CONNECT, OPTIONS, TRACE, PATCH
Example: "POST"
"GET"
status
(optional)
number HTTP response status. See list of statuses on MDN Web Docs. 200
data
(optional)
Object Response data. If you have bigger amount of data it could be replaced with key option (bellow)
Example:
data: { 
  id: 10, 
  title: 'Robinson Crusoe',
  genre: 'Adventure' 
}
null
key
(optional)
string Param will be used for searching for a file with response data (in JSON format) in defined database folder. You could store response data in a folder defined by database param with filename used as key with .json extension. Server will find that file and return content as JSON response. You can define different data (in separate files) for each HTTP status code using extension prefix. API Mockup Server uses key also as an ID in console log for identifying which route was handled/intercepted or which has an error.

Examples:
"BOOKS_LIST"
"BOOK_REMOVE"
"AUTHOR_EDIT"

Files based on examples above. They should be stored in database folder:
BOOKS_LIST.json
BOOK_REMOVE.json
AUTHOR_EDIT.json
AUTHOR_EDIT.202.json
AUTHOR_EDIT.400.json
AUTHOR_EDIT.500.json
""
applyIf
(optional)
Function Decide whether route should be mocked or not. Return true if route should not be proxyied but returned as defined JSON data mockup. It's useful when you want to proxy route only if some conditions are met. applyIf has lower priority than param active.

Function params:
  • req - ExpressJS request object
  • params - request URL params
  • body - PUT/POST request payload data
Return value (boolean):
  • true - if you want your route to be handled by mockup server
  • false - if you want to pass request to proxy target (if configured - otherwise empty response will be returned)

Example:
applyIf: (req, params, body) => {
  return params.bookId === '100';
}
null
callback
(optional)
Function Callback method for response manipulation. It should always return data.
Function params:
  • req - ExpressJS request object
  • res - ExpressJS response object
  • data - returned data (from mock or from proxy target)
Example:
callback: (req, res, data) => {
  // modify data and return back
  data.time = new Date();
  return data;
}
null

License

MIT

Package Sidebar

Install

npm i api-mockup-server

Weekly Downloads

0

Version

3.1.2

License

MIT

Unpacked Size

50.7 kB

Total Files

18

Last publish

Collaborators

  • pergalsk