> For clean Markdown content of this page, append .md to this URL. For the complete documentation index, see https://learning.postman.com/llms.txt. For full content including API reference and SDK examples, see https://learning.postman.com/llms-full.txt.

# Create a mock server

POST https://api.getpostman.com/mocks
Content-Type: application/json

Creates a mock server in a collection.

**Note:**

- You cannot create mocks for collections added to an API definition.
- If you do not include the `workspaceId` query parameter, the system creates the mock server in the oldest personal Internal workspace you own.


Reference: https://learning.postman.com/api-docs/api-reference/mocks/create-mock

## OpenAPI Specification

```yaml
openapi: 3.1.0
info:
  title: Postman API
  version: 1.0.0
paths:
  /mocks:
    post:
      operationId: createMock
      summary: Create a mock server
      description: >
        Creates a mock server in a collection.


        **Note:**


        - You cannot create mocks for collections added to an API definition.

        - If you do not include the `workspaceId` query parameter, the system
        creates the mock server in the oldest personal Internal workspace you
        own.
      tags:
        - mocks
      parameters:
        - name: workspace
          in: query
          description: The workspace's ID.
          required: true
          schema:
            $ref: '#/components/schemas/workspaceId'
        - name: x-api-key
          in: header
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/mockCreateUpdateResponse'
        '400':
          description: Bad Request
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CreateMockRequestBadRequestError'
        '401':
          description: Unauthorized
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CreateMockRequestUnauthorizedError'
        '500':
          description: Internal Server Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/mock500Error'
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/createMock'
servers:
  - url: https://api.getpostman.com
    description: https://api.getpostman.com
  - url: https://api.eu.postman.com
    description: https://api.eu.postman.com
components:
  schemas:
    workspaceId:
      type: string
      title: workspaceId
    CreateMockMock:
      type: object
      properties:
        collection:
          type: string
          format: uid
          description: The unique ID of the mock's associated collection.
        environment:
          type: string
          format: uid
          description: The unique ID of the mock's associated environment.
        name:
          type: string
          description: The mock server's name.
        private:
          type: boolean
          default: false
          description: >-
            If true, the mock server is set private. By default, mock servers
            are public and can receive requests from anyone and anywhere.
      required:
        - collection
      title: CreateMockMock
    createMock:
      type: object
      properties:
        mock:
          $ref: '#/components/schemas/CreateMockMock'
      title: createMock
    MockCreateUpdateResponseMockConfigDelayType:
      type: string
      enum:
        - fixed
      description: The `fixed` value.
      title: MockCreateUpdateResponseMockConfigDelayType
    MockCreateUpdateResponseMockConfigDelayPreset:
      type: string
      enum:
        - '1'
        - '2'
      description: |
        The simulated fixed network delay value:
        - `1` — 2G (300 ms).
        - `2` — 3G (100 ms).
        The object does not return this value for custom delay values.
      title: MockCreateUpdateResponseMockConfigDelayPreset
    MockCreateUpdateResponseMockConfigDelay:
      type: object
      properties:
        type:
          $ref: '#/components/schemas/MockCreateUpdateResponseMockConfigDelayType'
          description: The `fixed` value.
        duration:
          type: integer
          description: >-
            For custom network delays, the custom configured delay, in
            milliseconds.
        preset:
          $ref: '#/components/schemas/MockCreateUpdateResponseMockConfigDelayPreset'
          description: |
            The simulated fixed network delay value:
            - `1` — 2G (300 ms).
            - `2` — 3G (100 ms).
            The object does not return this value for custom delay values.
      description: >-
        Information about the mock server's simulated network delay settings.
        This returns a null value if there are no configured network delay
        settings.
      title: MockCreateUpdateResponseMockConfigDelay
    MockCreateUpdateResponseMockConfig:
      type: object
      properties:
        matchBody:
          type: boolean
          description: >-
            If true, the mock server matches the request's body to the body of
            the saved examples.
        matchHeader:
          type: boolean
          description: >-
            If true, the mock server matches the request's headers in the
            `header` array to the headers of the saved examples.
        headers:
          type: array
          items:
            type: string
          description: A list of header key values.
        matchQueryParams:
          type: boolean
          description: If true, match query parameters to the saved examples.
        matchWildcards:
          type: boolean
          description: If true, use wildcard variable matching.
        delay:
          oneOf:
            - $ref: '#/components/schemas/MockCreateUpdateResponseMockConfigDelay'
            - type: 'null'
          description: >-
            Information about the mock server's simulated network delay
            settings. This returns a null value if there are no configured
            network delay settings.
        serverResponseId:
          type:
            - string
            - 'null'
          description: >-
            The ID of mock server's default response for requests. All calls to
            the mock server will return the defined response.
      description: Information about the mock server's configuration.
      title: MockCreateUpdateResponseMockConfig
    MockCreateUpdateResponseMock:
      type: object
      properties:
        id:
          type: string
          description: The mock server's ID.
        owner:
          type: string
          description: The ID of mock server's owner.
        uid:
          type: string
          format: uid
          description: The mock server's unique ID.
        collection:
          type: string
          description: The unique ID of the mock's associated collection.
        mockUrl:
          type: string
          format: url
          description: The mock server URL.
        name:
          type: string
          description: The mock server's name.
        config:
          $ref: '#/components/schemas/MockCreateUpdateResponseMockConfig'
          description: Information about the mock server's configuration.
        createdAt:
          type: string
          format: date-time
          description: The date and time at which the mock server was created.
        updatedAt:
          type: string
          format: date-time
          description: The date and time at which the mock server was last updated.
        environment:
          type: string
          description: The unique ID of the mock's associated environment.
      description: Information about the mock server.
      title: MockCreateUpdateResponseMock
    mockCreateUpdateResponse:
      type: object
      properties:
        mock:
          $ref: '#/components/schemas/MockCreateUpdateResponseMock'
          description: Information about the mock server.
      title: mockCreateUpdateResponse
    CommonErrorTypeTitleDetailDetail:
      oneOf:
        - type: string
        - type: object
          additionalProperties:
            description: Any type
      description: Information about the error.
      title: CommonErrorTypeTitleDetailDetail
    commonErrorTypeTitleDetail:
      type: object
      properties:
        type:
          type: string
          description: The type of error.
        title:
          type: string
          description: A short summary of the problem.
        detail:
          $ref: '#/components/schemas/CommonErrorTypeTitleDetailDetail'
          description: Information about the error.
      title: commonErrorTypeTitleDetail
    CommonErrorTypeTitleDetailStatusType:
      oneOf:
        - type: string
          format: uri-reference
        - type: string
      title: CommonErrorTypeTitleDetailStatusType
    commonErrorTypeTitleDetailStatus:
      type: object
      properties:
        type:
          $ref: '#/components/schemas/CommonErrorTypeTitleDetailStatusType'
        title:
          type: string
          description: A short summary of the problem.
        detail:
          type: string
          description: Information about the error.
        status:
          type: integer
          description: The error's HTTP status code.
      title: commonErrorTypeTitleDetailStatus
    CommonErrorNameMessageDetailsErrorDetails:
      oneOf:
        - type: object
          additionalProperties:
            description: Any type
        - type: array
          items:
            type: string
      description: Information about the error.
      title: CommonErrorNameMessageDetailsErrorDetails
    CommonErrorNameMessageDetailsError:
      type: object
      properties:
        name:
          type: string
          description: The error name.
        message:
          type: string
          description: The error message.
        details:
          $ref: '#/components/schemas/CommonErrorNameMessageDetailsErrorDetails'
          description: Information about the error.
      title: CommonErrorNameMessageDetailsError
    commonErrorNameMessageDetails:
      type: object
      properties:
        error:
          $ref: '#/components/schemas/CommonErrorNameMessageDetailsError'
      title: commonErrorNameMessageDetails
    CreateMockRequestBadRequestError:
      oneOf:
        - $ref: '#/components/schemas/commonErrorTypeTitleDetail'
        - $ref: '#/components/schemas/commonErrorTypeTitleDetailStatus'
        - $ref: '#/components/schemas/commonErrorNameMessageDetails'
      title: CreateMockRequestBadRequestError
    CommonErrorNameMessageError:
      type: object
      properties:
        name:
          type: string
          description: The error name.
        message:
          type: string
          description: The error message.
      description: Information about the error.
      title: CommonErrorNameMessageError
    commonErrorNameMessage:
      type: object
      properties:
        error:
          $ref: '#/components/schemas/CommonErrorNameMessageError'
          description: Information about the error.
      title: commonErrorNameMessage
    CreateMockRequestUnauthorizedError:
      oneOf:
        - $ref: '#/components/schemas/commonErrorTypeTitleDetailStatus'
        - $ref: '#/components/schemas/commonErrorNameMessage'
      title: CreateMockRequestUnauthorizedError
    Mock500ErrorError:
      type: object
      properties:
        type:
          type: string
          description: The error name.
        message:
          type: string
          description: The error message.
      title: Mock500ErrorError
    mock500Error:
      type: object
      properties:
        error:
          $ref: '#/components/schemas/Mock500ErrorError'
      title: mock500Error
  securitySchemes:
    PostmanApiKey:
      type: apiKey
      in: header
      name: x-api-key
    scimApiKey:
      type: apiKey
      in: header
      name: Authorization
      description: >-
        A valid [SCIM API
        key](https://learning.postman.com/docs/administration/scim-provisioning/scim-provisioning-overview/#generating-scim-api-key)
        for calls to SCIM endpoints.
    basicAuth:
      type: http
      scheme: basic

```

