DEV Community

Cover image for How to mock APIs from the CLI
Hassann
Hassann

Posted on • Originally published at apidog.com

How to mock APIs from the CLI

You need a fake API to build against. The backend isn’t ready, a third-party service is rate-limited, or your tests need to run without calling a live server. The usual answer is a mock. The question is how to stand one up from the command line.

Try Apidog today

You can define routes and canned responses in a GUI, but a mock built manually in a desktop app is difficult to reproduce, version, or recreate in CI. A CLI-defined mock is different: it is a command in a script, a pipeline step, or something an AI coding agent can run. If you can type it, automation can type it too.

This guide covers two approaches:

  1. Open-source CLI mock servers that turn an OpenAPI spec or JSON file into a local HTTP endpoint.
  2. The Apidog CLI workflow, which imports a spec into a hosted project and scripts custom mock expectations.

For a broader comparison, see the best API mock tools and REST API mocking tools guides.

The general route: run a mock server from a file

The classic CLI mock is a small binary pointed at a file. Give it a spec or data file, and it serves a real HTTP endpoint locally. No project, login, or account required.

Use this route when you need a quick, local, reproducible mock server.

Prism: serve an OpenAPI spec

If you already have an OpenAPI file, Prism from Stoplight is one of the fastest options. It reads your paths, response examples, and schemas, then serves responses that match the contract.

npx @stoplight/prism-cli mock ./openapi.yaml
Enter fullscreen mode Exit fullscreen mode

This starts a server on http://127.0.0.1:4010 and exposes every operation in the spec.

Check that it is running:

curl http://127.0.0.1:4010/orders/123
Enter fullscreen mode Exit fullscreen mode

Prism returns a defined response example when available. Otherwise, it generates data that matches the response schema. It also validates incoming requests against the OpenAPI document, so malformed requests receive a 422 response.

Prism is stateless: a POST request does not persist data for later requests. That makes it useful when contract accuracy matters more than simulated database behavior.

Install it globally if you do not want to use npx:

npm install -g @stoplight/prism-cli
Enter fullscreen mode Exit fullscreen mode

Mockoon CLI: run a data file headless

Mockoon CLI runs a mock environment from a data file. The file can come from the free Mockoon desktop app or be a plain OpenAPI specification.

npx @mockoon/cli start --data ./env.json
Enter fullscreen mode Exit fullscreen mode

Point --data to either:

  • A Mockoon environment file
  • An OpenAPI JSON file
  • An OpenAPI YAML file

Mockoon serves the environment immediately, using port 3000 by default. Set a different port when needed:

npx @mockoon/cli start --data ./env.json --port 4000
Enter fullscreen mode Exit fullscreen mode

If the environment file came from an older Mockoon version, the CLI migrates it in memory without modifying the original file.

Install it globally for a persistent mockoon-cli command:

npm install -g @mockoon/cli
Enter fullscreen mode Exit fullscreen mode

Use Mockoon CLI when you need hand-tuned routes, custom response rules, and headless execution in CI. A lightweight mock server for a RESTful API often fits this model.

json-server: fake a REST API from JSON

When you do not have an API spec yet, json-server is the fastest path. Create a JSON file with your data, and json-server generates a REST API around it.

npx json-server db.json
Enter fullscreen mode Exit fullscreen mode

For example, create db.json:

