The Building of GraphQL APIs Using Node

Dec 20, 2022
GraphQL NodeJS

GraphQL is the latest trend used in API development. Although RESTful APIs are still the preferred method to expose data from applications but they do have some limitations that GraphQL aims to solve.

GraphQL is the name of a query language that was developed by Facebook which was transformed into an open-source project in the year 2015. T It offers an intuitive and flexible syntax for explaining as well as accessing information through an API.

What is GraphQL?

According to the official information: "GraphQL is a API query language and a runtime for fulfilling the queries using your existing information. GraphQL provides a complete and easy-to-read explanation of the information that you provide through your API. It allows clients to get exactly what they need and not more. This helps to make it simpler to develop APIs with time and also provides developers with powerful tools."

To create a GraphQL service, start by defining schema types and developing fields based on those types. Then, you create the function resolver which will be run on every field and type whenever data is requested by the client side.

GraphQL Terminology

GraphQL type system can be used to define what data is able to be requested and what information you can manipulate. This is at the heart of GraphQL. Let's discuss different ways we could describe and modify the data within GraphQ.

Types

GraphQL objects are models that contain fields with a strong type. It is recommended to have a 1-to-1 mapping between your models and GraphQL types. Here is an example of GraphQL Type:

type User Type User's ID! "! "!" is the first name that must be used: Stringlastname Email: String: String
 
 username: String
 
 todos: [Todo] # Todo is a different GraphQL type
 
 

Queries

GraphQL Query defines all the queries that clients could run through the GraphQL API. The client should create the root querythat includes all of the current queries by protocol.

Below, we will define and map the queries to the RESTful API that corresponds to them:

Type RootQuery user(id ID): User # Corresponds to GET /api/users/:idUsers: User # Corresponds to GET API/users
todostodo(id: ID! ): Todo # Corresponds to GET /api/todos/:id
 
 todos: [Todo] # Corresponds to GET /api/todos
 
 

Mutations

If GraphQL is a GET request, mutations are POST, the PUT, PATCH and DELETE requests that manipulate GraphQL API.

We will put all the mutations in a single RootMutation to show:

type RootMutation *

You may have noticed the usage of the -input types to define the transformations for example user input, TodoInput. It is always best practice to create input types when creating or changing your resource.

You are able to define Input kinds like those below:

input UserInput firstname String! lastname: String
 
 email: String! username: String!
 
 

Resolvers

Create a brand new resolvers.js file and include the following code in it:


 
 import sequelize from '../models';
 
 export default function resolvers () 
 
 const models = sequelize.models;
 
 return 
 
 // Resolvers for Queries
 
 RootQuery: 
 
 user (root,  id , context) 
 
 return models.User.findById(id, context);
 
 ,
 
 users (root, args, context) 
 
 return models.User.findAll(, context);
 
 
 
 ,
 
 User: 
 
 todos (user) 
 
 return user.getTodos();
 
 
 
 ,
 
 
 
 // Resolvers for Mutations
 
 RootMutation: 
 
 createUser (root,  input , context) 
 
 return models.User.create(input, context); 
 
 ,
 
 updateUser (root,  id, input , context) 
 
 return models.User.update(input,  ...context, where:  id  );
 
 ,
 
 removeUser (root,  id , context) 
 
 return models.User.destroy(input,  ...context, where:  id  );
 
 ,
 
 // ... Resolvers for Todos go here
 
 
 
 ;
 
 }
 
 

Schema

GraphQL schema defines what GraphQL exposes to the world. Thus, the kinds, queries, and mutations will be included inside the schema that will be made available to the public.

Below are the steps to reveal kinds, queries and modifications to the public:


 
 schema 
 
 query: RootQuery
 
 mutation: RootMutation
 
 
 
 

In the above script we added the RootQuery as well as the RootMutation which we developed earlier in order in order to make them available to the world.

How does GraphQL Function with Nodejs and Expressjs

GraphQL offers an implementation of the majority of programming languages and Node.js is not exempted. The official GraphQL site you will find a section that addresses JavaScript support as well as you can find other versions of GraphQL that make writing and coding in GraphQL easy.

GraphQL Apollo provides an implementation for Node.js as well as Express.js and allows users to get started with GraphQL.

You will learn how to build and create your first GraphQL application with Nodes.js and Express.js backend framework using GraphQL Apollo in the next section.

Setting up GraphQL By using Express.js

Making an GraphQL API server with Express.js is easy for beginners to start. In this section we'll explore the steps to create an GraphQL server.

Create a New Project With Express

Set up a folder in your project and install Express.js with this command:


 
 cd  && npm init -y
 
 npm install express
 
 

This command will create the fresh package.json file and installs the Express.js library in your application.

Do you want to know the ways we have increased visitors by 1000 per cent?

Join over 20,000 others to receive our newsletter each week that contains insider WordPress advice!

Next, we will organize our project in the manner illustrated in the picture below. The project will have various modules that will be used to implement the functions of the application, such as users, todos, etc.

Initialize GraphQL

Start with setting up our GraphQL Express.js dependency dependencies. The following command is needed to install:


 
 npm install apollo-server-express graphql @graphql-tools/schema --save
 
 

The process of creating Schemas and Types

We are now going to build the index.jsfile inside the module folder. Then, we will include the code snippet below:

