Dockerized json-server for building a full fake RESTful API.
Created with <3 for front-end developers who need a quick back-end for prototyping and mocking.
Note: This version uses json-server v1 (beta), which is a ground-up rewrite. Many CLI options from v0 have been removed. See Options for the current set of supported configuration.
- Features
- Getting Started
- Usage
- Database File
- Middleware
- Typescript Support
- Options
- Query Parameters
- Maintaining/Contributing
- 💨 Up and running quickly - Spin up a RESTful mock API in seconds.
- ⚙️ Configurable - Supports
json-serverv1 configuration via environment variables.
Typescript support - Use TS for your db, middleware, or
any file you mount into the container.- 💻 Mount in any supporting files you'd like! - For instance, want to use your custom data fixtures, utils, etc. in your db/middleware? Mount them in, import & prosper.
- 📦 Useful dependencies are pre-installed in the image for your convenience. Use
lodash-es&@faker-js/fakerin any of the files powering your mock api. - 🧳 Install your own dependencies - Use the
DEPENDENCIESenvvar to pass a list of additional npm dependencies to use in your server files. - 🔂 Hot reloading the server on any changes.
Latest Version: codfish/json-server:1.0.0-beta.12
Note
You are reading the docs for the v1 beta of json-server-docker. If you'd prefer the stable v0 release, run
docker run -p 3000:80 codfish/json-server:0.17.4 and view the
v0 documentation.
By default, the image runs an instance of json-server with some dummy data for show. Spin up the example mock api in
seconds.
# Visit <http://localhost:3000> to see it in action.
docker run -p 3000:3000 codfish/json-serverThat's all good, but not very useful to you. You're meant to mount in your own db file(s) into the container. Read on for usage...
Warning
It's recommended to specify the tag of the image you want rather than using the latest image, which might break. Image tags are based off of the release versions for json-server. However there is not an image for every version. See the available versions on Docker Hub.
This project actually dogfoods itself. View the docker-compose.yml & the
examples/ directory to see various usage examples. Also visit the
json-server docs for more detailed examples on how to use the tool.
Examples
- Simple json file
- Installing extra dependencies
- Typescript
- Mount in additional files
- Custom middleware
- Static files
services:
api:
image: codfish/json-server:1.0.0-beta.12
ports:
- 3000:3000
volumes:
- ./my-db.js:/app/db.js:delegated
- ./my-middleware.js:/app/middleware.js:delegatedRun docker compose up api. Visit http://localhost:3000/ to see your API.
Tip
The server listens on 0.0.0.0:3000 by default inside the container. Mapping a different host port (e.g.
-p 3001:3000) will work fine, but your logs will still say localhost:3000. For the best DX, pass the PORT env
var to sync them (e.g., docker run -e PORT=3001 -p 3001:3001 ...).
docker run -d -e PORT=3001 -p 3001:3001 \
-v ./my-db.js:/app/db.js \
-v ./my-middleware.js:/app/middleware.js \
codfish/json-server:1.0.0-beta.12Set configuration via environment variables.
services:
json-server:
image: codfish/json-server:1.0.0-beta.12
volumes:
- ./db.ts:/app/db.ts:delegated
- ./middleware.ts:/app/middleware.ts:delegated
environment:
DEPENDENCIES: chance@1 node-emoji@1See all the available options below.
- IDs must be strings. json-server v1 uses strict equality (
===) to match URL params against record IDs. Since URL params are always strings, integer IDs will never match on individual resource lookups (e.g.,GET /users/1). Use string IDs like"1"or UUIDs. - All mounted files should use ESM syntax (
import/export default). - All files should be mounted into the
/appdirectory in the container. - The following files are special and will "just work" when mounted over:
/app/db.{ts,js,json}- The database file. JS/TS files mustexport defaulta function that returns your data./app/middleware.{ts,js}- Custom middleware file. Mustexport defaulta(req, res, next)function./public- Static files directory.
When building your mock api's you'll most like want to generate some fake data and return a number of items for a specific collection. Faker is included in the image to help facilitate doing these sorts of things inside your db or middleware files. For example:
// db.js
import { faker } from '@faker-js/faker';
export default () => ({
posts: faker.helpers.multiple(
() => ({
id: faker.string.uuid(),
title: faker.lorem.words(3),
body: faker.lorem.paragraphs(3),
}),
{ count: 100 },
),
});Mount a middleware.{js,ts} file to add custom middleware that runs before json-server's route handlers. This is
useful for things like authentication checks, request mutation, custom headers, and logging.
// middleware.ts
export default (req, res, next) => {
// Add custom response headers
res.set('X-Custom-Header', 'my-value');
// Require authorization for non-browser requests
if (!req.accepts('html') && !req.header('Authorization')) {
res.status(401).send();
return;
}
next();
};Important
- Use
export default ...for default exports from your ts files. - TS is configured to target ESM (
es2022/nodenext). - A path alias is configured for your convenience to map to the
/appdirectory where all server files should be mounted. - When importing local files in TS, use the
.jsextension (e.g.,import foo from './fixtures/bar.js').
// db.ts
import { faker } from '@faker-js/faker';
interface Database {
posts: Array<{
id: string;
title: string;
body: string;
}>;
}
export default (): Database => ({
posts: faker.helpers.multiple(
() => ({
id: faker.string.uuid(),
title: faker.lorem.words(3),
body: faker.lorem.paragraphs(3),
}),
{ count: 10 },
),
});docker run -d -e PORT=3000 -p 3000:3000 -v ./db.ts:/app/db.ts codfish/json-server:1.0.0-beta.12json-server v1 has significantly fewer configuration options than v0. The following environment variables are
supported:
| Option | Description | Default |
|---|---|---|
DEPENDENCIES |
Install extra npm dependencies in the container for you to use in your server files. | — |
STATIC |
Serve an additional static files directory (./public is always served) |
— |
PORT |
Set the port the server listens on inside the container. | 3000 |
Caution
The DEPENDENCIES env var runs pnpm add with whatever packages you specify. A malicious package's install script
will execute inside the container. Only use packages you trust.
json-server v1 supports the following query parameters:
- Pagination:
_pageand_per_page(e.g.,?_page=1&_per_page=10) - Sorting:
_sort(e.g.,?_sort=idor?_sort=-idfor descending) - Filtering: Use field names directly (e.g.,
?title=foo) - Embedding:
_embed(e.g.,?_embed=comments)
Note: The
_expandandq(full-text search) parameters from v0 have been removed in v1.
This project dogfoods itself. To test it directly you can run:
git clone git@github.com:codfish/json-server-docker.git
cd json-server-docker
docker compose up -dIf you want to test it locally without docker, you can pnpm install and then pnpm start to run the server directly
on your machine.
The docker-compose.yml defines several services that exercise different features. Each one maps to a directory in examples/.
| Service | Port | Description |
|---|---|---|
docker-compose up basic |
3000 | Default db.js with faker-generated data |
docker-compose up typescript |
9998 | TypeScript db & middleware |
docker-compose up json-db |
9997 | Plain JSON database file |
docker-compose up middlewares |
9996 | Custom middleware that sets response headers |
docker-compose up deps |
9995 | Extra dependencies installed via DEPENDENCIES envar |
docker-compose up static |
9993 | Custom public directory with static HTML |
docker-compose up dags |
9994 | Supporting files mounted alongside the db |
Run all examples:
docker compose up --buildOr run a specific one:
docker compose up --build typescriptVisit the corresponding port (e.g., http://localhost:9998) to verify.
To update:
- Bump version of
json-serverinpackage.json - Bump node dependencies
- Test it out
docker compose up -d --buildVisit http://localhost:3000. Update db.js or middleware.js to test out
functionality. Changes should propagate automatically, just refresh the page.
New version:
git tag -m '1.0.0-beta.12' 1.0.0-beta.12
git push origin 1.0.0-beta.12Pushing a tag triggers the release workflow, which builds and pushes the Docker image tagged with the version.
Updating old version
We keep our versions in sync with json-server. This scenario would happen if there's a bug fix or feature change with
our implementation but the json-server version doesn't change.
git tag -fa 1.0.0-beta.12 -m "Update 1.0.0-beta.12 tag" && git push origin 1.0.0-beta.12 --forceForce-pushing the tag re-triggers the release workflow to rebuild the image.