Build API mocks with JavaScript
A mock is a code-based API simulator you build with custom JavaScript request handlers. Unlike mock servers created from a collection that return saved examples, mocks let you define exactly how requests are handled. Mocks can return dynamic responses, maintain state across requests, and simulate complex API behavior without calling real services. This makes them useful when dependencies are unavailable, still under development, or when static examples aren’t enough.
You can customize your mock using pm methods: use pm.mock to serve saved Postman examples, pm.state to persist data across requests, and pm.datasets to return query-driven responses. Start your mock locally to test during development, or deploy it as a mock server to run it in the Postman Cloud and make it always available to your team.
A mock can contain multiple scenarios. Each scenario has its own request handling code, endpoints, and conditions, so you can model different situations your API might encounter from a single mock.
Mocks are available in Local View for all plans, and in Cloud View for Solo, Team, and Enterprise plans. For more information, see the pricing page.
If you want to create a mock server from saved examples in a collection instead, see Deploy a mock server.
Create a mock
Before you create a mock in Local View, connect your Git project to your workspace using Native Git.
In the sidebar, click and select Mock. The mock is created and available in the
Items tab under Mocks in the sidebar.
If you’re in Local View, Postman generates files for your mock in your local Git repository. To learn more, see About the mock files.
After creating your mock, you can customize its behavior and settings:
- Customize your mock — Edit the JavaScript implementation to define how the mock handles requests and returns responses.
- Use pm methods in the mock editor — Use built-in objects like
pm.mockandpm.stateto serve saved examples and add stateful behavior. - Manage scenarios in a mock — Add named scenarios to model different situations your API might encounter, each with its own implementation and conditions.
- Configure a mock — Update settings like the mock’s name and port number.
About the mock files
In the Postman desktop app in Local View, Postman generates a folder for each mock in the postman/mocks/ directory in your local Git repository. The folder is named after the mock and contains:
config.yaml— A YAML file with the mock configuration and the list of scenarios. Each scenario entry includes its name, the path to its implementation file, and any conditions applied to it. The default scenario is marked withdefault: true.- A
<scenario-name>.jsfile for each scenario — A JavaScript file with that scenario’s request handling implementation. Endpoints are defined in the code using// @endpointcomments.
Any changes you make in Postman are reflected in these files, and updates to the files are reflected in Postman.
When working in Local View, make sure to commit the mock folder to your Git repository. This ensures your teammates get the latest mock files.
Use Agent Mode to create a mock
With Agent Mode, you can generate and modify mocks using prompts. It understands your workspace context and can create realistic mock behavior, including multi-step workflows and data that persists across requests.
In Local View, you can also use Agent Mode to generate a mock based on endpoints in your connected Git repository. Select More actions > Scan endpoints next to a mock in the sidebar.
The following are example prompts you can use to create and test different API behaviors with mocks.
Simulate request patterns and failures
Use this prompt to create a mock that introduces failures at specific intervals.
Simulate an authentication flow
Use this prompt to mock a basic login and authorization flow where access depends on prior requests.
Simulate CRUD behavior with memory
Use this prompt to create a mock service that stores and returns data across requests.
Simulate idempotent operations
Use this prompt to ensure repeated requests return consistent results instead of creating duplicates.
Simulate multi-step workflows
Use this prompt to model flows where later requests depend on earlier ones.
Simulate runtime configuration changes
Use this prompt to create a mock that reflects updates made during execution.
Simulate state-dependent failures
Use this prompt to create behavior that changes based on prior interactions with specific resources.
Simulate long-running processes
Use this prompt to model APIs that return different states over time.
Customize your mock
In Local View, define how your mock handles requests and returns responses. This is where you simulate the behavior of a real API. The implementation is stored in the <scenario-name>.js file. Each scenario has its own implementation, so you can customize how each one handles requests independently.
To customize your mock, do the following:
-
Click the
Items tab in the sidebar.
-
Click Mocks.
-
Select a mock you want to customize.
-
In the Code pane, update the implementation with your request handling logic.
Example:
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 mock implementation files. Click Packages to add packages to your mock. To learn more, see Import packages into Postman.
If you deployed your mock as a mock server, you can click Mock Server in the upper right to view it.
Within these handlers, you can:
- Use
pm.mockto serve responses from your saved examples. - Use
pm.stateto persist data across requests and enable stateful behavior. - Use
pm.datasetsto query datasets and use the data in your request handling logic. - Use
pm.testandpm.expectto add test assertions and validate request or response data.
Learn more about the pm objects available in the mock editor.
Push and pull mocks
You can push and pull mocks to and from the Postman cloud. You can push mocks to the Postman cloud to share them with your team. You can also pull mocks from the Postman cloud to your local workspace to start it locally.
Learn more about pushing and pulling changes in Postman.
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.
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 mocks.
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 mocks.
You can also learn how to view state behavior for your mock.
pm.datasets
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 mocks more dynamic and realistic. To learn more, see Manage and use datasets in scripts.
pm.test and pm.expect
The pm.test object enables you to define test assertions in your mock 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 logs. Learn more about writing tests using pm.test and pm.expect.
pm.environment
The pm.environment object provides access to variables in the active environment. To learn more, see Reference variables in Postman scripts.
pm.globals
The pm.globals object provides access to global variables at the workspace level. To learn more, see Reference variables in Postman scripts.
Manage scenarios in a mock
A scenario is a named version of your mock’s behavior. Each scenario has its own request handling code, its own set of endpoints, and its own conditions for simulating real-world behavior like delays and errors. Because all of a mock’s scenarios share the same mock URL, you can use scenarios to test different use cases against a single mock, such as a standard request flow and a degraded flow under heavy load, without creating a separate mock for each one.
A scenario has two layers that work independently:
- Code — The request handling logic that defines what the scenario does, including its endpoints, response bodies and status codes, and any stateful behavior. This is the functional behavior of the dependency you’re mocking. For example, one scenario might return a full list of items from an endpoint, while another returns an empty list.
- Conditions — Real-world faults layered on top of the code, like latency, errors, and rate limits. Conditions change how the scenario behaves under stress without changing what it returns. For example, you can add a delay to test how your service handles a slow dependency.
You can apply conditions to a scenario directly in the mock, or reuse a scenario in a simulation and override its conditions for a specific run. To learn more, see Apply a simulation to a mock.
Every mock starts with a default scenario. Scenarios appear as tabs in the mock editor. When you start the mock and send requests to it, it uses the default scenario’s code, endpoints, and conditions. To run a different scenario, add the mock to a simulation and select the scenario there.
Create a scenario
- Click the
Items tab in the sidebar.
- Click Mocks.
- Select the mock you want to add a scenario to.
- In the mock editor, click
Add new scenario next to the scenario tabs.
- Enter a name for the scenario.
The new scenario is based on the default scenario. In the Code pane, define the request handling logic for the scenario. Each scenario has its own code, so you can customize how it handles requests independently of other scenarios. To learn more, see Customize your mock.
To target a specific scenario in a request, include the x-mock-scenario: <scenario-name> header. In the Code pane, click Open in a new request next to the header key-value to open a new request with the header already filled in.
The default scenario
Click a scenario’s tab to view and edit its code and conditions. One scenario in the mock is the default, marked with default: true in the config.yaml file. When you start the mock directly, it uses the default scenario, including its conditions.
To run a specific scenario with simulated conditions applied, add the mock to a simulation and use the Select scenario dropdown list to choose the scenario you want. To learn more, see Create and run simulations in Postman.
Apply conditions to a scenario
Apply conditions to a scenario to introduce real-world disruptions like latency, errors, and rate limits. Conditions saved on a scenario are its permanent failure profile. They define what the scenario represents, such as a slow dependency or a service returning errors, and can be reused across tests. Conditions are available when you add the scenario to a simulation, where you can override them for a specific run without changing the scenario itself. To test how your service responds when multiple dependencies fail at the same time, use a simulation to coordinate multiple mocks together.
-
Click the scenario tab you want to apply conditions to.
-
In the mock editor toolbar, click
Configure.
-
Turn on each condition you want to apply, then enter a value where required:
- Simulate error response — Return a specified HTTP status code.
- Add response delay — Add a delay in milliseconds before the scenario sends a response, simulating network latency.
- Simulate rate limiting — Limit the scenario to a maximum number of requests per minute.
- Chaos mode — Randomly fail a percentage of requests with 5xx status codes.
The scenario shows how many conditions are applied, along with the value for each, such as 2000 ms.
To learn how a scenario’s conditions are reused and overridden in a simulation, see Create and run simulations in Postman.
Configure a mock
Configure your mock to control how it runs on your machine, such as the port number and restart behavior. To configure a deployed mock server, see Configure a deployed mock server.
-
Click the
Items tab in the sidebar.
-
Click Mocks.
-
Select the mock you want to configure.
-
In the upper right of the editor, select
> Edit.
-
You can configure the following details:
- Name — The name of the mock.
- Port — The local port number for the mock. If the specified port is already in use, the mock falls back to an available port assigned by the OS.
- Auto-restart on change — By default, mocks restart when the handler or configuration changes. Deselect the checkbox to turn off this behavior.
-
Click Save.
Deploy a mock as a mock server
Deploy a mock as a mock server to run it in the Postman cloud. Unlike a local 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 mock as a mock server is supported in Cloud View for Solo, Team, and Enterprise plans only.
- Click the
Items tab in the sidebar.
- Click Mocks.
- Select the mock.
- In the upper right, click Deploy.
- (Optional) Customize the URL for your mock server. The customized URL must be unique and can only have lowercase letters, numbers, and hyphens.
- (Optional) Select the Allow public access checkbox to allow anyone with the mock server URL to send requests to the mock server. To learn more, see Allow public access.
- (Optional) By default, 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.
- (Optional) Select Auto deploy when mock changes to automatically redeploy the mock server when you make changes to the mock.
- Click Deploy.
The mock server is automatically running once it’s deployed. To send requests to it and inspect its activity, see Call a mock server deployed from a mock.
Make calls to a mock
You can send requests to a mock in Local View or to a deployed mock server in Cloud View. To learn more, see Make calls to mock servers.
- In Local View, you can start a mock locally and send HTTP requests to it at
http://localhost:<port>. See Send local requests to a mock. - In Cloud View, you can send requests to the deployed mock server URL. See Send requests to a deployed mock server.
You can also view requests, responses, and state information in the Logs and State tabs. See Inspect mock activity.
Apply a simulation to a mock
Apply a simulation to a mock to introduce real-world conditions like latency, errors, and rate limits. When you add a mock to a simulation, you select which scenario to use and can override that scenario’s conditions for the simulation, without changing the scenario itself. 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 mock, select More actions > Simulate in the upper right to create or open a simulation.
To learn more, see Create and run simulations in Postman.