Chuyển đến nội dung

Bài 28 · Validation and Contract Testing

Mock Servers from OpenAPI with Prism

Run a mock API straight from an OpenAPI document with Prism: static and dynamic responses, the Prefer header, validation proxy mode, and a runnable mock server stand-in.

If your spec contains paths, schemas and examples, a program can answer requests from it without any real implementation. That is a mock server. Front-end teams can build against it before the backend exists, tests can run without a database, and the API design can be tried out by real clients early, while changes are still cheap.

Prism by Stoplight is the usual open-source choice. It runs on Node and cannot run on this website, so the commands are read-only; a Python stand-in at the end implements the core behavior so you can try it.

Start a mock

Terminal
npm install --save-dev @stoplight/prism-cli

# serve a mock of the spec on http://127.0.0.1:4010
npx prism mock openapi.yaml

# then, from another terminal
curl -i http://127.0.0.1:4010/books/b1

Prism reads the spec, matches the request to an operation and returns a response. It chooses which response using these rules:

  1. A named example or examples entry in the response media type, if any.
  2. Otherwise, a value generated from the response schema.
  3. Otherwise, an empty body with the declared status.

By default Prism answers with the first 2xx response it finds.

Static or dynamic

Terminal
# static (default): same example every time
npx prism mock openapi.yaml

# dynamic: generate fresh fake values from the schema (-d)
npx prism mock -d openapi.yaml

Static is good for predictable tests. Dynamic is good for exploring how a UI copes with different data. In both modes, format, enum, minimum and maxLength in the schema guide the generated values.

Choose a response with the Prefer header

A client can ask Prism for a particular response using the standard Prefer request header:

Terminal
# force the 404 response defined in the spec
curl -i -H "Prefer: code=404" http://127.0.0.1:4010/books/b1

# pick a named example
curl -i -H "Prefer: example=withdrawn" http://127.0.0.1:4010/books/b1

# ask for dynamic generation on one call
curl -i -H "Prefer: dynamic=true" http://127.0.0.1:4010/books

This lets front-end developers test error screens without any special server code.

Validation in the mock

Prism also validates the request against the spec. A request with a missing required parameter, a malformed body or missing credentials gets an error response (such as 422 or 401) with a body that explains what failed. That means a client built against the mock already fails early when it sends something the real API will not accept.

Proxy mode: validating a real server

Terminal
npx prism proxy openapi.yaml https://staging.example.com

In proxy mode, Prism forwards requests to the real server and checks both directions against the spec. Violations are reported (with --errors the proxy turns them into error responses). It is a cheap way to run response validation in a test environment without changing the server code.

Stand-in: a mock that follows the same rules

This runnable Python version picks responses like Prism: Prefer: code= and Prefer: example= choices first, then the first 2xx, using the examples in the spec and falling back to a schema-generated value.

Python Stand-in: a spec-driven mock

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Mocking in a workflow

flowchart LR
  D["Design spec with examples"] --> M["Prism mock"]
  M --> F["Front-end builds against mock"]
  D --> B["Backend implements"]
  B --> P["Prism proxy / contract tests"]
  F --> I["Integrate with real API"]
  P --> I

Front-end and backend work in parallel from the same document.

Tips for good mocks:

  • Write realistic, varied examples; a mock is only as helpful as its data.
  • Include examples for error responses, not just success.
  • Keep the mock in CI (docker run -p 4010:4010 stoplight/prism:4 mock -h 0.0.0.0 /spec/openapi.yaml) so UI tests do not depend on a shared dev server.
  • Remember that a mock has no state: POST /books followed by GET /books will not show the new book. Use a stateful stub when you need that.

Check your understanding

Quick check · 3 questions

of 3 answered You scored / 3 · perfect!

  1. 1. How can a client ask Prism to return the 404 response defined in the spec?

    The Prefer header supports code=, example= and dynamic=true.
  2. 2. What does prism mock -d do?

    -d turns on dynamic response generation based on the schema.
  3. 3. Why does a mock not show a book created by a previous POST?

    Responses come from examples or schemas, not from stored data.

Summary

  • Prism mocks an API from the spec: examples first, generated data second.
  • -d enables dynamic data, and Prefer chooses status codes and named examples per request.
  • Prism validates requests, and in proxy mode it checks a real server against the spec.
  • Mocks are stateless; good examples make them useful.
  • The Python mock is a stand-in for the selection logic.

Next: Contract testing with Schemathesis and Dredd

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.