Automate · Lesson 14 of 20

Mock servers

Answer requests from saved examples, so front ends and tests can work before the real API is ready.

Intermediate · 2 min · Updated

A mock server answers requests with responses you prepared, instead of a real backend. Front-end developers can start before the API is finished, tests can run without a database, and you can try error cases that are hard to cause for real.

Mocks answer with a collection's saved examples. To add one, send a request and click Save as example, or create one by hand in the request's examples list. Save a few per endpoint: a success, a 404, a validation error.

A mock in the cloud

  1. Open Mocks in the left sidebar and click +.
  2. Pick the collection (and optionally an environment for {{variables}} in the examples).
  3. Copy the mock's URL and use it as your API's base URL.

When a request comes in, the mock finds the example whose method and path match (/orders/42 matches an example saved for /orders/:id), the closest query and body, and answers with its status, headers and body.

Choose the response

Send these headers to pick a specific example:

  • x-mock-response-code: 404 for the example with that status;
  • x-mock-response-name: Out of stock for an example by name;
  • x-mock-response-delay: 2000 to wait 2 seconds first, to see how your app handles a slow API.

Responses that use the request

Examples can copy values from the incoming request:

JSON
{ "id": "{{$pathSegments '1'}}", "status": "paid", "email": "{{$body 'customer.email'}}" }

{{$queryParams 'page' '1'}} and {{$headers 'X-Request-Id'}} work the same way, with an optional default value.

A mock on your computer

swc mock runs the same mock locally, with no account and nothing leaving your machine:

Shell
swc mock shop.json --port 4010
Text
✓ mock of "Shop" on http://127.0.0.1:4010  (3 route(s) with examples, Ctrl+C to stop)
  GET /orders/{id} (2 examples)

It uses exactly the same matching and the same headers as the cloud mock, prints every request it answers, and allows browser calls from any port (CORS), so a front end on localhost:5173 can use it directly. A request no example matches gets a 404 listing the routes the mock knows.

What you learned

  • Mocks answer from saved examples; headers pick the status, the example and a delay.
  • Run them in the cloud for a shareable URL, or locally with swc mock.

Next: watch your API around the clock and see how reliable it really is.

Try it on your own API

Swastik Codes runs in the browser and is free to use. Create an account to send requests, sync your workspaces and invite your team.