Mocking APIs with Prism from OpenAPI Specs for Frontend Testing

Mocking APIs with Prism from OpenAPI Specs for Frontend Testing

Frontend development has a classic blocking problem: the backend isn't ready. You're building a checkout flow, but the payments API returns a 500. You want to test the empty state, but the backend always returns data. You need to simulate a 429 rate limit, but production systems don't cooperate on demand.

Prism solves this. It reads your OpenAPI spec and spins up a fully functional mock server in seconds. Every endpoint, every response schema, every example — available instantly, no backend required.

What Prism Does

Prism is an open-source HTTP mock server by Stoplight. Given an OpenAPI spec, it:

  • Generates realistic response bodies using schema examples or random data
  • Validates incoming requests against the spec
  • Returns spec-compliant error responses for invalid requests
  • Supports dynamic response selection via Prefer headers

It runs as a local server or in Docker, making it straightforward to integrate into development and CI workflows.

Installing and Starting Prism

npm install -g @stoplight/prism-cli

Start a mock server from a local spec:

prism mock openapi.yaml

Or from a URL:

prism mock https://api.example.com/openapi.yaml

Prism starts on port 4010 by default. Every endpoint in your spec is now available:

curl http://localhost:4010/users/123
# → {"id": "123", "name": "Jane Doe", "email": "jane@example.com"}

The response body is generated from the example values in your spec, or synthesized from the schema if no examples are provided.

Writing Spec Examples for Better Mocks

The quality of Prism's responses depends on the quality of your spec's examples. Vague schemas produce random-looking data; detailed examples produce realistic mocks.

Compare these two approaches:

Schema-only (poor mock quality):

components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: string
        email:
          type: string
        createdAt:
          type: string
          format: date-time

Schema with examples (good mock quality):

components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: string
          example: "usr_01HQKF5P2V3B8X7YNTCWRD6Z4A"
        email:
          type: string
          format: email
          example: "jane.doe@acme.com"
        createdAt:
          type: string
          format: date-time
          example: "2026-01-15T09:30:00Z"

The second version gives Prism concrete values to return, making mock responses look like real data.

Simulating Different Scenarios with Prefer Headers

Prism's most powerful feature for testing is the Prefer header. It lets you tell the mock server which response to return without changing the spec.

Return a specific status code:

curl -H "Prefer: code=404" http://localhost:4010/users/999
<span class="hljs-comment"># → {"type": "https://example.com/not-found", "title": "Not Found", "status": 404}

Return a named example:

responses:
  "200":
    content:
      application/json:
        examples:
          active_user:
            value:
              id: "usr_123"
              status: "active"
          suspended_user:
            value:
              id: "usr_456"
              status: "suspended"
curl -H "Prefer: example=suspended_user" http://localhost:4010/users/456
<span class="hljs-comment"># → {"id": "usr_456", "status": "suspended"}

This makes it trivial to test edge cases: empty states, error responses, paginated results, rate limits — all from the same mock server.

Request Validation

Prism validates incoming requests by default and rejects those that don't match the spec. This is useful during frontend development: if your code sends a malformed request, Prism returns a 422 with details about what's wrong.

curl -X POST http://localhost:4010/users \
  -H "Content-Type: application/json" \
  -d <span class="hljs-string">'{"email": "not-a-valid-email"}'

<span class="hljs-comment"># → 422 Unprocessable Entity
<span class="hljs-comment"># → {"type": "UNPROCESSABLE_ENTITY", "errors": [{"path": ".body.email", "message": "must match format \"email\""}]}

To disable validation (useful when testing intentionally malformed inputs):

prism mock --errors false openapi.yaml

Running Prism in CI

Add Prism to your CI pipeline to run frontend integration tests against a mock backend:

# .github/workflows/frontend-tests.yml
name: Frontend Tests
on: [pull_request]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
      - name: Start Prism mock server
        run: |
          npm install -g @stoplight/prism-cli
          prism mock openapi.yaml &
          sleep 2
      - name: Run frontend tests
        run: npm test
        env:
          API_BASE_URL: http://localhost:4010

Your frontend tests point at http://localhost:4010 and get consistent, spec-compliant responses every time.

Prism as a Proxy

Beyond pure mocking, Prism can run as a proxy in front of your real backend:

prism proxy openapi.yaml http://localhost:3000

In proxy mode, Prism forwards requests to the real server but validates both requests and responses against the spec. Any drift between the spec and the actual API surfaces immediately — Prism logs a warning when the real server returns something the spec doesn't describe.

This is contract testing in reverse: instead of generating test cases (like Schemathesis), it monitors live traffic for spec violations.

Practical Frontend Testing Workflow

  1. Design the spec first — define endpoints, schemas, and examples before writing any code
  2. Start Prism immediately — frontend development begins against the mock server from day one
  3. Use Prefer headers in tests — cover success paths, empty states, and errors without conditionals in test setup
  4. Validate against the real server — when the backend is ready, run Prism in proxy mode to catch drift
  5. Keep examples current — update spec examples when business logic changes; stale examples produce misleading mocks

The frontend team unblocks itself. The backend team gets a clear spec to implement against. And contract violations surface at review time, not in production.

For teams that need end-to-end test coverage beyond mock validation — testing real user flows across a deployed environment — HelpMeTest provides AI-powered test automation on top of your actual running services. Prism covers the development phase; end-to-end tests cover what ships.

Read more