{
  "posts": [
    {
      "id": "1",
      "title": "First post",
      "published": true
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

Then call the generated endpoint:

curl http://localhost:3000/posts
Enter fullscreen mode Exit fullscreen mode

json-server provides GET, POST, PUT, PATCH, and DELETE endpoints. Unlike Prism, a POST persists data by writing it back to db.json.

It also supports filtering, sorting, and pagination through query parameters.

Install it globally if you want it on your PATH:

npm install -g json-server
Enter fullscreen mode Exit fullscreen mode

Choosing an open-source CLI mock

Tool Input Best for Stateful
Prism OpenAPI spec Contract-first local mocks No
Mockoon CLI Mockoon environment or OpenAPI Rich, hand-tuned routes in CI Depends on environment setup
json-server JSON data file Fast CRUD APIs without a spec Yes

These tools are lightweight and file-based, but each is a separate system. You must keep the mock files, API design, tests, and running processes synchronized yourself.

For exact request matching or replay scenarios, MockServer and WireMock offer deeper controls, with the trade-off of requiring a Java runtime.

The Apidog CLI route: import the spec, script the expectations

Apidog works differently from local mock-server binaries.

The apidog CLI does not start a local mock server from a file. There is no command such as:

apidog mock ./openapi.yaml
Enter fullscreen mode Exit fullscreen mode

Instead, Apidog hosts the mock. The CLI imports your API definition and manages custom mock expectations.

Apidog is not open source; it is a commercial product with a free tier. Its key workflow advantage is that API design, mocks, and tests can live in the same project rather than in separate files and processes.

If you only need a throwaway mock from one local file, Prism, Mockoon CLI, or json-server may be a better fit. If your mock must stay aligned with an evolving API definition, use the Apidog workflow.

Install and authenticate first. The Apidog CLI installation guide covers token setup.

npm install -g apidog-cli
apidog login --with-token <YOUR_ACCESS_TOKEN>
Enter fullscreen mode Exit fullscreen mode

Import a spec to get hosted smart mocks

Import an OpenAPI file into an Apidog project:

apidog import --project <PROJECT_ID> --format openapi --file ./openapi.json
Enter fullscreen mode Exit fullscreen mode

After import, Apidog provides hosted mock URLs for your endpoints.

This differs from Prism and json-server:

  • You do not start a local server process.
  • The imported definition produces hosted mocks.
  • Smart mock responses use schema field types and names.

For example, an email field can return a plausible email value, and a createdAt field can return a realistic timestamp instead of an arbitrary string.

apidog import also accepts Swagger 2.0, Postman, and Apidog formats, so existing API definitions can become hosted mocks through one command.

Script custom responses with apidog mock

Auto-generated mock data is useful for general cases. For specific request/response behavior, create mock expectations.

For example, you might need:

  • 200 OK for one user ID
  • 404 Not Found for another user ID
  • A specific response body for a particular request

The apidog mock command group manages these expectations. It is CRUD for hosted mock rules, not a server-start command.

List expectations for a project:

apidog mock --help
apidog mock list --project <PROJECT_ID>
Enter fullscreen mode Exit fullscreen mode

List expectations for a specific endpoint:

apidog mock list --project <PROJECT_ID> --http-api-id <ENDPOINT_ID>
Enter fullscreen mode Exit fullscreen mode

The CLI returns structured JSON, which you can filter with jq in scripts:

apidog mock list --project <PROJECT_ID> \
  | jq '.data'
Enter fullscreen mode Exit fullscreen mode

Read, update, or delete an expectation:

apidog mock get --project <PROJECT_ID>
apidog mock update --project <PROJECT_ID> --file ./mock.json
apidog mock delete --project <PROJECT_ID>
Enter fullscreen mode Exit fullscreen mode

The create and update commands accept a --file that describes the expectation.

Validate the expectation file before writing it

Do not guess the expected JSON shape. Use the CLI schema commands to retrieve and validate it before creating or updating an expectation.

apidog cli-schema get mock-create
apidog cli-schema validate mock-create --file ./mock.json
apidog mock create --project <PROJECT_ID> --file ./mock.json
Enter fullscreen mode Exit fullscreen mode

Use this sequence:

  1. Fetch the schema with cli-schema get.
  2. Create mock.json to match the schema.
  3. Validate the file.
  4. Create the expectation only after validation succeeds.

For updates, use the mock-update schema key:

apidog cli-schema get mock-update
apidog cli-schema validate mock-update --file ./mock.json
apidog mock update --project <PROJECT_ID> --file ./mock.json
Enter fullscreen mode Exit fullscreen mode

If validation returns a non-zero exit code, your pipeline stops before an invalid expectation reaches the project.

Commands return JSON with an agentHints.nextSteps block that indicates what to run next. This makes the workflow suitable for scripts and AI coding tools as well as interactive CLI usage. The complete Apidog CLI guide covers additional command groups.

Wiring it into CI

Both approaches work in CI because every command has an exit code and text output.

Run Prism during a test job

Start Prism in the background, run tests, then stop the process:

# Start Prism in the background, then run tests against it.
npx @stoplight/prism-cli mock ./openapi.yaml &
PRISM_PID=$!

npm test

kill $PRISM_PID
Enter fullscreen mode Exit fullscreen mode

In a production pipeline, ensure cleanup still runs when tests fail. For example:

npx @stoplight/prism-cli mock ./openapi.yaml &
PRISM_PID=$!

trap 'kill $PRISM_PID' EXIT

npm test
Enter fullscreen mode Exit fullscreen mode

Apply Apidog expectations during a test job

The Apidog workflow does not need a local server process because the mock is hosted. Validate and apply mock expectations as setup steps, then run tests against the hosted mock URL.

# Validate the expectation before applying it.
apidog cli-schema validate mock-create --file ./mock.json
apidog mock create --project <PROJECT_ID> --file ./mock.json
Enter fullscreen mode Exit fullscreen mode

The underlying goal is the same in both cases: no manual clicks. Your API spec, CI job, and AI coding agent can all reproduce the same mock behavior from the same commands.

Common snags

Expecting apidog mock to start a server.

It does not. There is no apidog mock start, apidog mock serve, or apidog mock ./file.yaml.

Use apidog import to import a spec and generate hosted mocks. Use apidog mock to manage custom expectations on those hosted mocks.

If you need a local process launched from a file, use Prism, Mockoon CLI, or json-server.

Skipping schema validation before a write.

apidog mock create and apidog mock update accept a --file. A wrong file shape can fail or create an expectation you did not intend.

Always run:

apidog cli-schema get mock-create
apidog cli-schema validate mock-create --file ./mock.json
Enter fullscreen mode Exit fullscreen mode

Prism returns unhelpful data because the spec is thin.

Prism can only use the examples and schemas in your OpenAPI definition. If responses have no examples and vague schemas, the generated mock data will also be vague.

Add explicit examples to improve the output:

responses:
  "200":
    description: Order found
    content:
      application/json:
        schema:
          type: object
          properties:
            id:
              type: string
            status:
              type: string
        example:
          id: "123"
          status: "paid"
Enter fullscreen mode Exit fullscreen mode

Expecting state from a stateless tool.

Prism and Apidog contract mocks do not persist writes. A POST followed by a GET will not automatically return the newly created record.

If you need persistent CRUD behavior, use json-server. Otherwise, create an Apidog expectation that returns the response shape your test requires.

Wrapping up

Mocking from the CLI turns a click-heavy task into commands you can script, review, run in CI, and hand to an agent.

Use the open-source route when you need a local mock from one file:

  • Prism for OpenAPI-based contract mocks
  • Mockoon CLI for headless Mockoon environments or OpenAPI files
  • json-server for instant stateful REST APIs from JSON

Use the Apidog route when you want hosted mocks that stay alongside your API design and tests. Import a spec once, then manage custom responses with apidog mock and validate every change with cli-schema.

Choose based on where the mock should live. For a quick local server, use the open-source tools. For an integrated project workflow, Download Apidog, install the CLI, and stand up mocks without touching a mouse.

Top comments (0)