# Mock Servers and Contract Testing — OpenAPI / Swagger

Source: https://www.skillbyai.com/en/openapi/t-mock

> Mock APIs from OpenAPI documents and test implementations against the contract.

## Using the contract before and after implementation

Because an OpenAPI document precisely describes requests and responses, tools can act on it. **Mock servers** such as **Prism** (Stoplight) serve responses generated from schemas and examples, validating incoming requests against the document; frontend and mobile teams can build against a realistic API before the backend exists, and the mock flags requests that violate the contract. **Contract testing** checks that the real implementation honours the document. **Schemathesis** generates many requests from the schema, including edge cases, sends them to a running API and reports crashes, undocumented status codes and responses that do not match their schemas. **Request and response validation** middleware, available for many frameworks, can reject non-conforming requests at run time and, in test environments, check responses too. Consumer-driven contract testing tools such as **Pact** complement OpenAPI by verifying the specific interactions each consumer relies on. Together these keep documentation honest: if the implementation drifts from the contract, tests fail.

## Mocking and property-based testing from the document

Prism serves the contract; Schemathesis attacks the implementation with generated requests.

```bash
# mock server from the contract (validates requests, returns examples)
npx @stoplight/prism-cli mock api/openapi.yaml --port 4010
curl -s http://localhost:4010/orders?limit=2 -H "Authorization: Bearer test"

# validate a running implementation against the contract with generated test cases
schemathesis run api/openapi.yaml \
  --url http://localhost:8080 \
  --header "Authorization: Bearer $TEST_TOKEN" \
  --checks all
# reports: 500 errors, responses not matching schemas, undocumented status codes,
#          content-type mismatches
```

## Run contract tests in CI against every build

A contract test that runs only before a big release finds drift too late. Start the service in CI, run Schemathesis or response validation against it, and fail the build on mismatches.

**Quiz:** What does Schemathesis do with an OpenAPI document?

- [x] Generates many test requests from the schema and checks the running API's responses against the contract
- [ ] Generates documentation websites
- [ ] Converts YAML to JSON only
- [ ] Deploys the API

*Answer:* Generates many test requests from the schema and checks the running API's responses against the contract. It is a property-based testing tool that finds crashes and contract violations.
