Intro to GraphQL

Used by Facebook, GraphQL is a flexible query language for APIs and a runtime for fulfilling those queries with your data. GraphQL gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools.

Although GraphQL is supported at the back end by various languages such as PHP, Go, Python, Ruby, we will illustrate how to use GraphQL with a Node.js Express server below.Server Side Server Side Server Side (Express) (Express) (Express)

To install the dependencies:

npm install express express-graphql graphql cors

server.js:

# schema.graphqlschema{ query: Student mutation: UpdateStudent}type Student{ name: String sid(year: Int): ID subjects: [String] address: Location}type Location{ unit: String city: String country: String postCode: Int}type UpdateStudent{ setName(nn: String): String}
RESETRUNFULL
// server.jsconst express = require('express');const { graphqlHTTP } = require('express-graphql');const { buildSchema } = require('graphql');const cors = require( `cors` );   // deals with Cross-Origin issuesvar fakeDatabase = [{sid:parseInt(Math.random()*10000),
                                name:'Philip',
                                subjects:['Chemistry', 'Physics', 'Maths'],
                                address:{
                                    unit: 'H505',
                                    city: 'London',
                                    country: 'United Kingdom',
                                    postCode: 33100}}];var schema = buildSchema(fs.readFileSync('schema.graphql','utf8'));// Each field is either a constant or a callbackvar root = {
  name: ()=>fakeDatabase[0].name,
  sid: arg => (arg.year+"-"+fakeDatabase[0].sid),
  subjects: fakeDatabase[0].subjects,
  address: () => ({
     city: ()=>fakeDatabase[0].address.city
  }),
  setName: arg => {fakeDatabase[0].name=arg.nn; return arg.nn;}};var app = express();app.use(cors());app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: root,
  graphiql: true,}));app.listen(4000);console.log('Running a GraphQL API server at http://localhost:4000/graphql');

To launch the GraphQL server:

node server.js

If you navigate in a browser to http://localhost:4000/graphql, you should see an interface that lets you update data and enter queries:

...

Client-side Client-side Client-side

Run the following JavaScript to obtain data from the GraphQL server:


RESETRUNFULL
fetch('http://127.0.0.1:4000/graphql', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
  },
  body: JSON.stringify({query: "{ name subjects }"})}).then(r => r.json()) .then(data => console.log('data returned:', data));

You should see the data returned, logged in the console:

Generic Wrapper Generic Wrapper Generic Wrapper On the client side, we can extract out the desired functionality with a wrapper function:


RESETRUNFULL
// fetchGraphQL.jsasync function fetchGraphQL(text, variables) {
   const response = await fetch('http://127.0.0.1:4000/graphql', {
      method: 'POST',
  headers: { 'Content-Type': 'application/json',
                      'Accept': 'application/json'},
      body: JSON.stringify({query: text, variables}),
   });
   return await response.json();}export default fetchGraphQL;