MENU
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 (Express)
To install the dependencies:
| npm install express graphql-http graphql cors |
'schema.graphql' and 'server.js':
schema.graphql:
# schema.graphql
schema{
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
}// server.jsconst fs = require('fs');const express = require('express');const { createHandler } = require('graphql-http/lib/use/express');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.all('/graphql', createHandler({
schema: schema,
rootValue: root,
}));app.listen(4000);console.log('Running a GraphQL API server at http://localhost:4000/graphql');To launch the GraphQL server:
| node server.js |
Unlike some older GraphQL server packages, graphql-http is a minimal, spec-compliant implementation and does not bundle a browser GUI for entering queries by hand. You can verify the server is working with a tool like curl or Postman, or simply by running the fetch() example below.
Client-side
Run the following JavaScript to obtain data from the GraphQL server:
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. On the client side, we can extract out the desired functionality with a wrapper function:
// 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;