Getting Started With GraphQL & Why it is Required (Part 1)
Tags: graphql, javascript, webdev, beginners
Published: 2023-12-19 18:29:40

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 was open-sourced in the year 2015, it was developed to address some of the limitations and challenges that were associated with REST APIs, the challenges include

1. **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).

2. **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.

3. **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.

4. **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**.


![Request for particular user with id](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5foig2w8gfk1mn9zodph.jpg)


![Request for particular user Post](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m7mg9lm9xva2i74mj9gw.jpg)


![Request for particular user Followers](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3lzql5qff3gc2jg0p91b.jpg)


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.



![query using Graphql](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fxpwv5cxdkkzjjfidvuq.jpg)

---

Now, let us head toward creating our first GraphQl server using Apollo Server

## Creating Our First Server :

1. Our First step includes creation of a new Project , you have to ensure that your system has node.js installed

```
 mkdir my-first-graphql-server
 cd my-first-graphql-server
```

2. Now, let's Initialize our project using npm(node package manager) and set our type in the package.json file as "module", so that we can use the import statement, the below command will create a package.json file inside your project directory

```
npm init --yes && npm pkg set type="module"
```

3. 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
```

4. Now, here comes the most interesting part of creating the server in graphql, we have to define the **Graphql Schema** which typically represents the structure of our data present and the shape of the query, it is typically denoted with **typeDefs**, now create an index.js file inside our project directory and import the certain things and create the **typeDefs** as mentions which refers 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]
   }
 `;

```

5. Again inside our **index.js** or in other files you can mention your data and export the data if required, again for a simple purpose we are just taking **books** which represent the array of objects with a particular book **title** and **author**.

```
 //index.js 
 const books = [
   {
     title: 'The Awakening',
     author: 'Kate Chopin',
   },
   {
     title: 'City of Glass',
     author: 'Paul Auster',
   },
 ];

```

6. 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 the Apollo server how to fetch the particular data when a certain query is made and what the given query returns, below code snippets will return 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,
   },
 };

```

7. Now we need to create our instance of ApolloServer, inside the 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}`);

```

8. Now for **running the server**, we have to make some changes in our script object present inside the **package.json** file, since 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 runs your index.js file
  },

```

```
//now open the terminal and write the start command this will
//start your Apollo server at port 4000 with the URL as http://localhost:4000/
npm run server

```

Ahh we now have created our first Graphql server using Apollo Server, opened our localhost and make the query in the playground, provided by ApolloServer playground as shown in the the image.



![Apollo Studio](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pezd6yzkyvtiv1tmlkg7.jpg)

---


## 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 its 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.

---


{% embed https://www.apollographql.com/docs/apollo-server/ %}