GraphQL for beginners


What is GraphQL?

GraphQL is a query language for APIs.


Simply put, it's a query language. It's a way to ask an API for data and talk to an API.

API ( downloaded from Wikipedia ):

Application Programming Interface (API) is a connection between a computer or computer program and software service. It is a software interface that enables the programmer to access the service.


How to create a GraphQL server


First, create a folder called graphql-api. Open it in your terminal and run npm (Node package manager). This assumes you have Node installed link. Here are the steps:

mkdir graphql-api
cd graphql-api
npm init -y

Then install the following packages:

npm install express graphql express-graphql --save

Create a file called schema.js:

touch schema.js

The first thing to do is to define what kind of data we want to get from the API. In this case, we want to get a string. So, we define a GraphQLObjectType called RootQueryType. This is the root of our GraphQL schema. The schema defines the kinds of data we want to get from the API.

const graphql = require('graphql')
const {
GraphQLString,
GraphQLObjectType,
GraphQLSchema
} = graphql
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
data: {
type: GraphQLString,
resolve(parent, args, context, info) {
return 'Hello World';
},
},
},
})
module.exports = new GraphQLSchema({
query: RootQuery,
})

To fulfill the request, we need to define a function called resolve. This function is called when the request is made. It's a function that returns the data we want to return:

resolve(parent, args, context, info) {
return 'Hello World';
}
ArgumentsExplanation
parentResolver return for the parent of a particular field
argsAn object that contains all the GraphQL arguments that exist for a particular field
contextAn object divided by each resolver that performs a particular operation
infoContains information on the status of the operation

For real use cases, we need to create a server. We can do this by creating a file called server.js. Let's run the following command in the terminal to download Express.js dependencies:

npm install express express-graphql graphql --save

Then create a file called server.js and add the following code:

const express = require("express");
const { graphqlHTTP } = require("express-graphql");
const schema = require("./schema")
const app = express();
app.use(
"/graphql",
graphqlHTTP({
schema,
graphiql: true,
})
);
app.listen(4000, () => {
console.log("Running a GraphQL API server at http://localhost:4000/graphql");
});

Now, we can run the server by running the following command in the terminal:

node server.js

  • Another example

In the schema.js file, we define the following:


const {
GraphQLSchema,
GraphQLObjectType,
GraphQLString,
GraphQLID,
GraphQLList,
} = require("graphql");
const Users = require("./data/users");
const Posts = require("./data/posts");
const userType = new GraphQLObjectType({
name: "User",
fields: () => ({
id: { type: GraphQLID },
username: { type: GraphQLString },
email: { type: GraphQLString },
posts: {
type: new GraphQLList(postType),
resolve(parent, args) {
const posts = Posts.filter(
(posts) => posts.user_id === JSON.stringify(parent.id)
);
return posts;
},
},
}),
});
const postType = new GraphQLObjectType({
name: "Post",
fields: () => ({
id: { type: GraphQLID },
title: { type: GraphQLString },
text: { type: GraphQLString },
user_id: { type: GraphQLID },
user: {
type: userType,
resolve(parent, args) {
const user = Users[parent.user_id - 1];
return user;
},
},
}),
});
const RootQuery = new GraphQLObjectType({
name: "RootQuery",
fields: {
user: {
type: userType,
args: { id: { type: GraphQLID } },
resolve(parent, args) {
const user = Users[args.id - 1];
return user;
},
},
users: {
type: GraphQLList(userType),
resolve(parent, args) {
const users = Users;
return users;
},
},
post: {
type: postType,
args: { id: { type: GraphQLID } },
resolve(parent, args) {
const post = Posts[args.id - 1];
return post;
},
},
posts: {
type: new GraphQLList(postType),
resolve(parent, args) {
return Posts;
},
},
},
});
module.exports = new GraphQLSchema({
query: RootQuery,
});

So, we have a GraphQL schema that defines the following:

  • A user
  • A list of users
  • A post
  • A list of posts

Each of these objects has a field that returns the data we want to return.

In the new folder called data, we create the following files:

  • users.js
  • posts.js
    as follows: link

Open the graphql explorer by entering the following URL in your browser:

http://localhost:4000/graphql

Send a request to the server by entering the following query in the GraphQL explorer:

query {
{
user (id: 1) {
username
posts {
id
text
title
}
}
}

Play around with the GraphQL explorer to see how the data is returned. Now, you're ready to start building your GraphQL API. In addition to the Query type, you can also define the following types:

  • A mutation type
  • A subscription type In the next posts, we'll learn how to build a mutation type and a subscription type.

© 2022 Dragan Vucinic