## Examples

### Successful Response



**Request**

```json
undefined
```

**Response**

```json
{
  "mock": {
    "id": "e3d951bf-873f-49ac-a658-b2dcb91d3289",
    "owner": "12345678",
    "uid": "12345678-e3d951bf-873f-49ac-a658-b2dcb91d3289",
    "collection": "12345678-12ece9e1-2abf-4edc-8e34-de66e74114d2",
    "mockUrl": "https://e3d951bf-873f-49ac-a658-b2dcb91d3289.mock.pstmn.io",
    "name": "Test Mock",
    "config": {
      "matchBody": false,
      "headers": [
        "POST"
      ],
      "matchQueryParams": true,
      "matchWildcards": true,
      "delay": {
        "type": "fixed",
        "duration": 300,
        "preset": "1"
      },
      "serverResponseId": "9a291bbe-dc0a-44ba-a3c8-6dbd06a61460"
    },
    "createdAt": "2022-06-09T19:00:39.000Z",
    "updatedAt": "2022-06-09T19:00:39.000Z",
    "environment": "12345678-5daabc50-8451-43f6-922d-96b403b4f28e"
  }
}
```

**SDK Code**

```python Successful Response
import requests

url = "https://api.getpostman.com/mocks"

querystring = {"workspace":"1f0df51a-8658-4ee8-a2a1-d2567dfa09a9"}

headers = {
    "x-api-key": "<apiKey>",
    "Content-Type": "application/json"
}

response = requests.post(url, headers=headers, params=querystring)

print(response.json())
```

