> For clean Markdown content of this page, append .md to this URL. For the complete documentation index, see https://learning.postman.com/llms.txt.

# Simulate APIs with code mock servers

With a *code mock*, you can simulate a real API using custom JavaScript request handlers and response logic while developing and testing your APIs. Unlike [classic mock servers](/docs/design-apis/mock-apis/set-up-mock-servers) that return saved examples from a collection, code mocks support dynamic responses, stateful behavior, and custom request handling logic. This makes them useful when dependencies are unavailable, still under development, or before deploying your APIs to the Postman cloud.

You can create a code mock from a template, a collection, or an API specification, or by using Agent Mode. Then you can start a code mock locally, or deploy a code mock to a mock server. Send requests to the code mock to simulate API responses based on the request and response logic defined in your implementation, and view logs for requests the code mock handles.

Code mocks are available in Local View for all plans, and they're available in Cloud View as a beta feature.

## Create a code mock

To get started, you can create a code mock from a template that includes a basic HTTP server implementation. You can also create a code mock based on a collection or API specification, giving you a starting point that reflects your API design.

Before you create a code mock in Local View, [connect your Git project to your workspace](/docs/use/native-git/overview/#connect-your-git-project-to-your-workspace) using Native Git.

To create a code mock, do the following:

1. Choose one of the following:

   * In Local View, click <img alt="Add icon" src="https://assets.postman.com/postman-docs/aether-icons/v12/action-add-stroke.svg#icon" width="20px" /> in the sidebar and select **Mock**.
   * In Cloud View, click <img alt="Add icon" src="https://assets.postman.com/postman-docs/aether-icons/v12/action-add-stroke.svg#icon" width="20px" /> in the sidebar and select **Mock Server > Mock**.

2. Enter a name for your code mock.

3. (Optional) Customize the port number for your code mock. The default port number is `3001`.

4. Choose the source for your code mock:

   * **Start with a template** — Create a code mock from a template with a basic HTTP server you can customize.
   * **Use a collection** — Create a code mock based on a collection. You can upload a file or drag and drop it from the left sidebar.
   * **Use a specification** — Create a code mock based on an API specification. You can upload a file or drag and drop it from the left sidebar.

5. (Optional) If you selected a collection or specification as the source, you can select the checkbox to keep the source synced with your code mock. Any changes you make to the collection or specification are reflected in the mock behavior. It's recommended that you avoid making manual changes to the code mock. You can identify a code mock in the sidebar that's synced with a collection or specification by the sync icon <img alt="Synced icon" src="https://assets.postman.com/postman-docs/aether-icons/v12/icon-state-synced-stroke.svg#icon" width="20px" />.

6. (Optional) Use [Agent Mode](/docs/use/agent-mode/overview/) to quickly create a code mock based on endpoints in your connected Git repository, if you're in Local View. You can also describe the API behavior you want to mock, and Agent Mode generates a code mock for you.

7. Click **Create Mock**.

When you create a code mock, it's available in the <img alt="Items icon" src="https://assets.postman.com/postman-docs/aether-icons/v12/descriptive-items-stroke.svg#icon" width="20px" /> **Items** tab under **Mocks** in the sidebar.

### About the code mock files

In the Postman desktop app in Local View, Postman generates two files in the `postman/mocks/` directory in your local Git repository:

* `<code-mock-name>.js` — A JavaScript file that contains the [mock server implementation](#customize-your-code-mock). Define the request and response logic for simulating real API behavior.
* `<code-mock-name>.json` — A JSON file that contains the [mock server configuration](#configure-code-mock-details), such as the port number and routes. Any changes you make to the configuration are reflected in this file, and updates to the file are reflected in Postman.

When working in Local View, make sure to commit the JavaScript implementation file and JSON configuration file to your Git repository. This ensures your teammates get the latest code mock files.

## Customize your code mock

In Local View, define how your code mock handles requests and returns responses. This is where you simulate the behavior of a real API. In Local View, this is stored in the `mock-server-name.js` implementation file. Code mocks are read-only in Cloud View.

To customize your code mock in Local View, do the following:

1. Click the <img alt="Items icon" src="https://assets.postman.com/postman-docs/aether-icons/v12/descriptive-items-stroke.svg#icon" width="20px" /> **Items** tab in the sidebar.
2. Click **Mocks**.
3. Select a code mock you want to customize.
4. In the **Code** pane, update the implementation with your request handling logic.

   Example:

   ```js
   const http = require("http");

   const server = http.createServer((req, res) => {
       if (pm.mock.matchRequest('<request-path>', req)) {
           return pm.mock.sendExample('<example-path>', res);
       }

   ...
   });
   ```

Code mocks are implemented using custom request handlers. You can use standard HTTP server patterns to control how requests are handled. For example, you can add conditionals, generate dynamic data, or implement any valid JavaScript logic.

Packages from the Postman Package Library and external registries are supported in code mock implementation files. Click <img alt="Package icon" src="https://assets.postman.com/postman-docs/aether-icons/v12/icon-entity-package-stroke.svg#icon" width="20px" /> **Packages** to add packages to your code mock. To learn more, see [Import packages into Postman](/docs/tests-and-scripts/write-scripts/packages/overview).

If you [deployed your code mock to a mock server](#deploy-a-code-mock-as-a-mock-server), you can click **Mock Server** in the upper right to view it.

Within these handlers, you can:

* Use `pm.mock` to serve responses from your saved examples.
* Use `pm.state` to persist data across requests and enable stateful behavior.
* Use `pm.datasets` to query datasets and use the data in your request handling logic.
* Use `pm.test` and `pm.expect` to add test assertions and validate request or response data.

Learn more about the [`pm` objects available in the mock editor](#use-pm-methods-in-the-mock-editor).

### Push and pull code mocks

You can push and pull code mocks to and from the Postman cloud. Code mocks are read-only in Cloud View, so you need to push them to the Postman cloud to share them with your team. You can also pull code mocks from the Postman cloud to your local workspace to make changes.

Learn more about [pushing and pulling changes in Postman](/docs/use/native-git/collaborate#push-and-pull-changes-in-postman).

## Use Agent Mode with code mocks

With Agent Mode, you can generate and modify code mocks using prompts. It understands your workspace context and can create realistic mock behavior, including multi-step workflows and data that persists across requests.

The following are example prompts you can use to create and test different API behaviors with code mocks.

In Local View, you can also use Agent Mode to generate a code mock based on endpoints in your connected Git repository. Select <img alt="Options icon" src="https://assets.postman.com/postman-docs/aether-icons/v12/action-options-stroke.svg#icon" width="20px" /> **More actions > Scan endpoints** next to a code mock in the sidebar.

### Simulate request patterns and failures

Use this prompt to create a code mock that introduces failures at specific intervals.

```text wordWrap
Create a mock for a payments API where every third request to /charge fails with 500, and a successful one after that. It should remember attempts across requests.
```

### Simulate an authentication flow

Use this prompt to mock a basic login and authorization flow where access depends on prior requests.

```text wordWrap
Mock a simple auth service locally: POST /login returns a token, GET /me only works if the last login token is sent, else 401.
```

### Simulate CRUD behavior with memory

Use this prompt to create a mock service that stores and returns data across requests.

```text wordWrap
Set up a mock cart service: POST /cart adds an item, GET /cart returns everything added so far, DELETE /cart clears it. It should remember items between requests.
```

### Simulate idempotent operations

Use this prompt to ensure repeated requests return consistent results instead of creating duplicates.

```text wordWrap
Mock an orders API where posting the same orderId twice returns the same response instead of creating a new one.
```

### Simulate multi-step workflows

Use this prompt to model flows where later requests depend on earlier ones.

```text wordWrap
I'm testing a 2-step OTP flow. Create a mock: POST /otp/send generates a code, POST /otp/verify only succeeds if the code from the previous call is sent back.
```

### Simulate runtime configuration changes

Use this prompt to create a mock that reflects updates made during execution.

```text wordWrap
Create a mock for a feature flags service: PUT /flags/:name to turn a flag on/off, and GET /flags/:name reflects the latest value across requests.
```

### Simulate state-dependent failures

Use this prompt to create behavior that changes based on prior interactions with specific resources.

```text wordWrap
Mock the inventory service locally: the first call to /reserve/:sku succeeds, subsequent calls for the same SKU return 409 already reserved until I call /release/:sku.
```

### Simulate long-running processes

Use this prompt to model APIs that return different states over time.

```text wordWrap
Create a mock for a job API: POST /jobs starts one, GET /jobs/:id returns pending first, then running, then done across polls.
```

## Use pm methods in the mock editor

You can use some `pm` objects in the mock editor the same way you use them in [scripts](/docs/tests-and-scripts/write-scripts/postman-sandbox-reference/overview/).

### pm.mock

Postman provides an object called `pm.mock` that's available in the mocks sandbox environment. It gives you structured, Postman-aware functions for matching incoming requests and sending responses. This includes the ability to serve responses from your existing saved Postman examples rather than hard-coding everything. To learn more, see [Reference requests and examples in code mocks](/docs/tests-and-scripts/write-scripts/postman-sandbox-reference/pm-mock/).

### pm.state

The `pm.state` object is available as a beta feature.

Postman provides an object called `pm.state` that's available in the mocks sandbox environment. It provides a persistent store for managing data across requests, enabling your mock to behave like a real service instead of returning static responses. State persists across runs until it's cleared using `pm.state.clear()`. To learn more, see [Persist state across requests in code mocks](/docs/tests-and-scripts/write-scripts/postman-sandbox-reference/pm-state/).

You can also learn how to [view state behavior](#view-state) for your code mock.

### pm.datasets

The `pm.datasets` function is available as a beta feature.

Postman provides a function called `pm.datasets` that enables you to access datasets and run SQL queries against them. You can run predefined views or custom queries to retrieve structured data at runtime. This enables you to use persistent, queryable data across requests, making your mock servers more dynamic and realistic. To learn more, see [Manage and use datasets in scripts](/docs/tests-and-scripts/write-scripts/postman-sandbox-reference/pm-datasets/).

### pm.test and pm.expect

The `pm.test` object enables you to define test assertions in your mock server implementation file. You can use it with `pm.expect`, which provides Chai-style expectations for validating request headers, body content, status codes, or custom variables. Test results (pass, fail, or skip) are recorded and surfaced in mock server logs. Learn more about [writing tests using pm.test and pm.expect](/docs/tests-and-scripts/write-scripts/postman-sandbox-reference/pm-test-expect).

### pm.environment

The `pm.environment` object provides access to variables in the active environment. To learn more, see [Reference variables in Postman scripts](/docs/tests-and-scripts/write-scripts/postman-sandbox-reference/pm-variables#pmenvironment).

### pm.globals

The `pm.globals` object provides access to global variables at the workspace level. To learn more, see [Reference variables in Postman scripts](/docs/tests-and-scripts/write-scripts/postman-sandbox-reference/pm-variables#pmglobals).

## Send local requests to a code mock

In Local View and Cloud View, you can send local requests to a code mock using an HTTP request. Then you can observe the responses to validate that your mock server behaves as expected. The URL is `http://localhost:<port>` where the port number is specified in your [code mock configuration](#configure-code-mock-details). You can manually start and stop the mock server to control when it listens for requests.

In Cloud View, you can also [deploy a code mock as a mock server](#deploy-a-code-mock-as-a-mock-server).

1. Click the <img alt="Items icon" src="https://assets.postman.com/postman-docs/aether-icons/v12/descriptive-items-stroke.svg#icon" width="20px" /> **Items** tab in the sidebar.
2. Click **Mocks**.
3. Select the code mock.
4. Click **Start** in the upper right. You can also select <img alt="Options icon" src="https://assets.postman.com/postman-docs/aether-icons/v12/action-options-stroke.svg#icon" width="20px" /> **More actions > Run locally** next to a code mock in the sidebar.
5. In the upper right, click <img alt="Open in Postman icon" src="https://assets.postman.com/postman-docs/aether-icons/v12/icon-action-openInPostman-stroke.svg#icon" width="20px" /> **Open in a new request** to open a new request with the URL auto-filled. You can also click <img alt="Copy icon" src="https://assets.postman.com/postman-docs/aether-icons/v12/icon-action-copy-stroke.svg#icon" width="20px" /> **Copy URL** to copy the URL and use it in an HTTP request.
6. Send requests to the URL and observe the responses, simulating a real API.

Click **Stop** in the upper right to stop the code mock.

## Deploy a code mock as a mock server

Deploy a code mock as a mock server to run it in the Postman cloud. Unlike a local code mock that you start and stop manually, a deployed mock server is always running, so anyone with access can send requests to it at any time. Deploying a code mock as a mock server is only supported in Cloud View for paid plans.

1. Click the <img alt="Items icon" src="https://assets.postman.com/postman-docs/aether-icons/v12/descriptive-items-stroke.svg#icon" width="20px" /> **Items** tab in the sidebar.
2. Click **Mocks**.
3. Select the code mock.
4. In the upper right, click **Deploy as Mock Server**.
5. (Optional) Customize the URL for your code mock server. The customized URL must be unique and can only have lowercase letters, numbers, and hyphens.
6. (Optional) Select the **Make this mock public** checkbox to allow anyone with the mock server URL to send requests to the mock server. To learn more, see [Make a code mock server public](#make-a-code-mock-server-public).
7. (Optional) By default, code mock servers maintain separate state for each session. If you want to share a single state store across all requests, clear the **Enable sessions** checkbox. To learn more, see [State sessions](#state-sessions).
8. (Optional) Select **Auto-deploy on every change** to automatically redeploy the mock server when you make changes to the code mock.
9. Click **Deploy**.

The mock server is automatically running once it's deployed. Learn how to [send requests to a deployed mock server](#send-requests-to-a-deployed-mock-server).

### Make a code mock server public

In Cloud View, code mock servers are private by default. Private code mock servers can only be accessed by workspace members or callers that include a valid `x-api-key` header with a [Postman API key](/docs/reference/postman-api/authentication#generate-a-postman-api-key).

To allow anyone with the mock server URL to send requests to the code mock server, select **Make this mock public** when creating or editing the code mock server.

On Team and Enterprise plans, your team may require Team Admin approval before a code mock server can be made public. If approval is required, your request will be submitted for review and the code mock server will remain private until it's approved.

Learn how a Team Admin can [manage whether public code mock servers require approval](/docs/administration/managing-your-team/manage-team-workspaces#manage-mock-servers).

### State sessions

By default, all requests to a code mock share the same state store when using `pm.state`. When you enable sessions, each session gets its own isolated copy of state.

Use state sessions to simulate multiple users, run parallel tests, or test stateful workflows without requests affecting each other's data. Identify a session using the `x-mock-session` header. In Cloud View, Postman can also use a `pm_mock_session` cookie to maintain a session across requests automatically.

To learn more about `pm.state`, see [Use pm methods in the mock editor](#use-pm-methods-in-the-mock-editor).

## Send requests to a deployed mock server

After you [deploy a code mock as a mock server](#deploy-a-code-mock-as-a-mock-server), you can send requests to the mock server URL using an HTTP request in Cloud View. Then you can observe the responses to validate that your mock server behaves as expected. Code mock servers listen for incoming requests and return responses based on the logic you defined in the implementation. Deploying a code mock as a mock server is only supported in Cloud View for paid plans.

1. Click the <img alt="Services icon" src="https://assets.postman.com/postman-docs/aether-icons/v12/icon-descriptive-services-stroke.svg#icon" width="20px" /> **Services** tab in the sidebar.
2. Click **Mock Servers**.
3. Select the code mock server. You can identify a code mock server by the code icon <img alt="Code icon" src="https://assets.postman.com/postman-docs/aether-icons/v12/icon-descriptive-code-stroke.svg#icon" width="20px" />.
4. In the upper right, click <img alt="Open in Postman icon" src="https://assets.postman.com/postman-docs/aether-icons/v12/icon-action-openInPostman-stroke.svg#icon" width="20px" /> **Open in a new request** to open a new request with the URL auto-filled. You can also click <img alt="Copy icon" src="https://assets.postman.com/postman-docs/aether-icons/v12/icon-action-copy-stroke.svg#icon" width="20px" /> **Copy URL** to copy the URL and use it in an HTTP request.
5. Send requests to the URL and observe the responses, simulating a real API.

   * If the code mock server is private, you must either have access to the workspace or include a valid `x-api-key` header with a [Postman API key](/docs/reference/postman-api/authentication#generate-a-postman-api-key).
   * If the code mock server is public, anyone with the mock server URL can send requests to it.

In the upper right, you can click <img alt="Code icon" src="https://assets.postman.com/postman-docs/aether-icons/v12/icon-descriptive-code-stroke.svg#icon" width="20px" /> **View Mock** to view the [code mock implementation](#customize-your-code-mock).

## Configure code mock details

Configure a local code mock to control how it runs on your machine, such as the port number, source, and restart behavior. If you've [deployed a code mock as a mock server](#deploy-a-code-mock-as-a-mock-server), you can configure it separately to control how it's available in the Postman cloud, such as the URL, access settings, and session behavior.

### Configure a local code mock

1. Click the <img alt="Items icon" src="https://assets.postman.com/postman-docs/aether-icons/v12/descriptive-items-stroke.svg#icon" width="20px" /> **Items** tab in the sidebar.

2. Click **Mocks**.

3. Select the code mock you want to configure.

4. In the upper right of the editor, select <img alt="Options icon" src="https://assets.postman.com/postman-docs/aether-icons/v12/icon-action-options-stroke.svg#icon" width="20px" /> > **Edit configuration**.

5. You can configure the following details:

   * **Name** — The name of the code mock.
   * **Local URL** — The local port number for the code mock.
   * **Source** — The source for the code mock, either a collection or an API specification. You can also choose whether to keep the source synced with the code mock.
   * **Auto-restart on change** — By default, code mocks restart when the handler or configuration changes. Deselect the checkbox to turn off this behavior.
   * **Enable CORS** — By default, code mocks allow Cross-Origin Resource Sharing (CORS). Deselect the checkbox to turn off this behavior.

6. Click **Save**.

### Configure a deployed mock server

1. Click the <img alt="Services icon" src="https://assets.postman.com/postman-docs/aether-icons/v12/icon-descriptive-services-stroke.svg#icon" width="20px" /> **Services** tab in the sidebar.

2. Click **Mock Servers**.

3. Select the code mock server you want to configure.

4. In the upper right of the editor, select <img alt="Options icon" src="https://assets.postman.com/postman-docs/aether-icons/v12/icon-action-options-stroke.svg#icon" width="20px" /> > **Edit configuration**.

5. You can configure the following details:

   * **URL** — The unique URL for the mock server. It can only have lowercase letters, numbers, and hyphens.
   * **Make this mock public** — Allow anyone with the mock server URL to send requests to it. On Team and Enterprise plans, this may require Team Admin approval.
   * **Enable sessions** — When turned on, each session gets its own isolated copy of state. When turned off, all requests share a single state store.
   * **Auto-deploy on every change** — Automatically redeploy the mock server when you make changes to the code mock.

6. Click **Save**.

## Apply a simulation to a code mock

Apply a simulation to a code mock to introduce real-world conditions like latency, errors, and rate limits. This enables you to observe how your service behaves under stress and performance constraints, so you can address issues before deploying to staging or production.

From a code mock, you can click <img alt="Stroke icon" src="https://assets.postman.com/postman-docs/aether-icons/v12/icon-simulator-stroke.svg#icon" width="20px" /> **Simulate** in the upper right to create or update a simulation.

To learn more, see [Simulate real-world conditions in Postman](/docs/design-apis/simulate-conditions).

## Inspect code mock activity

View requests, responses, and state information for your code mock. You can inspect a local code mock in Local View and Cloud View. If you've [deployed a code mock as a mock server](#deploy-a-code-mock-as-a-mock-server), you can also inspect it in Cloud View.

1. Choose one of the following:

   * **Inspect a local code mock** — Click the <img alt="Items icon" src="https://assets.postman.com/postman-docs/aether-icons/v12/descriptive-items-stroke.svg#icon" width="20px" /> **Items** tab in the sidebar, click **Mocks**, then select a code mock.
   * **Inspect a deployed mock server** — Click the <img alt="Services icon" src="https://assets.postman.com/postman-docs/aether-icons/v12/icon-descriptive-services-stroke.svg#icon" width="20px" /> **Services** tab in the sidebar, click **Mock Servers**, then select a code mock server.

2. Use the **Session** dropdown list to inspect a specific state session. Requests that use the same session identifier share state and display together.

3. Use the **Logs** and **State** tabs to inspect requests, responses, and state information for the code mock.

### View logs

View incoming requests, responses, and state operations in the **Logs** tab.

You can filter logs by path, type, method, status, time range, and header to focus on specific requests and responses. For example, you can filter by a specific endpoint to see all requests made to that endpoint and the corresponding responses.

Select a log entry to view more details about the request and response, including headers and body content.

Logs with the simulator icon <img alt="Stroke icon" src="https://assets.postman.com/postman-docs/aether-icons/v12/icon-simulator-stroke.svg#icon" width="20px" /> indicate requests that ran with a simulation applied.

Click <img alt="Delete icon" src="https://assets.postman.com/postman-docs/aether-icons/v12/action-delete-stroke.svg#icon" width="20px" /> **Clear logs** to remove all logs for the code mock.

### View state

If your code mock uses `pm.state`, you can inspect the current state values for the selected session in the **State** tab.

State entries are displayed as key-value pairs. Expand a state entry to view its contents and inspect how requests have modified state over time.

Click <img alt="Delete icon" src="https://assets.postman.com/postman-docs/aether-icons/v12/action-delete-stroke.svg#icon" width="20px" /> **Clear session** to remove all state values for the selected session.