DEV Community

Cover image for How To Use GraphQL: A Beginner Walk-through
Emmanuel Uchenna
Emmanuel Uchenna

Posted on

How To Use GraphQL: A Beginner Walk-through

How To Use GraphQL: A Beginner Walk-through

Introduction

For software developers, it is a common practice to make several HTTP requests to retrieve server data for a single page. The consequence of making multiple HTTP requests may lead to several complications, including server and network overload, as well as complex error handling.

What if I told you there's another way? A smarter way of doing this? Fasten your seatbelt as you ride along with me to discover more. 🚀

In this post, I present to you GraphQL - a query language for APIs that has quickly gained popularity. Since its release to the open-source community by Facebook in 2015, GraphQL has significantly grown among the developer community.

In 2019 alone, according to data by StateOfJS, about ten thousand developers indicated interest to use GraphQL in addition to the seven thousand active users of GraphQL.

GraphQL 2019 StateOfJS

Image source: StateOfJS 2019

In this article, you will learn what GraphQL is, I will discuss how to use GraphQL and its advantages. I will also take a deep dive into queries, mutations, fragments, directives, and best practices to help you use GraphQL effectively. Are you ready to save time and write more efficient code? Let's get started!

What is GraphQL?

This may not be your first time coming across the term "GraphQL", however, if it is, you have nothing to worry about as you would be taking a deep dive into GraphQL in this post.

GraphQL stands for Graph Query Language. It is a query language for APIs. It allows clients to request specific data from an API, rather than receiving all of the data that is available. This makes GraphQL more efficient and flexible than traditional REST APIs.

A GraphQL query is a string that is sent to a server to be interpreted and fulfilled, which then returns JSON to the client. - Engineering at Meta

GraphQL

Why use GraphQL?

With GraphQL, you can fetch all the necessary data with a single request. No more multiple HTTP requests!

There are several reasons why you might want to use GraphQL:

  • Efficiency: GraphQL only returns the data that you request, which can improve performance.
  • Flexibility: GraphQL allows you to request data in any order or format, which gives you more control over your application.
  • Scalability: GraphQL can be used to scale your application as your needs grow.
  • Avoid unnecessary issues peculiar to REST API: The REST API architecture is known for the following issues such as:
    • Over-fetching: When the server sends unneeded data to the client, it is referred to as over-fetching within an API. The API is established prior, and the client only needs to comply with the API documentation. However, this approach has a downside in that it results in bandwidth being squandered.
    • Under-fetching: Insufficient data being sent to an endpoint during an API call, which requires another call, is referred to as under-fetching. The response time of your application or website is prolonged by the addition of each supplementary API call, leading to an increase in precious processing time for every interaction.
    • Dependent requests: Dependency constraints are usually present in REST APIs that limit the combinations of two or more parameters to form valid API calls.
    • Multiple round trips: Multiple round trips in REST API refer to the need for a client to make multiple requests to the server to retrieve all the required data, instead of retrieving everything in a single request/response cycle. It's a process where the client requests data from the server in multiple trips, frequently requiring several iterations to complete the process.

GraphQL vs REST

GraphQL is a newer technology than REST, but it is quickly gaining popularity. Here are some of the key differences between GraphQL and REST:

  • GraphQL is a query language, while REST is an architectural style.
  • GraphQL allows you to request specific data, while REST returns all of the data that is available.
  • GraphQL is more flexible than REST, but it can be more complex to implement.

Graph

Image source: Engineering at Meta

For an even more in-depth comparison between GraphQL and REST architecture, please check out this post - GraphQL vs REST: Differences, Similarities, and Why to Use Them.

Getting Started with GraphQL

To get started with GraphQL, you will need to choose any of these methods of implementation:

  1. Using AWS AppSync: The Fully managed GraphQL Service
  2. Open-source GraphQL libraries
  3. Self-managed service in your web application

In this post, you will learn how to setup GraphQL locally:

To get started, install the following:

Once you have installed a GraphQL server and client, you can start writing GraphQL queries.

Getting Started as a React Developer with GraphQL

In this article, I will quickly walk you through how to get started with GraphQL as a front-end developer. To quickly see what GraphQL looks like, take a look at the GraphQL playground.

The GraphQL PlayGround

GraphQL playground is an interactive web-based interface that allows developers to explore and test GraphQL APIs. It provides a user-friendly environment for executing queries, viewing results, and testing mutations. It also offers features such as auto-completion, error highlighting, and documentation to make it easier for developers to work with GraphQL APIs. The GraphQL Playground is commonly used during the development process to test and debug APIs before they are deployed to production.