```javascript Successful Response
const url = 'https://api.getpostman.com/mocks?workspace=1f0df51a-8658-4ee8-a2a1-d2567dfa09a9';
const options = {
  method: 'POST',
  headers: {'x-api-key': '<apiKey>', 'Content-Type': 'application/json'},
  body: undefined
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go Successful Response
package main

import (
	"fmt"
	"net/http"
	"io"
)

func main() {

	url := "https://api.getpostman.com/mocks?workspace=1f0df51a-8658-4ee8-a2a1-d2567dfa09a9"

	req, _ := http.NewRequest("POST", url, nil)

	req.Header.Add("x-api-key", "<apiKey>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby Successful Response
require 'uri'
require 'net/http'

url = URI("https://api.getpostman.com/mocks?workspace=1f0df51a-8658-4ee8-a2a1-d2567dfa09a9")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["x-api-key"] = '<apiKey>'
request["Content-Type"] = 'application/json'

response = http.request(request)
puts response.read_body
```

```java Successful Response
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.getpostman.com/mocks?workspace=1f0df51a-8658-4ee8-a2a1-d2567dfa09a9")
  .header("x-api-key", "<apiKey>")
  .header("Content-Type", "application/json")
  .asString();
```

```php Successful Response
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.getpostman.com/mocks?workspace=1f0df51a-8658-4ee8-a2a1-d2567dfa09a9', [
  'headers' => [
    'Content-Type' => 'application/json',
    'x-api-key' => '<apiKey>',
  ],
]);

echo $response->getBody();
```

