GraphQL is incrementally being used in API development and developers love it for many reasons.
To start with, it reduces the time and cost being invested in the development of a particular project, enabling rapid project development. There are dozens of libraries, which enables the developers with caching, real-time UI updates and more such advanced capacities while using GraphQL. Also, it is open-source and growing fast.
If you are into frontend development and have not started using GraphQL yet, you need to try it out for the reasons we’ve mentioned in the post. And if you are a beginner, just getting started with GraphQL – Well! This guide is written keeping you in mind. Go ahead and learn it all.
What is GraphQL?
Basically, GraphQL is a query and data manipulation language used for APIs. In 2012, Facebook developed GraphQL for their internal use & then released it as an open source in 2015.
GraphQL mainly supports reading the data, changing it and also provides a subscription to changes of data for real-time updates.
In short, GraphQL unites the client and the server for fetching and manipulating the data. It lets the client pick only those data that are needed from the server & not all.
The below are few main characteristics of GraphQL:
- GraphQL lets the client fetch the specific data that they need.
- It is easier to create a cluster of data from multiple sources using GraphQL.
- GraphQL uses a special type system for describing the data.
When GraphQL is best fit to use?
If there is a need to create a data-driven application of least moderate complexity, GraphQL is the best fit. Below are a few reasons when GraphQl is best to use:
- GraphQL APIs have a strongly typed schema. It lets the client define various operations such as querying, mutating and subscribing to the data that are supported by the API. It also includes providing arguments as input and returns possible responses.
- It is a Client-driven API, which lets client requests exactly what it needs. Hence it makes it easy for the client to dictate the shape of response objects that the API returns. There’s no need for the client to have deep knowledge of different databases.
- Another important factor is that it abolishes the Overfetching & Underfetching of data. The GraphQL server provides a single endpoint for handling all the data requests, and it gives the power to modify those data requests at any time.
- The “No More – No Less” approach to the querying is wonderful for any application where data needs to be fetched or modified in a timely manner.
- GraphiQL tool is another major advantage of using GraphQL. This tool allows developers to easily write the query in the browser with the benefit of autocompletion. Also, it views the results in the side panel, and navigate through the schema by using automatically generated documentation.
- It Lessens Network Round-trip, the request and response are directly related.
How can we use GraphQL?
GraphQL can be used in combination with numerous languages. The list of such languages includes JavaScript, PHP, C#, JAVA, Python, etc. The below code will show us how to use GraphQL along with javascript and NodeJS.
1. Pre-requisites:
- You need to install NodeJS from https://nodejs.org/en/
- Create a Folder. Name it ‘graphql-demo’ or whatever you prefer. Now, you move to where your project folder is placed and then run npm init for the creation of the project.
2. Install prerequisites:
- Install all the required dependencies to get started. Use the following command to do so –
npm install express express-graphql graphql
3. Code:
- Now, create a new file and name it server.js. Put it within the same project and insert this code in the file you’ve created:
const express = require(‘express’);
const port = 5000;
const app = express();
app.get(‘/hello’, (req,res) => {
res.send(“hello”);
}
);
app.listen(port);
console.log(`Server Running at localhost:${port}`);
The code, we’ve posted above, has single http get endpoint, namely /hello. It is created using express.
4 Enabling GraphQL:
- GraphQL will provide a single endpoint that is /graphql. This end-point will handle all the data requests.
- Again, open the file server.js which you’d created in the previous step and add the following code to it –
//get all the libraries needed
const express = require(‘express’);
const graphqlHTTP = require(‘express-graphql’);
const {GraphQLSchema} = require(‘graphql’);
const {queryType} = require(‘./query.js’);
//setting up the port number and express app
const port = 5000;
const app = express();
// Define the Schema
const schema = new GraphQLSchema({ query: queryType });
//Setup the nodejs GraphQL server
app.use(‘/graphql’, graphqlHTTP({
schema: schema,
graphiql: true,
}));
app.listen(port);
console.log(`GraphQL Server Running at localhost:${port}`);
5. GraphiQL:
- GraphiQL is useful during testing and development but should be disabled in production by default. It’s set to true to test our query.
6. Schema:
- Although there is only a single external endpoint named /graphql, you may add many such endpoints for performing various operations. You can specify these endpoints in the schema.
7. Specifying the endpoints in schema:
- To define the scheme, you can use the following code:
const schema = new GraphQLSchema({ query: queryType });
- There are also other things in schema such as the query and mutation types.
8. Query in the schema:
- In the schema, there is a queryType set for the query. Here we will create a custom js file named as query.js. After that, we will import this queryType from the file query.js by using the following command:
const {queryType} = require(‘./query.js’);
- The query is where we specify the read-only endpoints in a schema.
- Now, create a JS file and call it as query.js. Copy the following code and paste it into query.js.
const { GraphQLObjectType,
GraphQLString
} = require(‘graphql’);
//Define the Query
const queryType = new GraphQLObjectType({
name: ‘Query’,
fields: {
hello: {
type: GraphQLString,
resolve: function () {
return “Hello World”;
}
}
}
});
exports.queryType = queryType;
9. Running the Application:
- Run the application using the following command
node server.js
- Your first GraphQL endpoint is created. You can now run the application on your local server.
Final words
After reading the article, you must have understood why the application of GraphQL is gaining traction in the API world. The way it improves the workflow for the developers and the decline in project completion time on its utilization are the main reason for its adoption by the developers. Slowly, it is changing the way how APIs are developed and utilized.
Overall, it is good for people who like smooth and efficient API development technology. Go ahead and use it from your next project. Do not forget to tell us if it impresses you too.