Skip to content
Projekte

Über uns

A mock HTTP server in a single binary, with a web dashboard. Register REST, GraphQL and gRPC endpoints while it runs, or load them from a file or a Postman collection.

Systeme und Infrastruktur

So werden diese Zahlen gemessen

Gemessener Sternzuwachs

in 24h
0
in 7 days
Verlauf wird gesammelt
in 15 days
Verlauf wird gesammelt
in 1 month
Verlauf wird gesammelt

Nettoänderungen in überlappenden Zeiträumen, keine Tagessummen. Fehlende Messwerte bleiben leer. Sterne zeigen Interesse, nicht Qualität.

README.md

Original

The mockiapi icon: an orange mockingbird

mockiapi

mockiapi is a mock HTTP server. You tell it "when a request arrives at this path, answer with this JSON file", and it does. Your frontend, mobile app or integration test can then talk to http://localhost:3001 while the real API is not ready or not reachable.

Endpoints are registered while the server is running, from a web dashboard or with curl, and nothing needs a restart. A set of endpoints can also be kept in a file, written by hand or exported from Postman, and loaded when the server starts.

For a short overview with a screenshot of the dashboard, see the product page. Its source is docs/index.html.

The bird in the icon is a mockingbird. A mockingbird copies the songs of other birds well enough to pass for them, and mockiapi does the same for an API: it answers the way the real one would, so the code calling it cannot tell the difference.

What an endpoint can do:

  • answer with a fixed JSON file, on the HTTP methods you choose, with a different response for each method of a path if you want
  • accept path parameters such as /api/user/{id} and copy request values into the response
  • answer with any status code, after a delay, or under a rate limit
  • require Basic auth or a bearer token
  • answer GraphQL queries and mutations, returning only the selected fields
  • answer simulated gRPC calls sent as JSON over HTTP

Two things to know before you start:

  • Endpoints are saved as you register them and come back after a restart. They can also be written in a mocks file that is loaded at every start.
  • The response file must be JSON. The server always answers with Content-Type: application/json.

Contents

  1. Start the server
  2. Register your first endpoint
  3. Use path parameters and dynamic values
  4. Simulate errors, slow responses and rate limits
  5. Protect an endpoint
  6. Mock a GraphQL API
  7. Mock a gRPC call
  8. List, change and delete endpoints
  9. Start with your mocks already loaded
  10. Keep your endpoints across restarts
  11. Reference

1. Start the server

Pick one of the three ways below. In all of them the server listens on port 3001, unless you choose another port.

With Docker

docker compose up -d

Run it from the repository root. It uses the docker-compose.yml there, which starts the published edufsantos/mockiapi image and maps port 3001.

From source

Install Rust and Node.js with npm, then:

# Linux or macOS
chmod +x init.sh
./init.sh

On Windows, run init.bat.

The script builds the dashboard into frontend/dist, builds the server with the dashboard embedded in it, and starts the server with request logging on.

With a release binary

System Download
Linux, Intel or AMD mockiapi-linux-amd64
Linux, ARM mockiapi-linux-arm64
macOS, Apple Silicon (M1 and later) mockiapi-macos-arm64
macOS, Intel mockiapi-macos-amd64
Windows mockiapi-windows-amd64 (add the .exe extension after downloading)

The Linux ARM and macOS Intel binaries start with 0.2.0. In 0.1.9 itself, mockiapi-macos-amd64 is an Apple Silicon binary under the wrong name, so on an Intel Mac use 0.2.0 or later.

chmod +x mockiapi-linux-amd64
RUST_LOG=info ./mockiapi-linux-amd64

The download is a single executable with the dashboard inside it. There is nothing else to download, and it can be started from any directory.

On another port

Pass --port, or set the PORT environment variable. The argument wins when both are given.

./mockiapi-linux-amd64 --port 8080
PORT=8080 ./mockiapi-linux-amd64

The init scripts hand their arguments to the server, so ./init.sh --port 8080 works too. With Docker, set the variable and publish the same port:

