GraphQL | A query language for your API.

Reading Time: 4 minutes
GraphQL

In this blog, we are going to learn about how we can use GraphQL to make APIs fast, flexible, and developer-friendly.

What is GraphQL

It is a query language for APIs and a runtime for fulfilling those queries with your existing data. It provides a complete and understandable description of the data in your API, 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.

Why GraphQL

It is on the rise. Companies like Facebook, Netflix, Shopify or PayPal are using the data language and API technology to drive their products. Here are top 5 reasons to use it and they are as follows: One Data Graph for all, No Over-Fetching or Under-Fetching, Better Developer experience, Higher Quality of Your System, Build for Change.

Considerations before Adopting GraphQL

It is an excellent tool to build scalable and flexible APIs, but it is not a panacea and is certainly not for everyone.

Learning Curve

Whereas REST is a simple and familiar approach to building APIs, GraphQL is a different beast altogether.

Infrastructure and Tooling

Deploying GraphQL, especially at scale, can require significant investment in infrastructure and tooling.

Performance and Security

You also have to be extra careful that the additional flexibility afforded by it does not result in queries that maliciously or accidentally degrade or take down your system.

Get Many Resources in a Single Request

GraphQL queries access not just the properties of one resource but also smoothly follow references between them. While typical REST APIs require loading from multiple URLs, GraphQL APIs get all the data your app needs in a single request. Apps using it can be quick even on slow mobile network connections.

Evolve your API without Versions

Add new fields and types to your API without impacting existing queries. By using a single evolving version, this APIs give apps continuous access to new features and encourage cleaner, more maintainable server code.

Who’s using GraphQL

1631 companies reportedly uses it in their tech stacks, including Facebook, Shopify, and Instagram, etc.

Below is an example of how to use GraphQL:

Let’s create a simple Hello World example in GraphQL. Here, we shall use Node.js, Express, Apollo server, and GraphiQL.

Create Example:

First, create a folder named “first-example” and navigate to the folder by using node.js command prompt.

Now, add package.json file in the project folder “first-example” and give a name to the package:

{  
   "name":"first-example",  
   "private":true  
}  

Step 1- Install Express and its Dependencies

Now, install express your current directory along with two additional dependencies i.e. body-parser and cors:

npm install express body-parser cors  

Now it’s the time to create a server. Create a file named server.js and add this code to it:

const bodyParser = require('body-parser')  
   const cors = require('cors')  
   const express = require('express')  
   const port = process.env.PORT|| 4000  
   const app = express()  
     
   //register middleware  
   app.use(bodyParser.json() , cors())  
   app.listen(port, () =>  console.log(`server is started and running at ${port}`)  

Step 2- Install GraphQL and Apollo Server

After setting up Express, it’s turn to install following required dependencies.

  • graphql
  • graphql-tools
  • apollo-server-express

Use the following command to install the required dependencies:

npm install graphql graphql-tools apollo-server-express@<stable version>

Step 3- Define the Schema

The schema is used to define the kind of objects which can be fetched from service, and the fields they contain. GraphQL Schema Definition Language is used to define GraphQL schema. Add this code to server.js:

// Adding Type Definitions  
const typeDefinition = `  
   type Query  {  
      hello: String  
   }  

Step 4- Create a Resolver

The resolver is used to process the request to the hello attribute of the query. The structure of the resolver function and the schema function must be the same. Add this code to server.js:

// Adding resolver  
const  resolverObject = {  
   Query : {  
      hello: () => 'Hello World! Welcome to GraphQL...'  
   }  
} 

Use a pre-defined function makeExecutableSchema() to bind the schema and resolver. This function is pre-defined in the tools module. Now add the below code in the server.js file to bind the schema and resolver:

const {makeExecutableSchema} = require('graphql-tools')  
const schema = makeExecutableSchema({typeDefs:typeDefinition, resolvers:resolverObject})  

Step 5- Define Routes to Retrieve Data

Add this code to server.js:

const {graphqlExpress, graphiqlExpress} = require('apollo-server-express')  
   //create routes for graphql and graphiql  
   app.use('/graphql',graphqlExpress({schema}))     
   app.use('/graphiql',graphiqlExpress({endpointURL:'/graphql'}))  

Step 6- Start the Server

Use the following command to execute the server:

node server.js  

Step 7- Open the browser to test the API

Open the browser at http://localhost:4000/graphiql and use the query:

{  
   hello  
}  

You will see the output:

{  
  "data": {  
    "hello": "Hello World! Welcome to GraphQL..."  
  }  
}  

Conclusion

There is no doubt that REST gets the job done, but if you’re at a point where you need a better way to build APIs and serve diverse clients, then you should probably give GraphQL a try. It allows you to build evolvable and queryable APIs, hide the complexity of internal systems used to retrieve various pieces of data, and leverage a type system that results in automatic and up-to-date API documentation.

References

https://graphql.org/

https://codersociety.com/blog/articles/graphql-reasons#the-rise-of-graphql

Scala Future