Before you begin

In this tutorial will learn how to create an API Rest using json-server and Docker. A Linux machine and Docker will be required to follow this tutorial.

Create a Docker image

Dockerfile:

FROM ubuntu:14.04

ENV tmp_dir /tmp

WORKDIR ${tmp_dir}

RUN apt-get update \
  && apt-get install -y curl wget vim \
  && curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash - \
  && apt-get install -y nodejs

RUN npm install -g json-server

#ADD test.json /tmp
RUN echo '{"cars":[{"id":1,"brand":"opel","model":"corsa"},{"id":2,"brand":"ford","model":"fiesta"}]}' > /tmp/test.json

ADD entrypoint.sh ${tmp_dir}

RUN chmod +x entrypoint.sh

ENTRYPOINT ["./entrypoint.sh"]

Run container/server

Commands to build and run the server on port 8080:

# Build previous image
$ docker build -t jsonserver .

# Run container
$ docker run --rm --name jsonserver-container -p 8080:8080 -it jsonserver

Copy JSON file

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 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