docker run -e PORT=8080 -p 8080:8080 edufsantos/mockiapi

If the port is already in use, the server says so and stops. The rest of this tutorial uses 3001.

Check that it is running

The server prints:

.: Server running at http://localhost:3001

Open http://localhost:3001 in a browser. You should see the MockiAPI dashboard. A strip at the top counts the endpoints, their groups, how many are protected and how many answer with a delay or under a rate limit. Below it are three columns: the list of endpoints, empty for now, the form for a new endpoint, and a Try it panel.

The server creates an uploads directory in the directory it was started from. That is where it keeps a copy of each response file, and the list of endpoints that lets it bring them back after a restart.

2. Register your first endpoint

Create a file named hello.json:

{ "message": "Hello, world!" }

In the dashboard, stay on the REST tab and fill in:

Field Value
Path /api/hello
HTTP Methods GET
Response (JSON File) hello.json

Leave the other fields empty and click Register endpoint, at the top of the form. The endpoint shows up in the list on the left and stays open in the form. In the Try it panel, click Send to call it from the browser and see the status, the time it took and the body.

There is no need for a file if you would rather type: next to Response, switch from File to Text and paste the JSON into the box.

With curl, the same registration is:

curl -X POST http://localhost:3001/register \
  -F path=/api/hello \
  -F methods=GET \
  -F [email protected]
"Registered successfully"

Now call it:

curl http://localhost:3001/api/hello
{ "message": "Hello, world!" }

The rules for a registration:

  • The path is required and must start with /.
  • At least one HTTP method is required. For several, tick more than one box, or send them comma-separated: -F methods=GET,POST.
  • The response file is required.
  • A path can hold one endpoint per method. Register /api/users for GET and again for POST with another file and another status code, and each method gets its own answer.
  • Registering a path again for a method it already answers replaces the endpoint that answered it. If the registration comes without a file, the endpoint keeps the response it had and only its other settings are replaced.
  • A group is optional: -F group=users, or the Group field. It only sorts the list in the dashboard.

And what callers get when a request does not fit:

Request Answer
A path nobody registered 404 Resource not found
A registered path with a method it was not registered for 405 Method not allowed

3. Use path parameters and dynamic values

A {name} segment in the path matches any value. Registering /api/user/{id} answers /api/user/1, /api/user/2 and every other id with the same file.

To make the response change with the request, write {{name}} placeholders in the response file and turn on Dynamic Vars. Create user.json:

{
  "message": "Hello, {{name}}!",
  "user_id": "{{id}}",
  "requested_item": "{{item}}",
  "timestamp": "{{timestamp}}"
}

In the dashboard:

Field Value
Path /api/user/{id}/item/{item}?name={name}
HTTP Methods GET
Dynamic Vars checked
Response (JSON File) user.json

With curl:

curl -X POST http://localhost:3001/register \
  -F 'path=/api/user/{id}/item/{item}?name={name}' \
  -F methods=GET \
  -F with_dynamic_vars=true \
  -F [email protected]

Call it:

curl "http://localhost:3001/api/user/123/item/laptop?name=John"
{
  "message": "Hello, John!",
  "user_id": "123",
  "requested_item": "laptop",
  "timestamp": "2026-11-18T22:34:07.857749903+00:00"
}

Note the two kinds of braces: single braces {id} in the path say where a value is read from, double braces {{id}} in the file say where it is written.

Where placeholder values come from:

  • {name} segments of the registered path
  • query parameters of the request, by their own name
  • top-level fields of a JSON request body, so a POST with {"name": "John"} fills {{name}}
  • {{timestamp}}, which is always the current UTC time

How it behaves at the edges:

  • Without Dynamic Vars checked, the file is sent exactly as uploaded, placeholders included.
  • A placeholder with no matching value is left in the response as it is.
  • A fixed query value in the registered path, such as /search?kind=book, must be present in the request for the endpoint to match. Its position among the other parameters does not matter.

4. Simulate errors, slow responses and rate limits

Three optional fields change how an endpoint answers:

