Table of contents
In this article, we will explore the most loved query language which resolves the most important problem statement in modern web app development
Although there are quite a lot of techniques to work with Graphql, for the sake of simplicity we will be going to use Apollo Server as your server for the Graphql
But Before moving forward let us understand, Why there is a need for Graphql
Why Graphql ?
Graphql was developed by Facebook in the year 2012, and it is open-sourced in the year 2015, it was developed to address some of the limitations and challenges that was associated with REST APIs, the challenges includes
Under-fetching: In REST, endpoints are fixed, and the server determines the structure of the response. This can lead to under-fetching (receiving less data than needed).
Over-fetching: The REST also have an issue called Over-fetching(receiving more data than needed)., where generally we get more data than is required which can affect the efficiency.
Single Request for Multiple Resources: With GraphQL, clients can request multiple resources in a single query, reducing the number of HTTP requests needed to retrieve data. This can result in faster and more efficient communication between clients and servers.
Flexible Schema and Strong Typing: GraphQL uses a flexible schema that allows clients to define the shape of the response they expect. It also enforces strong typing, providing clarity about the types of data that can be queried and reducing the chance of runtime errors.
let us now clearly, understand how Graphql reduces under-fetching and over- fetching, by taking the example of the user, in REST we have to create a different endpoint for getting with id /user/<id>, similarly for getting a post of a particular user /user/<id>/posts and for followers we have /user/<id>/followers.
With REST, you have to make three requests to different endpoints to fetch the required data. You’re also overfetching since the endpoints return additional information that’s not needed.
In GraphQL on the other hand, you’d simply send a single query to the GraphQL server that includes the concrete data requirements. The server then responds with a JSON object where these requirements are fulfilled.
Now, let us head toward creating our first GraphQl server using Apollo Server
Creating Our First Server :
Our First step include creation of new Project , you have to ensure that your system has nodejs installed
mkdir my-first-graphql-server cd my-first-graphql-server
Now, let Initialize our project using npm(node package manager) and set our type in package.json file as "module",so that we can use import statment,
the below command will create a package.json file inside your project directory
npm init --yes && npm pkg set type="module"
Install Dependencies, to use the graphql and apollo server , we have to install the dependencies and also nodemon for running our server.
npm install @apollo/server graphql nodemon
Now, here comes the most interesting part in creating the server in graphql, we have to define the Graphql Schema which typical represent the structure of our data present and shape of the query, it is typically denoted with typeDefs , now create a index.js file inside our project directory and import the certain things and create the typeDefs as mentions which referes to ours schema,
//index.js import { ApolloServer } from '@apollo/server'; import { startStandaloneServer } from '@apollo/server/standalone'; // A schema is a collection of type definitions (hence "typeDefs") // that together define the "shape" of queries that are executed against // your data. //Adding #graphql to the beginning of a template literal provides //GraphQL syntax highlighting in supporting IDEs. const typeDefs = `#graphql type Book { title: String author: String } type Query { books: [Book] } `;
Again inside our index.js or in other file you can mention your data export the data if required, again for simple purpose we are just taking an books which represent the array of object with particular book title and author.
//index.js const books = [ { title: 'The Awakening', author: 'Kate Chopin', }, { title: 'City of Glass', author: 'Paul Auster', }, ];
Define the resolvers inside index.js, now that we have created our data set we have to create our resolvers which are basically a function that tells apollo server how to fetch the particular data when the certain query is made and what should the given query returns, below code snippets will returns all the books from the array , when the books query is made.
//index.js // Resolvers define how to fetch the types defined in your schema. // This resolver retrieves books from the "books" array above. const resolvers = { Query: { books: () => books, }, };
Now we to create our instance of ApolloServer, inside index.js file which will take **typeDefs and resolvers,**We've defined our schema, data set, and resolver. Now we need to provide this information to Apollo Server when we initialize it.
//index.js // The ApolloServer constructor requires two parameters: your schema // definition and your set of resolvers. const server = new ApolloServer({ typeDefs, resolvers, }); // Passing an ApolloServer instance to the `startStandaloneServer` function: // 1. creates an Express app // 2. installs your ApolloServer instance as middleware // 3. prepares your app to handle incoming requests const { url } = await startStandaloneServer(server, { listen: { port: 4000 }, }); console.log(`🚀 Server ready at: ${url}`);
Now for running the server, we have to make some changes in our script object present inside the package.json file ,since now we have already installed nodemon, it is time we have to utilise it while running the server,add the below code snippet to our package.json files scripts object.
//package.json
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"server":"nodemon index.js" //this run your index.js file
},
//now open the terminal and write the start command this will
//start your apolloServer at port 4000 with url as http://localhost:4000/
npm run server
Ahh we now have created our first Graphql server using Apollo Server, open our localhost and make the query in the playground, provided by ApolloServer playground as shown in the the image.
Conclusion :
So, from this Article, we have learned how GraphQl is better than REST API and the benefits it provides over a conventional REST framework and we have also seen how it resolves the challenges of Under-fetching and Over-fetching by utilising the one-only query for different resources.
Further, we have created our first GraphQl server using Apollo server and utilised it querying capabilities, in the next article we will further explore some of the different techniques present in graphql for manipulating the data known as Mutation
I have learned a lot about this topic from the internet and also advise you the same for more exploring and deep diving, do reply and comment on this article for better sharing and good content creation.