DEV Community

Cover image for Introduction to GraphQL
Adriana DiPietro
Adriana DiPietro

Posted on

Introduction to GraphQL

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
  2. How It Works
  3. Differences Between GQL + REST
  4. Elements of GraphQL
  5. Summary + Recap

GraphQL is a Query Language

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

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 flow 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

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


Elements of GraphQL

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

Data Types

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

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
}
Enter fullscreen mode Exit fullscreen mode

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!
}
Enter fullscreen mode Exit fullscreen mode

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


Scalars

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
}
Enter fullscreen mode Exit fullscreen mode

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

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
}
Enter fullscreen mode Exit fullscreen mode

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

  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.
  5. 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.

🍵Make sure to check out GraphQL's official website here for documentation and more information.

🍵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.

Discussion (3)

Collapse
cerchie profile image
Lucia Cerchie

This was a clear and informative introduction to GraphQL, Adriana!

Collapse
am20dipi profile image
Adriana DiPietro Author

Thank you Lucia! Are you currently studying or implementing GQL in your work?

Collapse
cerchie profile image
Lucia Cerchie

I am!
I work at StepZen -- you can try it out here https://stepzen.com/getting-started?details=examples&example=rest-directive

Staying on top of our GraphQL game is paramount since we provide GraphQL APIs ;)

When I started, I was new to GraphQL completely, so I relied a lot on articles like yours. Keep it up!