DEV Community

Cover image for A Quick Guide for GraphQL
Weseek-Inc
Weseek-Inc

Posted on • Updated on • Originally published at weseek-inc.Medium

A Quick Guide for GraphQL

Introduction

Hi, I am Kota, a system engineer from WESEEK, Inc. in Japan.

This time, I have decided to write a blog about my introduction to GraphQL, which I had not yet touched.


What Is GraphQL?

GraphQL is a query language for APIs and a runtime for building data-driven applications, developed by Facebook and released as open-source in 2015.

It allows clients to specify the data they need, unlike REST APIs that query endpoints, thus optimizing network usage and improving performance. It also eliminates API versioning issues and allows for API and front-end development decoupling.


Technology Before GraphQL Appeared

Before the advent of GraphQL, the predominant way of exchanging data in web applications was through RESTful APIs, which strictly followed the HTTP protocol and used endpoints to access resources.

However, this RESTful approach had several problems.

The first is the problem of “overfetching” and “underfetching”. “Overfetching” means that the client gets more data than it needs, which consumes unnecessary network and computational resources, while “underfetching” means that the client gets more data than it needs, which consumes unnecessary network and computational resources. On the other hand, “underfetching” refers to the fact that the client cannot get all the data it needs at once and must make multiple requests.

The second is endpoint complexity, which requires independent endpoints for each resource, so as the API grows, the number of endpoints increases and becomes more difficult to manage. In addition, multiple requests are required to retrieve data from multiple endpoints.

Third is the versioning problem, which makes API versioning difficult because a new version of the endpoint must be created each time the format or structure of the data changes.

The fourth implies a strong coupling between the client and server since the endpoint design is highly dependent on the data structure needed by the client. This problem makes it difficult to have front-end and back-end development going at the same time.

These problems were greatly improved with the advent of GraphQL. Specifically, GraphQL allows a single endpoint to retrieve multiple resources, eliminating the need for versioning and allowing for client and server decoupling.


What Has Changed With GraphQL?

With the advent of GraphQL, the above problems were greatly alleviated. This is because GraphQL provides the client with precision in identifying and retrieving data.

Specifically, GraphQL gives clients the ability to specify which fields to retrieve, thereby ensuring that only the required data is retrieved accurately. This improves network utilization and avoids wasting resources by fetching unnecessary data.

In addition, because GraphQL functions as a query language, it is now possible to retrieve complex data and refine the data. These elements are critical to the flexibility and performance of the API.


GraphQL vs REST

REST and GraphQL are both technologies for building APIs but with the following differences.

First, REST returns a fixed data structure for each endpoint. While this is simple and easy to understand, it is prone to the aforementioned “overfetching” and “underfetching” problems.

In contrast, GraphQL allows clients to freely specify the data they need, thus avoiding unnecessary data fetching. This leads to efficient network utilization and high performance.

Furthermore, with REST, if data needs to be retrieved across multiple endpoints, multiple requests must be made. GraphQL, on the other hand, allows multiple resources to be retrieved with a single request. This greatly reduces the number of requests.

Code Comparison

To understand the difference between GraphQL and REST APIs, let’s compare their respective requests and responses using a simple example.

For example, let’s say we want to retrieve information about a user and the title of a blog post by that user. Let’s see how each API style does this.

REST API

In a REST API, there is usually a separate endpoint for each resource. You would first retrieve the user’s information, and then make separate requests to retrieve the user’s postings.

The first request (to retrieve user information):

The first request

Response:

Response1

The second request (to retrieve user posts):

The second request

Response:

Response2

GraphQL

GraphQL, on the other hand, allows the client to retrieve all necessary information in a single request. The client can also specify the exact shape and amount of data needed. An example is shown below.

Request:

Request3

Response:

Response3

Thus, GraphQL has the advantage that a single request can retrieve multiple related resources and the client can specify the exact data needed. In contrast, the REST API may require multiple requests and return data in a form and quantity defined on the server side.


GraphQL 3 Key Features

The primary functions of GraphQL are queries, mutations, and subscriptions.

Query

A query reads data. The following is an example of a GraphQL query:

Query

The query retrieves the name and email fields for a user whose id is 1. The query keyword is optional, but it is easy to read and understand if it is stated. user is the field name, and the id in this case represents an argument. By using arguments, you can retrieve specific users, posts, etc.

