What is GraphQL?
Tags: graphql, webdev, tutorial, javascript
Published: 2021-04-10 10:09:19

**GraphQL is a query language for reading and mutating data in APIs**

By the end of this, you'll understand what GraphQL is, how it works and how's it different from REST. I will also provide some resources for further research. I'll try to be concise...

___

Let's start by explaining how REST works. And if you're familiar, you can jump to [this section](#gql),


### REST

REST, or Representational State Transfer, is an architectural style for providing standards between computer systems on the web, making it easier for systems to communicate with each other. In other words, with REST, as with GraphQL, we are *consuming* an API. In the case of RESTful API, data entities live on various URLs on a server. When a request is received the API responds with the full data payload of that entity. Hence, there are two possible drawbacks here. First, we may need multiple entities at the same time in which case each request is *under-fetching* the data we want. Second, we may only want a small subset of a larger data entity in which case we need to *over-fetch* from the API. 

___

### GraphQL <a name="gql"></a>

So, we said that GraphQL is a query language for reading and mutating data in APIs. While in a RESTful API, data lives on multiple URLs on a server. In the case of GraphQL, the API has a single entry point (`/graphql`). 

Now, let's imagine we have a team of 2, one Front End dev and one Back End dev. They are building a Koala managing website. In terms of GraphQL the perspective of the two devs, in a nutshell, looks like this:

1. **Front End Dev**: Explores and requests the **exact** data they need (not like in the case of RESTful API)
2. **Back End Dev**: Writes code to resolve that request

#### Back End work

Define a schema with all details needed about a Koala:
```graphql
type Koala {
  id: ID!
  name: String!
  limbs: Int!
  diet: [Plant]
  fluffy: Boolean!
}
type Plant {
  id: ID!
  name: String!
  calories: Int!
}
```
! - means this is required. `Koala` is a custom object name. ID, String, Int, Boolean are data types. We can have a custom type as well, like `Plant`. If we write a type inside [ ], then it's an array.

Evey GraphQL API has a Query type. It's a main entry point for a consumer of the API. `getKoalas` returns all Koalas, while `getKoala` returns a single one.
```graphql
type Query {
  getKoalas: [Koala]
  getKoala(koalaId: ID!): Koala
}
```
To mutate data, implement the Mutation type.
```graphql
type Mutation {
  createKoala(name: String!, limbs: Int!, fluffy: Boolean!, 
    plant: { name: String!, calories: Int!}): Koala
  deleteKoala(koalaId: ID!): String
}
```
Afterwards, define the code to resolve `getKoalas`, `createKoala` and others in any programming language. 
____

#### Front End work

Query (fetch) data by describing it with a syntax that mirrors its return shape in JSON. Often, with React, you'd be using something like [React Query](https://www.npmjs.com/package/react-query) or [Apollo GraphQL](https://www.apollographql.com/).

In the case of Apollo GraphQL, it will look something like this:
```javascript
//...

 const { data: { getKoala } = {} } = useQuery(FETCH_KOALA_QUERY, {
    variables: {
      koalaId,
    },
  });

//...
```
Where FETCH_KOALA_QUERY:
```javascript
import gql from 'graphql-tag';

const FETCH_POST_QUERY = gql`
  query($koalaId: ID!) {
    getKoala(koalaId: $koalaId) {
      id
      name
      diet {
        name
      }
    }
  }
`;

//...
```
And this is the pattern that you'll use for the rest of the fetching part of the code.
___

### Resources

As I tried to be concise, I'll leave you with some resource for further research. Have fun, GraphQL is awesome!

- [GraphQL vs REST](https://www.youtube.com/watch?v=AYZOHt6kz6Y)
- [GraphQL Basics](https://www.youtube.com/watch?v=7wzR4Ig5pTI)
- [GraphQL Full Course](https://www.youtube.com/watch?v=ed8SzALpx1Q)
- [Official Docs](https://graphql.org/)

Additionally, you can check out my MERNG stack side project w/ Apollo GraphQL and TailWindCSS:
-[server](https://github.com/daliboru/smb-server)
-[client](https://github.com/daliboru/smb-client)

___

##Thank You!

I hope you find this post useful! Any feedback is greatly appreciated!

Cheers,
Dalibor