Field Format Effect
Status Code A number, for example 503 The status of the response. Empty means 200.
Delay (ms) A number of milliseconds The server waits that long before answering.
Rate Limit <requests>/<window in ms> Requests over the budget get 429 Rate limit exceeded.

This endpoint answers 503 after half a second, and accepts two requests every ten seconds:

In the dashboard:

Field Value
Path /api/slow
HTTP Methods GET
Status Code 503
Delay (ms) 500
Rate Limit 2/10000
Response (JSON File) hello.json

With curl:

curl -X POST http://localhost:3001/register \
  -F path=/api/slow \
  -F methods=GET \
  -F status_code=503 \
  -F delay=500 \
  -F rate_limit=2/10000 \
  -F [email protected]

Call it three times in a row and print the status and the time each call took:

for i in 1 2 3; do
  curl -s -o /dev/null -w "%{http_code} %{time_total}s\n" http://localhost:3001/api/slow
done
503 0.501404s
503 0.502501s
429 0.000696s

The first two calls waited 500 ms and got the registered status. The third was over the limit and was refused right away.

The rate limit is counted per endpoint and per HTTP method. With 10/1000 on an endpoint registered for GET and POST, each method gets its own 10 requests per second.

5. Protect an endpoint

An endpoint with authentication answers 401 Unauthorized unless the request carries the right Authorization header. There are two kinds.

Basic auth

In the dashboard, set Authentication Type to Basic Auth and fill in the username and password.

With curl, send the credentials as JSON in the authentication field:

curl -X POST http://localhost:3001/register \
  -F path=/api/private \
  -F methods=GET \
  -F 'authentication={"username":"admin","password":"secret"}' \
  -F [email protected]
curl http://localhost:3001/api/private
# 401 Unauthorized

curl -u admin:secret http://localhost:3001/api/private
# { "message": "Hello, world!" }

curl -u builds the header for you. Other clients send Authorization: Basic <base64 of username:password>.

Bearer token

In the dashboard, set Authentication Type to Token Auth. The Token Data (JSON) box expects a JSON object with a tokenData field, not the bare token:

{ "tokenData": "my-secret-token" }

With curl:

curl -X POST http://localhost:3001/register \
  -F path=/api/token \
  -F methods=GET \
  -F 'authentication={"tokenData":"my-secret-token"}' \
  -F [email protected]
curl -H "Authorization: Bearer my-secret-token" http://localhost:3001/api/token
# { "message": "Hello, world!" }

These credentials are test data. The server stores them as plain text and returns them in /list, so don't use real ones.

6. Mock a GraphQL API

A GraphQL endpoint takes one file that describes every operation it answers. The file has a query section and a mutation section. Inside each, the key is the operation name and data is the full object that operation can return.

Create graphql.json:

{
  "query": {
    "getUser": {
      "data": { "id": "123", "name": "John Doe", "email": "[email protected]", "age": 30 }
    }
  },
  "mutation": {
    "createUser": {
      "data": { "success": true, "user": { "id": "789", "name": "New User" } }
    }
  }
}

In the dashboard, open the GraphQL tab, choose graphql.json and click Register endpoint. The path and method fields are hidden because they are fixed: the endpoint is always POST /api/graphql.

With curl:

curl -X POST http://localhost:3001/register \
  -F path=/api/graphql \
  -F methods=POST \
  -F isGraphQL=true \
  -F [email protected]

Send a query. The operation name, getUser, picks the mock:

curl -X POST http://localhost:3001/api/graphql \
  -d '{ "query": "query getUser { id name email }" }'
{"data":{"email":"[email protected]","id":"123","name":"John Doe"}}

age is in the file but was not selected, so it is not in the response. Nested selections work the same way:

curl -X POST http://localhost:3001/api/graphql \
  -d '{ "query": "mutation createUser { success user { id } }" }'
{"data":{"success":true,"user":{"id":"789"}}}

