# Run the mock server

Source: https://watership.ca/api-docs/docs/tasks/run-the-mock-server

Start a local mock of the API from the spec, choose which response it sends, and see why it rejected a request.

The mock server is [Prism](https://stoplight.io/open-source/prism), an open-source tool that serves an API from its OpenAPI file. It validates each request against the spec and answers with the examples in it. Use it to try the API before the hosted service exists, and to test your own client code.

## Start it [#start-it]

From the repository folder:

```sh
npm install
npm run mock
```

The mock listens on `http://127.0.0.1:4010`. To use another port, pass it after `--`:

```sh
npm run mock -- --port 8080
```

Prism needs Node.js 24.18 or later. The repository's `.nvmrc` names the version, so with a version manager such as nvm, run `nvm use` first.

## Get a particular response [#get-a-particular-response]

By default, the mock responds with the first success example for the endpoint. To get a different response, send a `Prefer` header:

| To get | Send |
|---|---|
| A particular status code | `Prefer: code=429` |
| A particular named example | `Prefer: example=textTooLong` |
| Both | `Prefer: code=400, example=textTooLong` |

For example, to see a rate-limit response:

```sh
curl -i http://127.0.0.1:4010/v1/rules \
  -H "Authorization: Bearer wsk_test_example" \
  -H "Prefer: code=429"
```

The example names are in the spec, under each response's `examples`. The [errors reference](https://watership.ca/api-docs/docs/reference/errors) lists the ones for each problem type.

## Find out why a request was rejected [#find-out-why-a-request-was-rejected]

When a request breaks the spec, the mock responds with the status code the spec gives for it, usually `400`. The body is always the first example for that status, so it may not describe your mistake. The real reason is in the `sl-violations` response header:

```sh
curl -i http://127.0.0.1:4010/v1/checks \
  -H "Authorization: Bearer wsk_test_example" \
  -H "Content-Type: application/json" \
  -d '{}'
```

```txt
HTTP/1.1 400 Bad Request
sl-violations: [{"location":["request","body"],"severity":"Error","code":"required","message":"Request body must have required property 'text'"}]
```

## Know what the mock can't do [#know-what-the-mock-cant-do]

The mock serves the spec, not the service behind it. It:

- Responds with the same example whatever text you send to `POST /v1/checks`
- Responds with the same rule, term, or voice whatever id you ask for, so it never responds with `404` on its own
- Doesn't count requests, so it never responds with `429` on its own
- Accepts any API key, and rejects only a request with no `Authorization` header

To test how your code handles one of these cases, ask for it with a `Prefer` header.
