APIGit
Native Git RepositoryVersioned, Git-native API repositoryAPI DesignVisual OpenAPI editor with live lintingAPI DocumentPublish versioned docs from GitAPI GovernanceCheck every API against your standardsMock ServerFrom your OpenAPI spec or Express.js codeTeam CollaborationOrganizations, teams, permissions and reviews

The full API lifecycle

Design, document, mock and govern your APIs in one Git-native workspace.

Get started freeView pricing

Learning

Help DocsGetting StartedVideo TutorialsBlog

Support

Contact UsRequest a DemoReport an Issue
PricingAbout
Sign InSign Up for Free
APIGit

The Git Platform for Full Life-Cycle API Development

Product

  • Native Git Repository
  • API Design
  • API Document
  • API Governance
  • Mock Server
  • Team Collaboration

Resources

  • Blog
  • Documentation
  • Pricing
  • Contact

Company

  • About
  • Careers
  • Privacy Policy
  • Terms of Service
  • Service Level Agreement
  • Cookie Policy

© 2026 APIGit. All rights reserved.

Home / Blog / mock-server / dynamic-mock-server

Dynamic Mock Server

2023-10-15
APIGit Team
5 min read
mock-server

APIGit supports dynamic, stateful and programmable mock servers to simulate any of complex business logic with ease. These are code-based mock servers, available on Team and Enterprise plans, and your scripts live in the apigit-mock/ folder of your repository, starting from apigit-mock/main.js. HTTP request messages are handled by defining routes using mock.define() and providing a URL pattern, HTTP verb and a callback function. You can also use mock.get(), mock.post() and the rest of the Express.js API, because mock is an Express.js app. For example:


mock.define('/users', 'GET', function(req, res) {
    ...
  })

or, for a POST method:


mock.define('/users', 'POST', function(req, res) {
    ...
  })

Standard HTTP methods such as 'DELETE' and 'PUT' are supported. The callback function you provide is always passed two objects as parameters, the Request and Response objects. The Request object contains all the data pertaining to the incoming request such as headers, body payload, and parameters. We use the Response object to build responses to the request.

Let's expand on the example above and start building a basic CRUD service for users. First, lets define a route to return a set of users:


mock.define('/users', 'GET', function(req, res) {
    var users = [ 
      { username: "dave", email: "dave@gmail.com" },
      { username: "john", email: "john@gmail.com" }
    ]
  
    return res.json(users)
  })

The res.json call will send a JSON response to the calling application. Remember to call a response function on the res object, without it your service will timeout and not return a successful result. We'll explore the other available response functions later

Lets add support for filtering based on the user's age using query parameters. req.query is an object containing the parsed query string, defaulting to . If we submit a request for 'GET /users?age=30' we can access the age value with req.query.age:


const _ = require('lodash')

mock.define('/users', 'GET', function(req, res) {
    var users = [
      { username: "dave", email: "dave@gmail.com", age: 32 },
      { username: "john", email: "john@gmail.com", age: 30 }
    ]
  
    if (req.query.age) {
      // convert req.query.age from String to a Number before filtering
      return res.json(_.filter(users, { 'age': Number(req.query.age) }))
    }
  
    return res.json(users)
  })

We use LoDash _.filter function to extract an array of users that match the age provided. If no users match the age criteria an empty array is returned. LoDash is one of the pre-installed libraries: load it with require at the top of your script, and it provides useful functions for manipulating arrays and objects.

To create our route for retrieving a single user we use route parameters as part of the service's URL path. With mock.define(), route parameters are specified using {route_param_name} syntax (:route_param_name works too), so in our example the URL path to retrieve a user by their username will be /users/{username}. The req.params is an object containing properties mapped to the named route parameters and our username will be available as req.params.username.


mock.define('/users/{username}', 'GET', function(req, res) {
    var users = [
      { username: "dave", email: "dave@gmail.com", age: 32 },
      { username: "john", email: "john@gmail.com", age: 30 }
    ]
  
    // respond with the user or an empty object if user doesnt exist (_ comes from the require above)
    return res.json(_.find(users, { 'username': req.params.username }) || {})
  })

Lets add a route for creating users. We'll verify that a username has been sent with the request and respond with an 400 error if it is missing. Data that is sent as a body payload in POST requests is accessible on the req.body object.


mock.define('/users', 'POST', function(req, res) {
    // validate username is present
    if (req.body.username === undefined) {
      return res.status(400).json({ error: { message: "Missing username" } })
    }
  
    return res.json({ status: "ok" })
  })

By default, all responses return a 200. To send another status, call res.status() first, as in the example above, where we've specified a custom error message.

That's a solid start, you can do a lot with services that return simple canned responses but they do only get you so far. To add realistic behaviour, persist data with the state object and generate responses with libraries such as faker.

Back to Blog

Related Posts

Spec-Based Mock Servers: A Working Mock from Your OpenAPI Document

APIGit • 2026-11-06
mock-server

Publish a mock server from your OpenAPI documents without writing code. It validates requests, answers from your examples and schemas, and works on every plan.

Read More

Spec-Based or Code-Based: Which Mock Server Do You Need?

APIGit • 2026-11-06
mock-server

APIGit has two types of mock server. Here is how they differ, when each one fits, and how to run both from one repository.

Read More

Mock Servers That Tell You What Is Wrong

APIGit • 2026-11-06
mock-server

Spec-based mock servers validate each request against your OpenAPI document, return clear problem+json errors, and let clients pick a response with the Prefer header.

Read More

Ready to get started with APIGIT?

Join thousands of developers and teams who are already using APIGIT to streamline their API development workflow.

Get Started Book a Demo