What the request has to look like:

  • The body is JSON with a query field holding the GraphQL text.
  • The operation must be a named query or mutation. { id } with no name, or a subscription, gets 400 Invalid GraphQL request.
  • A name that is not in the file gets 404 Resource not found.
  • Arguments and variables are accepted by the parser and ignored. The answer depends only on the operation name and the selected fields.

A longer sample file is in uploads/graphql.json.

7. Mock a gRPC call

mockiapi does not speak the gRPC wire protocol. It simulates a call as a plain HTTP request: the client posts JSON naming the service and the method, and gets back the JSON you registered for that pair.

Create book.json, the answer for BookService.GetBook:

{
  "id": "b123",
  "title": "The Rust Programming Language",
  "author": "Steve Klabnik"
}

In the dashboard, open the gRPC tab and fill in:

Field Value
Service com.example.BookService
RPC Method GetBook
Response (JSON File) book.json

With curl:

curl -X POST http://localhost:3001/register \
  -F path=/grpc \
  -F methods=POST \
  -F grpcService=com.example.BookService \
  -F grpcRPC=GetBook \
  -F [email protected]

Every gRPC mock is called at POST /grpc. The body names the service and the method:

curl -X POST http://localhost:3001/grpc \
  -d '{ "service": "com.example.BookService", "rpc": "GetBook", "request": { "id": "b123" } }'
{"author":"Steve Klabnik","id":"b123","title":"The Rust Programming Language"}

How it behaves:

  • To mock more methods, register again with another service and RPC method. They all share /grpc.
  • The request field is accepted but not looked at. Any payload gets the same answer.
  • A service or method that was not registered gets 404 with {"error":"Mock not found"}.
  • The status code and delay from the form apply to the answer.

8. List, change and delete endpoints

The dashboard lists every endpoint on the left, with its methods and its path. A path with one endpoint for GET and another for POST shows up twice. Group by splits the list by the group you gave each endpoint, or by HTTP method. Click an endpoint to open it:

  • The form shows its settings. Change the status code, the delay, the rate limit, the methods or the authentication and click Save changes.
  • The Response box shows what the endpoint answers now. Edit the text and click Save changes, and the next call gets the new response. Format indents it when it is valid JSON. To replace it with a file, switch to File.
  • The Try it panel calls the endpoint and shows what it answers. The path is editable, so you can fill in {id} segments and query parameters, and a POST or PUT request can carry a body. The same request is shown as a curl command.
  • Delete removes it.

New endpoint, at the top, goes back to an empty form. The search box above the list filters it by path or group, and the open endpoint is kept in the address of the page, so a reload comes back to it.

A gRPC mock cannot be changed without a file: fill in the service and the method again and choose its response.

With curl, change an endpoint by registering its path and method again. Without -F file=..., the response is kept:

curl -X POST http://localhost:3001/register \
  -F path=/api/hello \
  -F methods=GET \
  -F status_code=503

To change the methods of an endpoint, name it by the id that /list gives it. Without the id, -F methods=PUT would register a second endpoint next to the GET one:

curl -X POST http://localhost:3001/register \
  -F id=1 \
  -F path=/api/hello \
  -F methods=GET,PUT

List them:

curl http://localhost:3001/list
[
  {
    "id": 3,
    "path": "/api/slow",
    "type": "REST",
    "method": ["GET"],
    "group": null,
    "file": "uploads/b2bc44bf-f5eb-4c0e-aebf-4061dd9f3e1b.json",
    "status_code": 503,
    "delay": 500,
    "rate_limit": { "requests": 2, "window_ms": 10000 },
    "with_dynamic_vars": null
  }
]

The list is in the order the endpoints were registered. Up to 0.1.9 it was an object keyed by path, which could not hold two endpoints of one path.

Read the response an endpoint holds, by its id:

curl http://localhost:3001/content/3
{ "message": "Hello, world!" }

Delete one the same way:

curl -X DELETE http://localhost:3001/delete/3
Deleted successfully

After that, GET /api/slow is back to 404.

Both also take the registered path in place of the id, URL-encoded (/ becomes %2F): curl -X DELETE http://localhost:3001/delete/%2Fapi%2Fhello. By path, delete removes every endpoint of that path, and content answers only when the path has a single one.

