> ## Documentation Index
> Fetch the complete documentation index at: https://moeck.io/llms.txt
> Use this file to discover all available pages before exploring further.

# OpenAPI

> Load an OpenAPI v3 spec to auto-generate expectations or use it as a request matcher.

MockServer has first-class support for **OpenAPI v3** specifications. You can use a spec in two ways:

1. **Generate expectations** — MockServer reads each operation in the spec and automatically creates a matching expectation with an auto-generated example response.
2. **Match requests** — Use the spec as a request matcher inside an expectation so that only requests conforming to a specific operation are matched.

## Generate expectations from an OpenAPI spec

Submit a spec to MockServer using the `/mockserver/openapi` endpoint. MockServer creates one expectation per operation, with a response action derived from the operation's example or schema definitions.

### Load from a URL

<CodeGroup>
  ```java Java theme={null}
  new MockServerClient("localhost", 1080)
      .upsert(
          openAPIExpectation(
              "https://raw.githubusercontent.com/mock-server/mockserver/master/mockserver-integration-testing/src/main/resources/org/mockserver/openapi/openapi_petstore_example.json"
          )
      );
  ```

  ```javascript JavaScript theme={null}
  var mockServerClient = require('mockserver-client').mockServerClient;
  mockServerClient("localhost", 1080).openAPIExpectation({
      "specUrlOrPayload": "https://raw.githubusercontent.com/mock-server/mockserver/master/mockserver-integration-testing/src/main/resources/org/mockserver/openapi/openapi_petstore_example.json"
  }).then(
      function () { console.log("expectation created"); },
      function (error) { console.log(error); }
  );
  ```

  ```bash REST API theme={null}
  curl -v -X PUT "http://localhost:1080/mockserver/openapi" -d '{
      "specUrlOrPayload": "https://raw.githubusercontent.com/mock-server/mockserver/master/mockserver-integration-testing/src/main/resources/org/mockserver/openapi/openapi_petstore_example.json"
  }'
  ```
</CodeGroup>

### Load from a file path

```bash theme={null}
curl -v -X PUT "http://localhost:1080/mockserver/openapi" -d '{
    "specUrlOrPayload": "file:/Users/jamesbloom/git/mockserver/openapi_petstore_example.json"
}'
```

### Load from a classpath location

```bash theme={null}
curl -v -X PUT "http://localhost:1080/mockserver/openapi" -d '{
    "specUrlOrPayload": "org/mockserver/openapi/openapi_petstore_example.json"
}'
```

Do not include the `classpath:` scheme prefix — just provide the path relative to the classpath root.

### Load from an inline JSON object

Pass the spec content directly in the request body. In the REST API, embed the spec JSON as the value of `specUrlOrPayload`:

```bash theme={null}
curl -v -X PUT "http://localhost:1080/mockserver/openapi" -d "{
    \"specUrlOrPayload\": $(cat /path/to/openapi_petstore_example.json)
}"
```

In JavaScript, read the file and pass the string:

```javascript theme={null}
var fs = require('fs');
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).openAPIExpectation({
    "specUrlOrPayload": fs.readFileSync("/path/to/openapi_petstore_example.json", "utf8")
});
```

### Load from an inline YAML string

Pass the YAML spec as a string value for `specUrlOrPayload`:

```java theme={null}
new MockServerClient("localhost", 1080)
    .upsert(
        openAPIExpectation(
            "---\n" +
            "openapi: 3.0.0\n" +
            "info:\n" +
            "  version: 1.0.0\n" +
            "  title: Swagger Petstore\n" +
            "paths:\n" +
            "  /pets:\n" +
            "    get:\n" +
            "      summary: List all pets\n" +
            "      operationId: listPets\n" +
            "      responses:\n" +
            "        '200':\n" +
            "          description: A paged array of pets\n"
        )
    );
```

## Filtering operations and selecting response codes

Use `operationsAndResponses` to control which operations generate expectations and which status code is used for each operation's response. Keys are `operationId` values from the spec; values are status code strings (`"200"`, `"400"`, `"default"`, etc.).

<CodeGroup>
  ```java Java theme={null}
  Map<String, String> operationsAndResponses = new HashMap<>();
  operationsAndResponses.put("showPetById", "200");
  operationsAndResponses.put("createPets", "500");

  new MockServerClient("localhost", 1080)
      .upsert(
          openAPIExpectation(
              "https://raw.githubusercontent.com/mock-server/mockserver/master/mockserver-integration-testing/src/main/resources/org/mockserver/openapi/openapi_petstore_example.json",
              operationsAndResponses
          )
      );
  ```

  ```javascript JavaScript theme={null}
  mockServerClient("localhost", 1080).openAPIExpectation({
      "specUrlOrPayload": "https://raw.githubusercontent.com/mock-server/mockserver/master/mockserver-integration-testing/src/main/resources/org/mockserver/openapi/openapi_petstore_example.json",
      "operationsAndResponses": {
          "showPetById": "200",
          "createPets": "500"
      }
  });
  ```

  ```bash REST API theme={null}
  curl -v -X PUT "http://localhost:1080/mockserver/openapi" -d '{
      "specUrlOrPayload": "https://raw.githubusercontent.com/mock-server/mockserver/master/mockserver-integration-testing/src/main/resources/org/mockserver/openapi/openapi_petstore_example.json",
      "operationsAndResponses": {
          "showPetById": "200",
          "createPets": "500"
      }
  }'
  ```