GraphQL Playground

Apollo Studio

Apollo Studio is a web-based service for monitoring and managing your GraphQL APIs. With Apollo Studio, you can track your API performance, set up access controls, and version your schemas. It also comes with a built-in GraphQL Playground, so you can test your queries and mutations right from the browser. In this article, we'll take a look at how to install and get started with Apollo Studio.

Use Apollo Client to Fetch Data in React

Apollo Client is a JavaScript library that is used for managing the state of data in web applications. It is an open-source GraphQL client that allows you to easily manage data in your applications by providing a simple and intuitive API. Apollo Client can be used with any JavaScript framework and is compatible with most modern browsers.

It is used for data handling, fetching, and caching in web applications. It provides a unified API for fetching data from multiple sources, including REST APIs, GraphQL APIs, and local data sources. With Apollo Client, you can easily manage the state of data in your application, including caching, pagination, and real-time updates.

To get started with Apollo Client, you need to install both the main Apollo Client dependency, as well as GraphQL:

npm install @apollo/client graphql
Enter fullscreen mode Exit fullscreen mode

The primary idea of Apollo Client is to leverage its functionality across the entire application, accomplished by using a distinct ApolloProvider component, which passes the created Apollo client down the complete component hierarchy.

It is important to define the uri value, which represents a GraphQL endpoint, and to specify a cache when creating the Apollo Client. The in-memory cache of Apollo Client is utilized to locally store and regulate queries along with their pertinent data.


// index.js

import React from "react";
import ReactDOM from "react-dom";
import { ApolloProvider, ApolloClient, InMemoryCache } from "@apollo/client";

import App from "./App";

const client = new ApolloClient({
  uri: "https://spacex-production.up.railway.app/",
  cache: new InMemoryCache()
});

const rootElement = document.getElementById("root");
ReactDOM.render(
  <ApolloProvider client={client}>
    <App />
  </ApolloProvider>,
  rootElement
);
Enter fullscreen mode Exit fullscreen mode

In the snippet above, I specified the uri as https://spacex-production.up.railway.app/ which provides data about SpaceX and its past missions.

Once you've set up the Provider and client within your App component, you can use all of the different React hooks that Apollo Client gives you for all the different GraphQL operations. These include queries, mutations, and subscriptions. You can even use the created Apollo Client directly using a custom hook called useApolloClient.

Since you're just querying data here, you will use the useQuery hook.

You will include a GraphQL query as its first argument to write your query. You'll use the function gql, which does several things, such as giving you editor syntax highlighting and the auto-formatting functionality if you use the tool Prettier for your project.

Once you execute this query, you get back the values data, loading, and error:


// App.js

import React from "react";
import { useQuery, gql } from "@apollo/client";

const FILMS_QUERY = gql`
  {
    launchesPast(limit: 10) {
      id
      mission_name
    }
  }
`;

export default function App() {
  const { data, loading, error } = useQuery(FILMS_QUERY);

  if (loading) return "Loading...";
  if (error) return <pre>{error.message}</pre>

  return (
    <div>
      <h1>SpaceX Launches</h1>
      <ul>
        {data.launchesPast.map((launch) => (
          <li key={launch.id}> {launch.id}: {" "} {launch.mission_name}</li>
        ))}
      </ul>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

To ensure a smooth display of data and missions, it is important to manage the loading state beforehand. During the loading state, the query is fetched from the remote endpoint (the uri specified).

Any occurrence of errors should also be handled efficiently. For instance, errors can be simulated by creating a syntax error in the query, such as requesting a non-existent field. In such cases, returning and displaying a message from error.message can be quite convenient.

When you run the above app and navigate to localhost:3000, you should see a list of 10 recent Space launches and their ids, like so:

Screenshot of app

Other Resources to Accompany this Tutorial

This tutorial comes with an accompanying GitHub repository where the codes for the react-select-tutorial app that I built for this tutorial are hosted. I also included some additional YouTube video tutorials.

Other Methods of Fetching Data in React from a GraphQL API

Conclusion

GraphQL is a powerful and flexible query language that can be used to improve the performance, flexibility, and scalability of your APIs. If you are looking for a way to improve your APIs, GraphQL is a great option to consider.

Follow me on Twitter @eunit99 let's keep in touch 🚀

Further Readings

Top comments (0)