Blogs
Code

How To Quickly Integrate GraphQL Using Apollo?

In this blog, we will learn about GraphQL, an excellent alternative to REST along with how to integrate it with React using the Apollo Client.
Cover image showing GraphQL

There were only static files in the early days of web development but since then, a lot has changed. Today's online applications are powered by a variety of technologies, including databases, web sockets, real-time data, authentication, and many more.

It is a common practice these days to decouple the front end from the backend & have separate teams working on each. This makes it essential to create an interface so they can communicate with each other smoothly.

Application Programming Interface(API) is an industry-standard way of connecting the two.

Considering how APIs work, we can say that the client sends a request, the server processes the request, and then sends the response.

For example, let's ask the server for a variety of books. You can imagine the client as a web browser, such as Google Chrome, and the server as the data repository that sends back a lot of data present in it(or in external databases).

We can receive something like this:

Image showing client and server interacting

However, the client's ability to act depends on the data it can receive from the API & besides that, it may not need all the data that is sent from the API server. 

In an ideal scenario, the front end should be able to communicate with the backend and get exactly the data it needs. That's where GraphQL comes in.

GraphQL: A Modern Way to Build APIs

GraphQL is essentially a query language. It provides freedom by enabling you to perform a number of things, such as setting up your API, running queries, modifying the data, and more.

In short, it gives the client(front-end) the exact properties it needs.

Let's take an example to understand GraphQL. We’ll fetch data using REST and GraphQL to highlight their differences.

Assume we make the following request: 

The response will be as follows:

Here, we have a considerable amount of data with a lot of properties in the “/character” API endpoint, but what if we just need a few of them? In this situation, GraphQL can be useful.

Let's implement a GraphQL example now.

Query/ Input: 

Response/ Output: 

You can see that we requested some specific properties like “count”, “id”, and “name”, which are now part of the output.

In other words, we define the specific parameters inside the query object and then get the response depending on those. This is how GraphQL differs from a standard REST API.

Rise of GraphQL in Recent Years

GraphQL being a query language enables flexible communication between clients and servers by defining queries and even mutating the data.

It was created by Facebook in 2012 for internal usage. Later, It became accessible to the public, in 2015. And that’s where it started to compete with RESTful APIs.

As time went on, it was used all around the world. People even predicted that GraphQL will replace REST.

Even the State of JavaScript study found that from 2017 to 2020, GraphQL was one of the top technologies developers were interested in.

Image of statistics showing preferred developer tools

As you can see in the image below, only 6% of developers were adopting GraphQL technology in 2016; by 2020, that number had risen to 47%.

So it is apparent from the surveys that GraphQL is here to stay and will be widely used.

Fetching GraphQL Data from React using Apollo Client

Image of Apollo sever

We are all familiar that a client and server are necessary when developing a website. 

In this blog, we will use React on the frontend side and a GraphQL server on the server side.

We will use this particular GraphQL server to fetch the data in React. You can read more about it here

Now let's create a react app.

1. Create a React App

You need to install two npm packages i.e. GraphQL and Apollo Client.

To install GraphQL and Apollo Client, execute the following command:

React doesn’t have support for GraphQL by default, hence it cannot connect to a GraphQL server and run queries against it. There’s where Apollo Client comes in handy. Apollo Client is a leading state management library that combines React with GraphQL, two incredibly helpful tools for creating websites and apps.

After installing the packages, you would have a GraphQL server, a React app, and the necessary npm dependencies installed. Now you can use the Apollo Client to connect the React app to GraphQL.

Before proceeding further, delete the file's “logo.svg”, “setupTests.js”, “reportWebVitals.js”, and “App.test.js” files from the “src” folder; we don't need any of these. 

We can start with the index.js file.

2. Modifying index.js

Here, we created a client and passed a few arguments.

For the uri property, we have our GraphQL server link and our GraphQL query results are saved by Apollo Client in a local InMemoryCache. As a result, Apollo Client can respond to requests for already-cached data instantaneously, without performing the same requests again.

Lastly, we use ApolloProvider to wrap the app component.

Now let's query & render data.

3. Rendering a list of data inside App.js

So far, we have connected our app with GraphQL and now it’s time to render a list of data.

For that, inside the App.js file, we have to import useQuery and gql from Apollo Client.

Now it’s time to query the specific properties that we need inside our app. 

Here, we have used gql template literal to query the id and name property present in the character object(in the GraphQL server).

Now let’s render the list of data inside the App component.

Here, we used a useQuery hook before destructuring and rendering the data.

Now it’s time to run the react app:

npm start

The result appears as follows:

You may experiment more with GraphQL by changing the queries.

It is also possible to combine GraphQL with other well-known frameworks like Vue and Angular.  Even Apollo Client and GraphQL are compatible with React Native.

Should Every API Use GraphQL?

GraphQL has emerged as an alternative to REST since its launch. The ability of GraphQL to request specific data via queries and have a single endpoint makes us wonder whether every API should utilize GraphQL. This has provided developers with more options & sparked debates on which one is better.

The short answer is, it depends upon the data and how it is structured.

GraphQL may be used to retrieve specific data while avoiding numerous requests and saving bandwidth and time. In contrast, there may be instances when you need to make multiple requests, manage file uploads, and enable HTTP status codes, in that case, REST might be handy.

As a result, it is dependent on how you want to obtain the data and which features you want to employ. It also comes down to whether the particular framework or software you are using even allows GraphQL or not.

You would need to build the app with components that can accept props(data from these APIs) and render them. For this, you can use the Locofy.ai plugin to rapidly generate frontend code that accepts props to test & see these GraphQL APIs in action in pixel-perfect UIs.

Create a Full Stack App using Locofy and GraphQL

The Locofy.ai plugin for Figma & Adobe XD enables you to take your designs to high-quality, production-ready frontend code in a matter of few hours, which would have otherwise taken you days. You can make the code highly extendible inside the Locofy Builder where you can break down your designs into components as well as set props for each of these components & finally export the code.

You can pick a framework of your choice from the likes of React, Next.js, Gatsby, React Native, or even HTML-CSS.

This will generate code that you can easily extend and pass data from your API. We covered how to do this by building a full stack app with GraphQL and React, with help of tools like Locofy.ai and Hasura at a developer event in San Francisco in September 2022, and documented it in our recent guide.

Locofy.ai enables you to ship 5-10x faster by providing you with a polished codebase that you can easily extend with these APIs.

Keep your loco mode on!
Stay updated on the latest Locofy announcements and product updates

© 2024, Locofy Pte Ltd. All Rights Reserved.