The API Series - Part 3: GraphQL and Sending Queries with fetch()
Tags: codenewbie, 100daysofcode, javascript, graphql
Published: 2021-05-06 12:57:56

## Introduction

In this tutorial you'll learn how to query data from a GraphQL API. In the process, you'll be exposed to some common tools used to work with GraphQL APIs, GraphQL syntax and structure, and you'll receive a VanillaJS GraphQL repository to study and get running on your local system.

If you missed the previous parts, you can find them here:
[Part 1 - An Intro to APIs](https://dev.to/vetswhocode/the-api-series-part-1-an-intro-to-apis-1bd)
[Part 2 - The REST API, fetch(), and AXIOS](https://dev.to/vetswhocode/the-api-series-part-2-the-rest-api-fetch-and-axios-lf)

## Prerequisites

Some familiarity with HTML, Git, and JavaScript. 

## What is GraphQL

In the same way that the RESTful APIs conform to a REST architectural style, GraphQL APIs follow a strict GraphQL architecture. GraphQL is a query language for APIs organized with this GraphQL architecture. But unlike RESTful APIs, GraphQL has a single URL endpoint, offering an advantage over working with REST APIs that require different URL endpoints for different data. Additionally, GraphQL APIs only returns the data you need, unlike REST APIs which often deliver all the data associated with an object. For example, if you want to fetch the user name, the REST API would return the User object along with all of its properties. This is known as overfetching and can slow down your applications. With GraphQL, as you'll see, you can return the user name only.

As a frontend developer, you'll be interacting with an API that is already built, but understanding how they're built is useful. The GraphQL schema architecture is defined by a series of schema based on type, like the below example from the [GraphQL Foundation](https://graphql.org/) website:

```javascript
type Query {
  hero: Character
}
 
type Character {
  name: String
  friends: [Character]
  homeWorld: Planet
  species: Species
}
 
type Planet {
  name: String
  climate: String
}
 
type Species {
  name: String
  lifespan: Int
  origin: Planet
}
```

In the above example, there are several types: Query, Character, Planet, and Species. Some types are built into the query language. Examples of these are the types Query and Mutation, which we'll dive into deeper later on. The custom types of Character, Planet, and Species are referred to as object types. Each type will have one or more properties, which are often referred to as fields. From the example above, the Query type has a field of hero, which returns an array of the Character object type. Within the API, fields are assigned a type, such as the built-in String, Int, Float, Boolean, or ID, or fields are assigned type objects, such as, in the example above, Character, Planet, or Species. Like the syntax of JavaScript, object types enclosed in brackets return an array of that object type.

## Queries and Mutations

Whereas the REST API has several methods, such as POST, GET, PATCH, PUT, and DELETE, GraphQL has only two methods: Query and Mutation.

Queries are like the REST API GET method. They return data stored by the API.

Mutations change data, and encompass the REST API POST, PUT, PATCH, and DELETE methods.

## Getting Started With GraphQL API Query

In order to avoid getting bogged down in setting up a development environment to get started, we're going to first learn about consuming a GraphQL API using the OneGraph's GraphiQL explorer located at [https://www.onegraph.com/graphiql](https://www.onegraph.com/graphiql) 
The home page will look like this:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/esqh2p4ikfm80j6awa6k.png)

OneGraph is a company that integrates all the most commonly used APIs in business into a single GraphQL API, so developers can query Twitter, Salesforce, Slack, and UPS in a single query. GraphiQL is not owned by OneGraph. It is a tool that you can use independently.
 
To learn more about GraphiQL, visit [https://github.com/graphql/graphiql](https://github.com/graphql/graphiql)

In the leftmost column, we see all the APIs that OneGraph has integrated into their offering. The center columns is where we will write our query. The rightmost column is where our query output will be displayed.

In the below example, we'll query the DEV blogging API to get some article information from user `nbhankes`:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fy696dcixywrw4an01ct.gif)


The GraphiQL explorer shows us the GraphQL API schema structure of the DEV API and allows us to select the data we'd like to retrieve from the API. As we make this selection, the explorer creates a query, which we see being built in the middle column. Once our query is built, we run the query by hitting the play button on the bar. The query is then sent to the DEV API and the results are displayed on the right.

Below is the actual code for you to study. Notice the terms edges and node in the section labeled GraphQL Query.  nodes define objects and edges define relationships between objects and are optional (except in the Relay GraphQL client). Adding these to a query can be useful when working with complex APIs schemas. For the sake of this introduction, it's just important to be aware of them. If you'd like to dive deeper into edges and nodes, visit [https://www.apollographql.com/blog/explaining-graphql-connections-c48b7c3d6976/](https://www.apollographql.com/blog/explaining-graphql-connections-c48b7c3d6976/)

Let's dive into the code below:

```javascript
//GraphQL Query

query MyQuery {
  devTo {
    articles(username: "nbhankes") {
      edges {
        node {
          title
        }
      }
    }
  }
}


//API Response

{
  "data": {
    "devTo": {
      "articles": {
        "edges": [
          {
            "node": {
              "title": "The API Series - Part 2: The REST API, fetch(), and AXIOS"
            }
          },
          {
            "node": {
              "title": "The API Series - Part 1: An Intro to APIs"
            }
          },
          {
            "node": {
              "title": "Classless CSS Isn't Trashy"
            }
          },
          {
            "node": {
              "title": "Upgrade Your CSS: The Syntax.fm Typography Sizing Strategy"
            }
          }
        ]
      }
    }
  }
}




//GraphQL Query without edges or node

query MyQuery {
  devTo {
    articles(username: "nbhankes") {
      title
    }
  }
}


//API Response without edges or node

{
  "data": {
    "devTo": {
      "articles": [
          {
              "title": "The API Series - Part 2: The REST API, fetch(), and AXIOS"
          },
          {
              "title": "The API Series - Part 1: An Intro to APIs"
          },
          {
              "title": "Classless CSS Isn't Trashy"
          },
          {
              "title": "Upgrade Your CSS: The Syntax.fm Typography Sizing Strategy"
          }
        ]
      }
    }
  }
```

In the above code, you can see that the shape of the query defines the shape of the API response. The response is shaped like a nested JavaScript object and can be handled similarly.

## Using GraphQL in Your Project: A Demo

While the GraphiQL explorer is extremely useful, you can't just add the GraphQL query into your code and expect it to work. Below you'll find a link to a GitHub repo that makes a GraphQL query using plain JavaScript and the Fetch() API. This demonstration repository contains code for a website that queries the [SpaceX GraphQL API](https://api.spacex.land/graphql/) and renders the response data to the browser. The demo built this:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ajpp3fk25fl3qsjahe1s.png)

And the great thing about working with APIs is that if the CEO of SpaceX changes, our website will automatically reflect the changes as soon as the API is updated.

Visit the [Live Demo](https://vanillajs-graphql-demo.surge.sh/)

Link To Repo: [https://github.com/nbhankes/vanillaJS-GraphQL-demo](https://github.com/nbhankes/vanillaJS-GraphQL-demo)

Study the comments and the code in the repository, follow the directions on the README.md file to get the project running on your local environment. Customize the query and template literal for practice.

## Conclusion

In this tutorial you learned how to query data from a GraphQL API. You were exposed to some common tools used to work with GraphQL APIs, the GraphQL syntax and structure, and you received a VanillaJS GraphQL repository to study and get running on your local system.