</CodeGroup>

When you submit the above, MockServer creates one expectation per listed operation:

```json theme={null}
{
  "priority": 0,
  "httpRequest": {
    "specUrlOrPayload": "https://raw.githubusercontent.com/mock-server/mockserver/master/mockserver-integration-testing/src/main/resources/org/mockserver/openapi/openapi_petstore_example.json",
    "operationId": "showPetById"
  },
  "httpResponse": {
    "statusCode": 200,
    "headers": { "content-type": ["application/json"] },
    "body": { "id": 0, "name": "some_string_value", "tag": "some_string_value" }
  },
  "times": { "unlimited": true },
  "timeToLive": { "unlimited": true }
}
```

If `operationsAndResponses` is omitted, all operations are included and the first response body defined for each operation is used.

## Use an OpenAPI spec as a request matcher

Instead of generating expectations, you can use a spec as the **request matcher** inside a regular expectation. This lets you route all requests that match a given operation to a custom response action.

<Tabs>
  <Tab title="Java">
    ```java theme={null}
    // match all operations in the spec
    new MockServerClient("localhost", 1080)
        .when(
            openAPI(
                "https://raw.githubusercontent.com/mock-server/mockserver/master/mockserver-integration-testing/src/main/resources/org/mockserver/openapi/openapi_petstore_example.json"
            )
        )
        .respond(
            response().withBody("some_response_body")
        );

    // match a specific operation
    new MockServerClient("localhost", 1080)
        .when(
            openAPI(
                "https://raw.githubusercontent.com/mock-server/mockserver/master/mockserver-integration-testing/src/main/resources/org/mockserver/openapi/openapi_petstore_example.json",
                "showPetById"
            )
        )
        .respond(
            response().withBody("some_response_body")
        );
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    // match all operations
    mockServerClient("localhost", 1080).mockAnyResponse({
        "httpRequest": {
            "specUrlOrPayload": "https://raw.githubusercontent.com/mock-server/mockserver/master/mockserver-integration-testing/src/main/resources/org/mockserver/openapi/openapi_petstore_example.json"
        },
        "httpResponse": { "body": "some_response_body" }
    });

    // match a specific operation
    mockServerClient("localhost", 1080).mockAnyResponse({
        "httpRequest": {
            "specUrlOrPayload": "https://raw.githubusercontent.com/mock-server/mockserver/master/mockserver-integration-testing/src/main/resources/org/mockserver/openapi/openapi_petstore_example.json",
            "operationId": "showPetById"
        },
        "httpResponse": { "body": "some_response_body" }
    });
    ```
  </Tab>

  <Tab title="REST API">
    ```bash theme={null}
    # match all operations
    curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
        "httpRequest": {
            "specUrlOrPayload": "https://raw.githubusercontent.com/mock-server/mockserver/master/mockserver-integration-testing/src/main/resources/org/mockserver/openapi/openapi_petstore_example.json"
        },
        "httpResponse": { "body": "some_response_body" }
    }'

    # match a specific operation
    curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
        "httpRequest": {
            "specUrlOrPayload": "https://raw.githubusercontent.com/mock-server/mockserver/master/mockserver-integration-testing/src/main/resources/org/mockserver/openapi/openapi_petstore_example.json",
            "operationId": "showPetById"
        },
        "httpResponse": { "body": "some_response_body" }
    }'
    ```
  </Tab>
</Tabs>

When `operationId` is omitted, any request matching any operation in the spec will trigger the expectation.

<Note>
  When you use an OpenAPI spec as a request matcher, MockServer internally converts it to a set of request properties matchers. This means operations such as clearing expectations and retrieving active expectations work consistently regardless of whether a request properties matcher or an OpenAPI matcher was used.
</Note>

## Match exactly N times using OpenAPI

Combine an OpenAPI request matcher with `times` to limit how often the expectation fires:

```bash theme={null}
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest": {
        "specUrlOrPayload": "https://raw.githubusercontent.com/mock-server/mockserver/master/mockserver-integration-testing/src/main/resources/org/mockserver/openapi/openapi_petstore_example.json",
        "operationId": "showPetById"
    },
    "httpResponse": {
        "statusCode": 200,
        "body": "some_body"
    },
    "times": {
        "remainingTimes": 2
    }
}'
```