```csharp Successful Response
using RestSharp;

var client = new RestClient("https://api.getpostman.com/mocks?workspace=1f0df51a-8658-4ee8-a2a1-d2567dfa09a9");
var request = new RestRequest(Method.POST);
request.AddHeader("x-api-key", "<apiKey>");
request.AddHeader("Content-Type", "application/json");
IRestResponse response = client.Execute(request);
```

```swift Successful Response
import Foundation

let headers = [
  "x-api-key": "<apiKey>",
  "Content-Type": "application/json"
]

let request = NSMutableURLRequest(url: NSURL(string: "https://api.getpostman.com/mocks?workspace=1f0df51a-8658-4ee8-a2a1-d2567dfa09a9")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```

### Create Mock



**Request**

```json
{
  "mock": {
    "collection": "12345678-12ece9e1-2abf-4edc-8e34-de66e74114d2",
    "environment": "12345678-5daabc50-8451-43f6-922d-96b403b4f28e",
    "name": "Test Mock",
    "private": true
  }
}
```

**Response**

```json
{
  "mock": {
    "id": "e3d951bf-873f-49ac-a658-b2dcb91d3289",
    "owner": "12345678",
    "uid": "12345678-e3d951bf-873f-49ac-a658-b2dcb91d3289",
    "collection": "12345678-12ece9e1-2abf-4edc-8e34-de66e74114d2",
    "mockUrl": "https://e3d951bf-873f-49ac-a658-b2dcb91d3289.mock.pstmn.io",
    "name": "Test Mock",
    "config": {
      "matchBody": false,
      "headers": [
        "POST"
      ],
      "matchQueryParams": true,
      "matchWildcards": true,
      "delay": {
        "type": "fixed",
        "duration": 300,
        "preset": "1"
      },
      "serverResponseId": "9a291bbe-dc0a-44ba-a3c8-6dbd06a61460"
    },
    "createdAt": "2022-06-09T19:00:39.000Z",
    "updatedAt": "2022-06-09T19:00:39.000Z",
    "environment": "12345678-5daabc50-8451-43f6-922d-96b403b4f28e"
  }
}
```

**SDK Code**

```python Create Mock
import requests

url = "https://api.getpostman.com/mocks"

querystring = {"workspace":"1f0df51a-8658-4ee8-a2a1-d2567dfa09a9"}

payload = { "mock": {
        "collection": "12345678-12ece9e1-2abf-4edc-8e34-de66e74114d2",
        "environment": "12345678-5daabc50-8451-43f6-922d-96b403b4f28e",
        "name": "Test Mock",
        "private": True
    } }
headers = {
    "x-api-key": "<apiKey>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers, params=querystring)

print(response.json())
```

