Introduction to GraphQL
Tags: graphql, webdev, beginners, programming
Published: 2022-04-07 19:58:22

Hi everyone! 

Today we are learning about **GraphQL**! GraphQL is a new tool for me that I am lucky enough to learn about and use in my internship. _So_, I figured together we can learn what GraphQL is, why it is important and how we can use it. 

Let's get started! 

___________________________________________________________

## Learning Goals

1. [GraphQL is a Query Language](#language)
2. [How It Works](#works)
3. [Differences Between GQL + REST](#rest)
4. [Elements of GraphQL](#elements)
       - [Queries / Types](#types)
       - [Data Types](#datatypes)
       - [Scalars](#scalars)
       - [Enums](#enums)
5. [Summary + Recap](#recap)



________________________________________________________

## GraphQL is a Query Language <a name="language"></a>

As the title of this section suggests, **GraphQL is a Query language**. What does this mean? It means that GraphQL is a _programming_ language used to **get** and **post** data. 

_It is important to acknowledge what GraphQL is because of its name. While many databases end with "QL", GraphQL is NOT a database! Do not get confused by this._

A "query", as you may have guessed, is a request usually for information (in programming: data!). In life, I can query how old you are by asking you "Hey, how old are you?". In return, you may answer: "25" "I am not telling!" "I am turning 30 in July." 

Using GraphQL, we create queries to get data from our database. We ask our database: "How many users have brown eyes?" "How many pets does user 129i04u83 have?" "What stores are located in NYC?"

**Recap**: GraphQL is a QUERY language that we use to get and post data from our database. 

Now, let's learn how it _really_ works. 

________________________________________________________

## How It Works <a name="works"></a>

The client (the frontend of an application) uses GraphQL API to communicate with the database. Think of GraphQL as the bridge between the client and the database -- it does all the talking -- it is the middleman! 

How does the client use GraphQL API? Answer: through the `'/graphql'` endpoint. The client makes a request with a query to this endpoint (and this endpoint _only_) and the query determines what data is received or posted. Ultimately, the query _describes_ to the endpoint what it wants. 

The <u>flow</u> is as follows:

   - The client makes a request with a query to the GraphQL endpoint =>
   - The query is sent to GraphQL API =>
   - GraphQL parses (JSON) the query => 
   - GraphQL sends the desired data back to the client


________________________________________________________

## Differences Between GQL + REST <a name="rest"></a>

In the section above, we learned that the client only has to make requests to a single endpoint: `'/graphql'`. Which means GraphQL throws out the idea of REST (and its many, many endpoints) in order to use the single endpoint. Why?

With GraphQL, queries determine _exactly_ what data is to be received or posted. These queries completely diminish the need to specify endpoints. Queries also reduce the amount of **overfetching** and **underfetching** of data in an application. 

Overfetching occurs when the client receives more data than is needed from a specific REST endpoint. 

For example, if I am building an application that takes a user's age and outputs their expected high school graduation year, I only really need the user's age. But say within my database, in addition to the user age data, I also have their address, height and eye color. None of that data is necessary for my application. Graphql querying allows a pinpoint level of specification as to not receive unnecessary data that may slow down the application or cost a lot of money. 

Underfetching is quite the opposite: it occurs when a specific REST endpoint does not provide all the data required/desired for an application. 


Check out this diagram below for a visual representation:

![rest v graphql](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bsj2o0b8qr0vixehxmwo.png)
 
 

________________________________________________________

## Elements of GraphQL <a name="elements"></a>

Let's look into some of the elements of GraphQL to get a better understanding: 

### Data Types <a name="datatypes"></a>

GraphQL has five (5) data types:
   - ID **=>** a unique identifier
   - String **=>** a UTF-8 character sequence
   - Int **=>** a signed 32-bit integer
   - Boolean **=>** true or false
   - Float **=>** a decimal

___________________________________________________________

### Queries / Types <a name="types"></a>

Now that we know what a query is, we can look into how GraphQL defines them.

GraphQL describes a query using the **type** keyword. For example, to create a query for "cat" with fields "name", "age" "color", "breed", we would code it out like this:

```
type Cat {
   name: String
   age: Int
   color: String
   breed: String
}
``` 
Within each field, we declare the field name (or a _key_) and the data type of its value. So the name, color and breed of a Cat is a string, while the age is an integer. 

While querying, we can non-nullify the values of a field using an exclamation point(!) -- meaning the value of a cat's name cannot be "null". Like this: 

```
type Cat {
   name: String!
   age: Int!
   color: String!
   breed: String!
}
``` 

This is the basic, universal syntax for defining a query in GraphQL. 
___________________________________________________________

### Scalars <a name="scalars"></a>

While the above, five (5) data types are scalars in GraphQL, GraphQL also allows for custom scalars. What does this mean? It means we can create and initialize our own "data types" to be used to query. 

For example, let's say we have to query for website data:

```
type Website {
    id: ID
    name: String
    url: Url
}
```

This query returns the website's id, name and url. We could possible store the value of the url field as a string, but then any ol' string could be assigned to "url". Such as "ww.google.com" or "hey hey hey". And those are not valid urls. So, instead, we could just create our own scalar called "Url". 

In order to create our own scalar, we need to consider a few things:

   **1.** How the scalar's value is represented in the backend
   **2.** If and how the value's backend representation is JSON-compatible

So, a Url would be represented as a string in the backend, but a _regexed_ string. Meaning, it has to fulfill some requirements, such as:

   - starts with "https://www."
   - includes ".com", ".edu", ".org"... etc
   - does not have any spaces

With the scalar's value represented as a regexed string in the backend, we can ensure it is JSON-compatible in order to be sent to the frontend successfully: Strings are indeed very JSON-compatible!

There are many more custom scalars to be created:
   - Date
   - Time
   - Email
   - RGB color hex

What else can you think of?

___________________________________________________________

### Enums <a name="enums"></a>

Enums are basically a "special" data type we can use to catalog all the possible values or options for a given field. In short, the specified values of an enum are the _only_ _accepted_ options. 

For example:

```
enum BoxState {
    SHIPPED
    DELIVERED
    PENDING
}
```

When querying an object "box" and we want to know the state of the box, BoxState can only be provided the values of: SHIPPED, DELIVERED, or PENDING. The value cannot be "12", true/false, or "Awaiting truck for pickup".

Enums provide a specificity that keeps data values contained and limits bugs. 


________________________________________________________

## Summary + Recap <a name="recap"></a>

1. GraphQL is a QUERY language.
2. A query is a request for information/data. 
3. With GraphQL, the client uses a single endpoint to make requests: `'/graphql'`
4. GraphQL removes the need for many REST endpoints because of its queries. 
6. A "type" is a query.
6. An "enum" defines all possible, accepted values for a field.
7. Custom scalars can be defined and implemented as values for fields. 
8. Overfetching => receiving too much data that is not necessary for the application.
9. Underfetching => an endpoint not providing the desired data necessary for the application. 


:tea:Make sure to check out GraphQL's official website [here](https://graphql.org/) for documentation and more information.


:tea:Thank you for reading along and learning with me. Please feel free to share, like and comment below. But, please remember, everyone is always learning and the "correct" way is not always the best way.