9. Start with your mocks already loaded

Registering by hand is fine while you explore. For a set of mocks you want every day, in CI or in a container, describe them in a file and give it to the server:

./mockiapi-linux-amd64 --mocks mocks.yaml
.: Loaded 3 endpoints from mocks.yaml
.: Server running at http://localhost:3001

The endpoints are registered before the port is opened, so the first request already finds them. The file can live in your repository next to the code that calls the API.

The mocks file

Write it in YAML (.yaml or .yml) or in JSON (any other extension). Both take the same fields.

endpoints:
  - path: /api/users
    methods: [GET]
    group: users
    file: responses/users.json        # relative to the mocks file

  - path: /api/users
    methods: [POST]
    group: users
    status_code: 201
    body:                             # or write the response right here
      id: 3
      name: Grace

  - path: /api/users/{id}
    with_dynamic_vars: true
    body: '{ "id": "{{id}}", "name": "Ada" }'

The same file in JSON:

{
  "endpoints": [
    { "path": "/api/users", "methods": ["GET"], "group": "users", "file": "responses/users.json" },
    { "path": "/api/users", "methods": ["POST"], "group": "users", "status_code": 201, "body": { "id": 3, "name": "Grace" } },
    { "path": "/api/users/{id}", "with_dynamic_vars": true, "body": "{ \"id\": \"{{id}}\", \"name\": \"Ada\" }" }
  ]
}
Field Required Value
path yes As in a registration: starts with /, may contain {name} segments and a query string
methods no A list. Defaults to [GET], and to [POST] for GraphQL and gRPC
file or body one of them The response. file is a path relative to the mocks file. body is the response itself; written as text it is used as it is, which is how a template with bare {{name}} placeholders is given
group no The label the dashboard sorts the endpoint under
status_code, delay no Numbers, as in a registration
rate_limit no 10/1000, or { requests: 10, window_ms: 1000 }
authentication no { username: ..., password: ... } or { tokenData: ... }
with_dynamic_vars no true to replace {{name}} placeholders
type no REST (the default), GraphQL or gRPC
grpcService, grpcRPC for gRPC The service and the method the mock answers

A complete example with every kind of endpoint is in tests/fixtures/mocks/mocks.yaml.

The server does not start with a file it cannot load whole. It stops with exit code 1 and says which endpoint and why:

error: could not load mocks.yaml: endpoint 2 (/api/users): the response file responses/users.json could not be read: No such file or directory (os error 2)

The same goes for a field it does not know, which is usually a typo, and for two endpoints of the file that answer the same method on the same path.

Endpoints that came from a file are like any other afterwards: they are listed, and they can be changed and deleted in the dashboard or over HTTP. Those changes are not written back to the file, and the file is registered again at the next start: see together with a mocks file. The server works on copies in uploads, so it never changes or deletes your files.

A Postman collection

--mocks also takes a collection exported from Postman (v2.1 or v2.0):

./mockiapi-linux-amd64 --mocks shop.postman_collection.json

Every request that has a saved example becomes an endpoint:

  • the method and the path come from the request, and the status code and the body from its first example
  • GET /users and POST /users become two endpoints, each with its own response
  • a path variable such as /users/:id becomes /users/{id}
  • the host, a {{baseUrl}} variable in its place and the query string are left out
  • requests inside folders are read at any depth, and the outermost folder becomes the group

A request that cannot become an endpoint is skipped with a warning, and the rest of the collection is still loaded:

warning: "Login page" (GET /login) was skipped: it has no saved example to answer with
.: Loaded 4 endpoints from shop.postman_collection.json

That happens to a request with no saved example, with an example whose body is not JSON, or that repeats the method and path of an earlier one. Authorization settings, scripts and variables other than the base of the URL are not read.

With Docker

Mount the directory that holds the file and name it with MOCKS, or with --mocks after the image name:

