How to create an API Rest using json-server and Docker
Before you begin
In this tutorial, we’ll learn how to create a JSON API Rest using json-server and Docker. A GNU Linux/Mac OS machine and Docker will be required to follow this tutorial.
Create a Docker image
Dockerfile:
FROM debian:10-slim
ENV tmp_dir /tmp
RUN apt-get update \
&& apt-get install -y curl \
&& curl -sL https://deb.nodesource.com/setup_12.x | bash - \
&& apt-get install -y nodejs
RUN npm install -g json-server
RUN echo '{"cars":[{"id":1,"brand":"opel","model":"corsa"},{"id":2,"brand":"ford","model":"fiesta"}]}' > /tmp/test.json
ENTRYPOINT ["json-server", "--port", "8080", "--host", "0.0.0.0"]
CMD ["/tmp/test.json"]
Run containerized JSON Server
Commands to build and run the server on port 8080:
# Build previous image
$ docker build -t jsonserver .
# Run container
$ docker run --rm -it --name jsonserver-container -p 8080:8080 jsonserver
Copy JSON file to a Docker container
By default the image contains a /tmp/test.json with example of cars but you can overwrite it using a local/remote JSON file.
Remote file:
$ docker run --rm --name jsonserver-container -p 8080:8080 -e "file=https://REMOTE_FILE.json" -it jsonserver
Local file:
$ docker cp MY_LOCAL_FILE.json jsonserver-container:/tmp/test.json
Test JSON Server API
HTTP calls examples based on the following test.json:
{
"cars": [
{
"id": 1,
"brand": "opel",
"model": "corsa"
},
{
"id": 2,
"brand": "ford",
"model": "fiesta"
}
]
}
GET
$ curl http://0.0.0.0:8080/cars
POST
$ curl -i -H "Accept: application/json" -H "Content-type: application/json" -d '{"brand":"seat","model":"ibiza"}' -X POST http://0.0.0.0:8080/cars $ curl -H "Accept: application/json" -H "Content-Type: application/json" -X POST -d '{"brand":"seat","model":"ibiza"}' http://0.0.0.0:8080/cars
PUT
$ curl -H "Accept: application/json" -H "Content-Type: application/json" -X PUT -d '{"brand":"opel","model":"astra"}' http://0.0.0.0:8080/cars/1
More info about json-server at:
https://www.npmjs.com/package/jsonserver
https://github.com/typicode/json-server
Loading Comments
DevOps books:
Cloud providers:

DigitalOcean offers affordable pricing for VMs and many other public cloud services. You can sign up for DigitalOcean and receive a $100 free credit using this referral link.