Create Fake API REST with JSON-Server and Now

Many times we want to create an API Rest quickly and work beyond our localhost, then JSON-Server and Now come to the rescue.

Now allows us to publish static portals, but also applications with Node, so we will publish our API rest using JSON-server.

mkdir myfakeapp npm init -y npm install json-server --save-dev

API

To create the API using json-server, first creates a file db.json with the definition of the API so that json-server generates the verbs get, post, put and delete of the different entities that we define into the file.

{ "Games": [ { "id": 1, "vsteam": "Raptors", "date": "12/12/2017", "result": 0 } ] }

Server

Now we create a file server.js which will start the configuration of our json-server.

const jsonServer = require ('json-server') const server = json Server.create () const router = jsonServer.router ('db.json') const middlewares = json Server.defaults () server.use (middlewares) server.use (router) server.listen (3000, () => { console.log ('JSON Server is running') });

Deploy

Now we have to publish our API with Now, nothing complicated if we have Now installed we just have to write Now from the terminal and detect from our package.json the dependencies and I will start our API.

danyparedes @ danyimac ~ / Documents / fakeapi now > Deploying ~ / Documents / fakeapi under danywalls4@gmail.com > Using Node.js 8.9.1 (default) > Ready! https://fakeapi-sfrmdwbrsq.now.sh (copied to clipboard) [5s] > You (danywalls4@gmail.com) are on the OSS plan. Your code and logs will be made public. > NOTE: You can usenow —publicto skip this prompt > Synced 1 file (130B) [2s] > Initializing ... > Building > ▲ npm install > ⧗ Installing 1 main dependency ... > ✓ Installed 232 modules [3s] > ▲ npm start >> fakeapi@1.0.0 start / home / nowuser / src >> node server.js > JSON Server is running > Deployment complete!

We already have our API ready to be used from our application, you can read more in https://github.com/typicode/json-server and https://zeit.co/docs/deployment-types/node #backend #node #rest #api