```javascript Create Mock
const url = 'https://api.getpostman.com/mocks?workspace=1f0df51a-8658-4ee8-a2a1-d2567dfa09a9';
const options = {
  method: 'POST',
  headers: {'x-api-key': '<apiKey>', 'Content-Type': 'application/json'},
  body: '{"mock":{"collection":"12345678-12ece9e1-2abf-4edc-8e34-de66e74114d2","environment":"12345678-5daabc50-8451-43f6-922d-96b403b4f28e","name":"Test Mock","private":true}}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go Create Mock
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.getpostman.com/mocks?workspace=1f0df51a-8658-4ee8-a2a1-d2567dfa09a9"

	payload := strings.NewReader("{\n  \"mock\": {\n    \"collection\": \"12345678-12ece9e1-2abf-4edc-8e34-de66e74114d2\",\n    \"environment\": \"12345678-5daabc50-8451-43f6-922d-96b403b4f28e\",\n    \"name\": \"Test Mock\",\n    \"private\": true\n  }\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("x-api-key", "<apiKey>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby Create Mock
require 'uri'
require 'net/http'

url = URI("https://api.getpostman.com/mocks?workspace=1f0df51a-8658-4ee8-a2a1-d2567dfa09a9")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["x-api-key"] = '<apiKey>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"mock\": {\n    \"collection\": \"12345678-12ece9e1-2abf-4edc-8e34-de66e74114d2\",\n    \"environment\": \"12345678-5daabc50-8451-43f6-922d-96b403b4f28e\",\n    \"name\": \"Test Mock\",\n    \"private\": true\n  }\n}"

response = http.request(request)
puts response.read_body
```

```java Create Mock
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.getpostman.com/mocks?workspace=1f0df51a-8658-4ee8-a2a1-d2567dfa09a9")
  .header("x-api-key", "<apiKey>")
  .header("Content-Type", "application/json")
  .body("{\n  \"mock\": {\n    \"collection\": \"12345678-12ece9e1-2abf-4edc-8e34-de66e74114d2\",\n    \"environment\": \"12345678-5daabc50-8451-43f6-922d-96b403b4f28e\",\n    \"name\": \"Test Mock\",\n    \"private\": true\n  }\n}")
  .asString();
```

```php Create Mock
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.getpostman.com/mocks?workspace=1f0df51a-8658-4ee8-a2a1-d2567dfa09a9', [
  'body' => '{
  "mock": {
    "collection": "12345678-12ece9e1-2abf-4edc-8e34-de66e74114d2",
    "environment": "12345678-5daabc50-8451-43f6-922d-96b403b4f28e",
    "name": "Test Mock",
    "private": true
  }
}',
  'headers' => [
    'Content-Type' => 'application/json',
    'x-api-key' => '<apiKey>',
  ],
]);

echo $response->getBody();
```

```csharp Create Mock
using RestSharp;

var client = new RestClient("https://api.getpostman.com/mocks?workspace=1f0df51a-8658-4ee8-a2a1-d2567dfa09a9");
var request = new RestRequest(Method.POST);
request.AddHeader("x-api-key", "<apiKey>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"mock\": {\n    \"collection\": \"12345678-12ece9e1-2abf-4edc-8e34-de66e74114d2\",\n    \"environment\": \"12345678-5daabc50-8451-43f6-922d-96b403b4f28e\",\n    \"name\": \"Test Mock\",\n    \"private\": true\n  }\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift Create Mock
import Foundation

let headers = [
  "x-api-key": "<apiKey>",
  "Content-Type": "application/json"
]
let parameters = ["mock": [
    "collection": "12345678-12ece9e1-2abf-4edc-8e34-de66e74114d2",
    "environment": "12345678-5daabc50-8451-43f6-922d-96b403b4f28e",
    "name": "Test Mock",
    "private": true
  ]] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.getpostman.com/mocks?workspace=1f0df51a-8658-4ee8-a2a1-d2567dfa09a9")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```