# In-Browser Mock

> Answer API requests inside the page from your OpenAPI spec with the mock-server attribute, with no server to run.

Add `mock-server="true"` to `<rapi-doc>` or `<rapi-doc-mini>` and requests to your API are answered in the page, from the spec's examples and schemas. Nothing is deployed and nothing leaves the browser. Readers can press **Try** on a published page and get a sensible answer, and you can build and demo a frontend before the backend exists.

> **Tip: See it running**
> The [in-browser mock example](/examples/mock-server) has a live testbed: pick a status code and a delay, and call the API. For a real HTTP server that any client can call, with request validation and token checks, see [RapiMock](https://mock.rapidocui.com/); [In the page or as a server](#in-the-page-or-as-a-server) compares the two.

## Turn it on

```html
<rapi-doc
  spec-url="https://rapidocui.com/specs/petstore.yaml"
  mock-server="true"
></rapi-doc>
```

`<rapi-doc>` then shows a pulsing dot and a **MOCKING** label in its API Server section.

The mock patches the page's `fetch` and `XMLHttpRequest`. A request whose method and path match an operation in the spec is answered by the mock; every other request (analytics, images, other APIs) goes to the network as usual. That means it answers not only **Try**, but any script on the same page:

```javascript
const doc = document.querySelector('rapi-doc');
doc.addEventListener('spec-loaded', () => {
  // The mock starts right after spec-loaded, so call it on the next tick
  setTimeout(async () => {
    const res = await fetch('https://petstore3.swagger.io/api/v3/pet/findByStatus?status=available');
    console.log(await res.json()); // from the spec, not the real API
  });
});
```

Only operations that `<rapi-doc>` shows are mocked: endpoints left out by a `<rapi-doc-mini>` filter, for example, go to the network.

## Attributes

| Attribute | Default | Meaning |
| :--- | :--- | :--- |
| `mock-server` | `false` | `true` turns the mock on. Setting it back to `false` turns it off. |
| `mock-server-status-code` | `200` | The status code to answer with, a comma-separated list used in turn (`"503, 503, 200"`), the same with a strategy in front (`"random:200, 500"`), or a JSON map by operation (see below). Set it to `""` to use the first `2xx` response in the spec (else `default`, else the first response listed). |
| `mock-server-delay` | `0` | Milliseconds to wait before answering, to show loading states. For a streamed response, the gap between its items (300 ms when `0`). |
| `mock-server-log` | `false` | `true` logs each answered request to the browser console. |

## Simulating errors

Give `mock-server-status-code` several codes, with the strategy in front of them when it isn't `cycle`:

```html
<rapi-doc
  spec-url="/specs/api.yaml"
  mock-server="true"
  mock-server-status-code="503, 503, 200"
></rapi-doc>
```

<Tabs>
  <TabItem label="cycle (default)">
    `503, 503, 200` or `cycle:503, 503, 200`. Each operation steps through the list in turn: the first call gets `503`, the second `503`, the third `200`, and then it starts again. Use it to test retries and error messages.
  </TabItem>
  <TabItem label="random">
    `random:200, 429, 503`. Every call gets a code picked at random from the list. Use it to check that the UI copes with failures it doesn't expect.
  </TabItem>
  <TabItem label="one code">
    `401`. Every call gets it, which shows how a page behaves when the user is signed out. (`first:` exists for older pages; one code does the same.)
  </TabItem>
</Tabs>

Each operation's place in its list starts again whenever the codes change. A list without a prefix is used in turn; write `random:` or `first:` in front of it for another strategy (the `mock-server-status-strategy` attribute was [removed in v15](/docs/rapidoc/migration/v14-to-v15/)).

### Per-operation status codes

To make one operation fail while the others succeed, pass a JSON map. Keys are the method and path template from the spec; `"*"` applies to every other operation. Each entry has its own list and its own strategy, and a list cycles for that operation only:

```html
<rapi-doc
  spec-url="/specs/petstore.yaml"
  mock-server="true"
  mock-server-status-code='{ "POST /store/order": "503, 200", "GET /store/inventory": "random:200, 500", "*": "200" }'
></rapi-doc>
```

The same value can be set as an object on the `mockServerStatusCode` property. [`<rapi-flow>`](https://flow.rapidocui.com/docs/running/#running-against-a-mock) sets it from its Mock Response Status table for the length of a run.

## What the mock answers

For the chosen status code, the mock builds the response from the spec's response object:

1. **Body**: the media type's `example`; else the first entry of its `examples`; else the schema's `example`; else a value generated from the schema. Generated values use `enum`, `default`, `minimum`/`maximum`, `pattern` and `format` where they can (`user@example.com` for `email`, a UUID for `uuid`), and `writeOnly` properties are left out. JSON is preferred over XML, and XML over text.
2. **No body in the spec**: JSON responses get `{ "status": <code>, "message": "<status text>" }`, other types get the status text, and `204` gets an empty body.
3. **Headers**: response headers from the spec, filled from their `example` or schema `default`, plus `Access-Control-Allow-Origin: *` and `X-Mock-Server: RapiDoc`.
4. **Streams** (an OpenAPI 3.2 `itemSchema` on `text/event-stream`, JSON Lines or `application/json-seq`): the response starts at once and sends one item at a time, `mock-server-delay` apart (300 ms when `0`), so **Try** shows it arriving and its **STOP** button can end it. The items are those of the first example (a `dataValue` list, or the stream's text split into events or lines); without one, an item generated from the `itemSchema` is sent 5 times, its `id` numbered 1 to 5. Through `XMLHttpRequest` the whole stream comes at once.

## Mocking your app during development

Because the mock patches the page's `fetch`, your own frontend code in the same page is answered too. Add a hidden `<rapi-doc>` while you develop:

```html title="index.html"
<script type="module" src="https://unpkg.com/rapidoc/dist/rapidoc-min.js"></script>
<rapi-doc spec-url="/openapi.yaml" mock-server="true" mock-server-delay="200" style="display: none"></rapi-doc>
<div id="root"></div>
```

```javascript
// Anywhere in your app: answered from openapi.yaml, no backend needed
const user = await fetch('/api/v1/users/me').then((res) => res.json());
```

Matched requests never reach the network, so cross-origin (CORS) rules don't get in the way. For calls from other programs, or from a different page, use the [mock server](https://mock.rapidocui.com/) instead.

## Console log

With `mock-server-log="true"`, every answered request prints one line:

```text
[RapiDoc Mock] GET /users/42 ➔ 200 OK
```

Requests made with `XMLHttpRequest` are tagged `[RapiDoc Mock (XHR)]`.

## Several mocks on one page

Each element with `mock-server="true"` mocks its own spec with its own status codes and delay, so one page can mock two APIs:

```html
<rapi-doc-mini spec-url="/specs/orders.yaml" mock-server="true" filter-operations="POST /orders"></rapi-doc-mini>
<rapi-doc-mini spec-url="/specs/payments.yaml" mock-server="true" mock-server-status-code="402"></rapi-doc-mini>
```

A request goes to the most specific match: a route under the request's server origin and base path wins over the same path under another API's base path, which wins over a bare path.

When an element turns its mock off or is removed from the page, its routes stop being answered. The page's real `fetch` and `XMLHttpRequest` come back when no element is mocking any more.

## In the page or as a server

The in-browser mock answers code running in the same page: **Try**, `<rapi-flow>` and the page's own scripts. [RapiMock](https://mock.rapidocui.com/), RapiDoc's mock server (`rapidoc mock`), answers any client over HTTP.

| | In-browser mock | RapiMock |
| :--- | :--- | :--- |
| **How you turn it on** | `mock-server="true"` on `<rapi-doc>` or `<rapi-doc-mini>` | `npx rapidoc mock openapi.yaml` |
| **Runs** | Inside the page, by intercepting `fetch` | As a Node HTTP server (default port `4010`) |
| **Who can call it** | Code running in the same page | Any client: curl, your frontend, tests, MCP servers |
| **Choosing a status code** | `mock-server-status-code`, per operation if needed | `Prefer: code=…` request header |
| **Request validation, token and scope checks** | No | Yes |
| **Remembers what you create** | No: every call is answered on its own | Yes, with `--stateful` |

**Pick the in-browser mock** for docs and demos: readers can press **Try** on a published page and get a sensible answer, with nothing to deploy. **Pick RapiMock** for development and testing: when other programs need to call the API, when requests and tokens should be checked the way production checks them, or when a test has to create something and read it back. Its [quickstart](https://mock.rapidocui.com/docs/getting-started/quickstart/) starts one in a minute, and [Testing with RapiDoc](https://mock.rapidocui.com/docs/testing/with-rapidoc/) points `<rapi-doc>` at it.