Mutation

Mutation is the modification of data. This includes creating, updating, and deleting data. The following is an example of a mutation:

Mutation

Mutation creates a new user by calling the createUser function and providing the user’s name and email using the input argument. The function returns the id, name, and email of the newly created user. Mutations are used for operations that modify data, such as creating, updating, or deleting data, and always begin with the mutation keyword.

Subscription

Subscriptions are real-time data updates. The client is notified when a server-side event is triggered. The following is an example of a subscription:

Subscription

Subscriptions are used to notify clients in real-time when a new user is created with its id, name, and email. Subscriptions are used to notify clients when a specific event occurs on the server, in this case the creation of a new user. Subscriptions begin with the subscription keyword.


About GraphQL Schema and Type System

GraphQL provides a powerful type system to clearly define the shape and interaction of the data available through the API. This is known as a “schema”. A schema defines what data a client can retrieve from a server and how that data interacts with it.

Type system

The schema consists of “types” that represent objects with specific shapes and characteristics. Types range from simple scalar types (String, Int, Boolean, Float, ID) to more complex object, enumeration, interface, and union types. These are combined to form the overall picture of the data that the API represents.

For example, imagine an API for a blogging system. In this system, the schema would probably have object types such as “user,” “post,” “comment,” and so on. Each type would have different fields, such as name and age (user), title and content (article), body (comment), etc. Here is the specific code:

Type system

These types can have scalar or other object types. In this example, the posts field of type User indicates that it has a list of type Post, and vice versa, the author field of type Post indicates that it has a type User.

In particular, we will discuss notations such as [Post!] notation. This notation indicates an array of type Post, but there are two ! has two different meanings.

The first ! indicates that Post objects are required (non-nullable). This means that if an array exists, all elements contained within it must be objects of type Post, and null elements are not acceptable.

The second ! indicates that the array itself is required (non-nullable). That is, the posts field should always return an array of type Post, and the array itself is not allowed to be null.

Thus, [Post!] means that the array itself must exist and that the contents of the array must consist of one or more objects of type Post, which may never contain null. This allows the detailed definition of the type of each field and its null tolerance.

Relationships

In this way, the GraphQL schema also represents relationships between data. For example, a “user” can have multiple “articles” and each “article” can have multiple “comments”. These relationships are represented through fields of type Object. This relationship allows the client to select and retrieve only the data they need.

Schema Definition Language (SDL)

GraphQL schemas are written using a special syntax called Schema Definition Language (SDL). This SDL is a language for defining GraphQL data structures and can define various data types, such as the Userand Post types described above.

In a type definition, fields are defined in parentheses following the type name, and the type of the field is specified after each field. After the field name, a ! after the field name indicates that the field is required (not nullable). A [] before the type name indicates an array of that type.

In addition, the following special types exist in the schema:

  • Query type: This is the entry point for the query. Used by the client to read data.
  • Mutation type: handles data modification (creation, update, deletion). Used when the client modifies data.
  • Subscription type: monitors real-time updates. Used when the client tracks real-time changes to data.

These special types allow clients to request various operations from the server, such as data reading, modification, and real-time monitoring.

3type

In the above example, a Query type is defined, with fields such as users, users, and posts. Each of these fields returns a list of all users, users with a given ID, and all posts, respectively.

The Mutation type, on the other hand, defines fields for creating new users and posts, named createUser and createPost, respectively, along with the necessary parameters. These operations allow the client to create new users and posts.

The Subscription type defines a field postCreatedto provide information in real-time when a new post is created. This allows clients to monitor the creation of new posts in real-time.

These types and relationships allow the client to query exactly the data it needs and the server to validate the query and return accurate data. This demonstrates the power of GraphQL’s schema and type system.


About Us💡

In addition, we want to introduce a little more about GROWI, an open software developed by WESEEK, Inc.

GROWI is a wiki service with features-rich support for efficient information storage within the company. It also boasts high security and various authentication methods are available to simplify authentication management, including LDAP/OAuth/SAML.

GROWI originated in Japan and GROWI OSS is FREE for anyone to download and use in English.

For more information, go to GROWI.org to learn more about us. You can also follow our Facebook to see updates about our service.

GROWI.org

Top comments (0)