Run a mock server from an OpenAPI file on your machine
Last checked and updated
apigit mock serve openapi.yaml starts an HTTP server on your machine that answers every operation of the file. Responses come from the file's examples, or are generated from its schemas. Requests that do not match the description are refused with the reason. It runs offline and needs no account.
Start it
$ npm install -g @apigit/cli
$ apigit mock serve pay.yaml --port 4611
Mock of pay.yaml at http://127.0.0.1:4611 (Ctrl+C to stop). 1 operation(s):
POST /payments
The default port is 4010. Each request is logged with its status:
POST /payments -> 201
POST /payments -> 422
What it returns
For an operation with this response schema:
Pet:
type: object
required: [id, name]
properties:
id:
type: string
name:
type: string
nickname:
type: [string, "null"]
the mock answers:
$ curl http://127.0.0.1:4613/pets/1
HTTP/1.1 200 OK
{"id":"string","name":"string","nickname":"string"}
Generated values are placeholders that fit the schema: "string", or user@example.com for format: email. To get realistic data, put example values in the OpenAPI file. They then serve the documentation and the mock alike, which is the point of mocking from the description.
It validates requests
A body that does not match the request schema gets a 422 in the problem-details format (RFC 9457, application/problem+json), with one entry per failure:
$ curl -X POST http://127.0.0.1:4621/users -H 'content-type: application/json' \
-d '{"email":"a@example.com","labels":{"team":7}}'
HTTP/1.1 422 Unprocessable Entity
{"errors":[{"in":"body","pointer":"/labels/team","message":"must be string"}],
"type":"https://apigit.com/mock/problems/invalid-request",
"title":"The request does not match the API description","status":422, ...}
This makes the mock a test of the client: a frontend built against it cannot send what the real API will refuse. The messages are explained one by one in Errors and fixes.
Local or hosted
Local (apigit mock serve) | Hosted mock server | |
|---|---|---|
| Reachable by | your machine | anyone with the address, optionally with a token |
| Follows | the file on disk | a commit, or a branch as it moves |
| Request log | the terminal | kept; read it with apigit mock logs |
| Needs | Node.js | an APIGit repository |
Use the local mock while writing the description and the client. Publish a hosted one (apigit mock publish) when a team, a CI job or a partner needs the same address. The local mock runs a copy of the hosted mock server's engine, so both judge a request the same way.
Other kinds of mock
The same command serves a GraphQL schema (apigit mock serve schema.graphql, answering at /graphql) and a scripted mock for behaviour that examples cannot express, such as state that changes between calls (apigit mock serve ./apigit-mock).