docker run -p 3001:3001 -v "$PWD/mocks:/mocks" -e MOCKS=/mocks/mocks.yaml edufsantos/mockiapi

In a docker-compose.yml:

services:
  mockiapi:
    image: edufsantos/mockiapi
    ports:
      - "3001:3001"
    volumes:
      - ./mocks:/mocks:ro
    environment:
      MOCKS: /mocks/mocks.yaml

From the dashboard

Import file, at the top, takes the same three kinds of file and registers their endpoints on a running server. With curl:

curl -X POST http://localhost:3001/import -F [email protected]
{ "registered": 3, "warnings": [] }

The name of the file tells YAML from JSON. An imported endpoint replaces the ones it overlaps, by the same rule as a registration, and the others stay. The file is taken whole or not at all: a refusal answers 400 with the reason.

An uploaded file has no directory of its own, so file: does not work in it. Write every response in body.

10. Keep your endpoints across restarts

Nothing to set up: every endpoint you register, change or delete is saved, and the server brings them back the next time it starts, each with the id it had.

.: Restored 3 endpoints from uploads/endpoints.json
.: Server running at http://localhost:3001

The settings of the endpoints are in uploads/endpoints.json, and each response is in its own file in the same directory. The file is plain JSON with the fields GET /list shows. It is written when an endpoint changes and read once at startup, never while a mock is being served.

uploads is created in the directory the server was started from. To find the same endpoints wherever you start it, choose the directory yourself.

Good to know:

  • The credentials of a protected endpoint are saved as plain text. They are mock credentials, but do not reuse a real password or token there.

  • An endpoint whose response file is missing is skipped with a warning, and the others are restored:

    warning: skipped a saved endpoint: GET /api/hello: the response file uploads/1f0c.json could not be read: No such file or directory (os error 2)
    
  • If endpoints.json itself cannot be read, because it was edited by hand into something that is not valid or was written by a newer version, the server stops and says why. It does not start empty, since the next change would write over the file.

  • Rate limit counters are not saved. Every limit starts fresh.

Choose where the data is kept

Pass --data-dir, or set the DATA_DIR environment variable. The argument wins when both are given. The directory is created if it is not there.

./mockiapi-linux-amd64 --data-dir ~/.local/share/mockiapi
DATA_DIR=~/.local/share/mockiapi ./mockiapi-linux-amd64

endpoints.json and the responses then live in that directory, and the server finds them from any working directory:

.: Restored 3 endpoints from /home/you/.local/share/mockiapi/endpoints.json

endpoints.json names each response by its file name only, so the directory can be moved, renamed or mounted somewhere else: point --data-dir at the new place. That includes an uploads directory written by an earlier version, which is read as it is and saved in the new form at the next change. A version older than 0.1.10 does not read the new form, and says so.

Start empty

--no-persist starts with no endpoints and keeps the new ones in memory only. What an earlier run saved is not loaded and not touched, so it is back at the next start without the flag.

./mockiapi-linux-amd64 --no-persist
NO_PERSIST=true ./mockiapi-linux-amd64

The variable takes true, yes or 1. With Docker it saves replacing the command: docker run -e NO_PERSIST=true ....

Together with a mocks file

With --mocks, the saved endpoints are restored first and the file is registered over them. Where both answer the same method of the same path, the file wins at every start, so a change made in the dashboard to an endpoint that came from the file lasts until the next restart. Endpoints the file does not mention are kept as they were saved.

With Docker

A container has its own file system, so the endpoints go away with it unless the data directory is a volume. Name the directory with DATA_DIR and mount the volume there:

docker run -p 3001:3001 -e DATA_DIR=/data -v mockiapi-data:/data edufsantos/mockiapi

Without DATA_DIR the image keeps its data in /app/uploads, so a volume mounted there by an earlier setup still works. The docker-compose.yml of this repository keeps that path and names it, so the variable and the volume are seen to go together:

services:
  mockiapi:
    image: edufsantos/mockiapi
    ports:
      - "3001:3001"
    environment:
      DATA_DIR: /app/uploads
    volumes:
      - mockiapi-data:/app/uploads