const  gql  = require('apollo-server-express');
 
 const users = require('./users');
 
 const todos = require('./todos');
 
 const  GraphQLScalarType  = require('graphql');
 
 const  makeExecutableSchema  = require('@graphql-tools/schema');
 
 const typeDefs = gql`
 
 scalar Time
 
 type Query 
 
 getVersion: String!
 
  type Mutation 
 
 version: String!
 
  `;
 
 const timeScalar = new GraphQLScalarType(
 
 name: 'Time',
 
 description: 'Time custom scalar type',
 
 serialize: (value) => value,
 
 );
 
 const resolvers = 
 
 Time: timeScalar,
 
 Query: 
 
 getVersion: () => `v1`,
 
 ,
 
 ;
 
 const schema = makeExecutableSchema(
 
 typeDefs: [typeDefs, users.typeDefs, todos.typeDefs],
 
 resolvers: [resolvers, users.resolvers, todos.resolvers],
 
 );
 
 module.exports = schema;

Code Walkthrough

Let's go through this code-snippet, and break it down

Step 1

Then, we downloaded the libraries required and set up the default types of query and mutation. The query and mutation determine an instance of GraphQL API at present. However, we will extend the query and the mutation to incorporate additional schemas over time.

Step 2.

After that, we made a new type of scalar for time and our first resolver for the query and mutation made above. Additionally, we generated a schema using this createExecutableEchema function.

The schema generated includes the schemas that we have imported, and will add more schemas as we develop and then import them.

This code example illustrates that we have imported various schemas to the makeExecutableEchema method. This method helps in creating an application that is structured to handle complexity. Next, we are going build our own schemas, which will be based on the Todo as well as User schemas we brought in.

Creating Todo Schema

The Todo schema illustrates the basic operation that the users of the app can execute. Here is the schema that executes the Todo operations CRUD.

const  gql  = require('apollo-server-express');
 
 const createTodo = require('./mutations/create-todo');
 
 const updateTodo = require('./mutations/update-todo');
 
 const removeTodo = require('./mutations/delete-todo');
 
 const todo = require('./queries/todo');
 
 const todos = require('./queries/todos');
 
 const typeDefs = gql`
 
 type Todo 
 
 id: ID! title: String
 
 description: String
 
 user: User
 
 
 
 input CreateTodoInput 
 
 title: String! description: String
 
 isCompleted: Boolean
 
 
input UpdateTodoInput 
 
 title: String
 
 description: String
 
 isCompleted: Boolean
 
 
 
*do;
// Implement resolvers for the schema fieldsconst resolvers = 
Resolvers to resolve queriesQuery such as todo, todos and// Resolvers for Mutations
Mutation: 
 
 createTodo,
 
 updateTodo,
 
 removeTodo,
 
 ,
;
Module.exports = typeDefs;module.exports =  typeDefs, resolvers ;

     Code Walkthrough    

Let's work through this code-snippet, and break it down:

Step 1.

First, we created an schema to organize our Todo by using GraphQL types, input as well as expand. The extension keyword allows you to create additional queries or mutations to the existing base query as well as the mutation that the above-mentioned mutation.

Step 2:

We then created resolver, which can be used to retrieve the correct details when a certain request or change is referred to as.

With the resolver function installed, we are able to develop individual ways to handle management of the database and the business logic like in create-todo.js example.

Create an create-user.js file in the ./mutations folder and incorporate the business logic create a brand new Todo within your database.


 
 const models = require('../../../models');
 
 module.exports = async (root,  input , context) => 
 
 return models.todos.push( ...input );
 
 ;
 
 

The above code is a simplified way of creating a new Todo in our database using the ORM Sequelize. It is possible to learn the details about Sequelize as well as how you can set it up using Node.js.

You can follow this same procedure to build multiple schemas based on the needs of your application or you can copy the entire project to GitHub.

Next, we are going create a server with Express.js and launch the new Todo application using GraphQL as well as Node.js

Set up and running the Server  

Lastly, we will set up our server using the apollo-server-express library we install earlier and configure it.

The apollo-server-express is a simple wrapper of Apollo Server for Express.js, It's recommended because it has been developed to fit in Express.js development.

Using the examples we discussed above, let's configure the Express.js server to work with the newly installed apollo-server-express.

Create server.js file in the root directory. Copy server.js file in the root directory. Paste this code into it:


 
 const express = require('express');
 
 const  ApolloServer  = require('apollo-server-express');
 
 const schema = require('./modules');
 
 const app = express();
 
 async function startServer() 
 
 const server = new ApolloServer( schema );
 
 await server.start();
 
 server.applyMiddleware( app );
 
 
 
 startServer();
 
 app.listen( port: 3000 , () =>
 
 console.log(`Server ready at http://localhost:3000`)
 
 );
 
 

The code you have seen above shows that you have successfully created your very first CRUD GraphQL server for Todos as well as Users. You can start your development server and access the playground using http://localhost:3000/graphql. If everything goes as planned, you should be presented with the screen below:

Summary

GraphQL is modern technology that is supported by Facebook that makes easier the task of creating large-scale APIs with RESTful architectural patterns.

This article has explained GraphQL and demonstrated how to create your very first GraphQL API with Express.js.

Let us know the things you have built by using GraphQL.

  • Simple setup and management on My dashboard. My dashboard
  • Support is available 24/7.
  • The best Google Cloud Platform hardware and network, powered by Kubernetes for maximum scalability
  • A high-end Cloudflare integration that improves speed as well as security
  • Global audience reach with more than 35 data centers as well as more than 275 PoPs in the world.