Showing posts with label GraphQL. Show all posts
Showing posts with label GraphQL. Show all posts

Sunday, August 26, 2018

How to work with fake REST API?


Sometimes it is necessary to work with fake REST API for practice projects. To achieve such necessity we can implement JSON Server as follows:

npm install --save json-server

the above command is to install json-server package on nodejs project. Then next we can create a json file name db.json and can add json data as follows:

{
    "users": [
        {"id": "23", "firstName": "Bill", "age": 20},
        {"id": "44", "firstName": "Samantha", "age": 30}
    ]
}

Now we need to add script inside the package.json file with this text "json:server": "json-server --watch db.json" and full scripts as follows:

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "json:server": "json-server --watch db.json"
  },


To run json server we can execute the command as follows:

npm run json:server

We can now access the db.json file's contents using the server url http://localhost:3000/users. 

To know more: https://github.com/typicode/json-server

Friday, August 24, 2018

How To Setup GraphQL With NodeJs

We know about RESTFul API which has some complexity in different cases, for example nested http request like domain.com/api/user/frinds/positions/companies and also mutiple http requests concurrently which make the server slow down. And of-course chunk of information instead of full model.

To overcome such problems, GraphQL comes which is a query language for API and querying data as runtime.

To setup GraphQL with NodeJs following steps need to be followed:

npm init 

the above command is to initiate NodeJs environment.

npm install --save express express-graphql graphql lodash

through the above command we will install some dependency packages like express for NodeJs server express-graphql the middleware or bridge layer between express and graphql and lodash is for some utility features.

After installing dependency packages above we need to create express server by creating a file named server.js and add code as follows:

const express = require('express');
const expressGraphQL = require('express-graphql');

const app = express();

app.use('/graphql', expressGraphQL({
    graphiql: true
}));

app.listen(4000, () => {
    console.log('Listening');
});

in the above code we have created express nodejs http server to listen the port number 4000 and then bound graphql middleware with expressjs.