volumes:
  mockiapi-data:

A volume can change its mount point at any time: nothing in it has to change, as long as DATA_DIR follows.

Reference

Registration fields

POST /register takes a multipart form. These are the fields the dashboard sends.

Field Required Value
id no The id of the endpoint to change, as GET /list gives it. Needed only to change its methods.
path yes Starts with /. May contain {name} segments and a query string.
methods yes Comma-separated HTTP methods, for example GET,POST
group no A label such as users, used to sort the list in the dashboard
file for a new endpoint The JSON response file, 5 MB at most. Left out for an endpoint that already exists, the response is kept (not for gRPC).
status_code no Defaults to 200
delay no Milliseconds
rate_limit no <requests>/<window in ms>
authentication no {"username":"...","password":"..."} or {"tokenData":"..."}
with_dynamic_vars no true to replace {{name}} placeholders (REST only)
isGraphQL no true for a GraphQL endpoint
grpcService, grpcRPC no Both set for a gRPC mock

A form the server refuses gets 400 with the reason as a JSON string, for example "path is required and must start with /".

Reserved paths

POST /register, POST /import, GET /list, GET /content/... and DELETE /delete/... belong to the server, and so do the dashboard's own files (/, /assets/...). They are matched before the mocks, so a mock registered on one of them is never reached.

Answers the server gives on its own

Status Body When
400 Invalid GraphQL request The GraphQL body is not a named query or mutation
400 Invalid gRPC request The gRPC body has no service or rpc
401 Unauthorized Missing or wrong Authorization header
404 Resource not found No endpoint matches the path
405 Method not allowed The path is registered, but no endpoint of it answers this method
429 Rate limit exceeded The endpoint's budget for this method is used up

Logs

Logging is off unless the RUST_LOG environment variable is set. With RUST_LOG=info, the server writes one line per request with the client address, method, path, status, time taken and headers. The values of the Authorization, Proxy-Authorization and Cookie headers are replaced by <redacted>, so the log never holds credentials.

Development

The server embeds the dashboard, so the dashboard is built first:

cd frontend
npm install
npm run build
cd ..
cargo test

npm run build produces frontend/dist, with a gzip copy (.gz) next to each text file. The server sends that copy to clients that accept gzip, so it never compresses anything itself. Without frontend/dist, cargo build and cargo test stop with a message that says to build the frontend.

The dashboard is written in TypeScript. npm run check inside frontend/ type-checks it.

How the server gets the dashboard depends on the build:

  • A release build (cargo build --release) compiles frontend/dist into the binary. Rebuild the server after changing the dashboard.
  • A debug build (cargo run) reads frontend/dist from disk on every request, so npm run build is enough to see a dashboard change.

Releasing

A push to main builds and tests, and publishes nothing. A release is made by a version tag:

  1. Set the new version in Cargo.toml, run cargo build so Cargo.lock follows, and merge that to main.
  2. Tag that commit with the same number and push the tag:
git tag v0.2.0
git push origin v0.2.0

The workflow then checks that the tag matches Cargo.toml, creates a GitHub release named after the tag with notes generated from the merged pull requests, attaches the binaries to it (Linux and macOS for both amd64 and arm64, Windows for amd64), and publishes the crate to crates.io. The crate goes last, because a version published there cannot be replaced.

The same tag also builds the Docker image and pushes it to Docker Hub as edufsantos/mockiapi:<version> and latest, for linux/amd64 and linux/arm64. Each platform is built on a runner of its own architecture and the two are gathered under the same tags. That is a workflow of its own, Docker, which can also be run by hand from the Actions tab to build the image of a tag that already exists.

The repository secrets these need:

Secret For
CARGO_REGISTRY_TOKEN A crates.io API token, to publish the crate
DOCKERHUB_USERNAME, DOCKERHUB_TOKEN A Docker Hub user and access token that can push edufsantos/mockiapi

License

Licensed under either of MIT or Apache 2.0, at your option.

Ähnliche Projekte entdecken

Wird geladen…