COLUMN
2024年07月03日
Handling Data Guide for Front-End Engineers: GraphQL and REST API
Categories:Technology
Tags:API
As of 2024, using external service APIs has become commonplace in web development. The main API architectures in use are REST APIs and GraphQL.
This article introduces the differences between them and explains how to handle them efficiently.
Basics of REST API
REST API is a design style for APIs that manipulate data using HTTP methods and URLs. Its main features include being stateless, resource-oriented, and cacheable.
- HTTP Methods
Specify the data operations (retrieve, create, update, delete) - URL
Specify the identifier of the resource to be operated on
For example, to manipulate users (user/users), the URL is specified as follows:
- Retrieve multiple users: GET /users
- Retrieve a specific user: GET /users/:id
- Create a user: POST /users
- Update a user: PUT (or PATCH) /users/:id
- Delete a user: DELETE /users/:id
Furthermore, to retrieve the information that a user possesses (e.g., posts), use relationships as follows. userId
is the ID of the user and specifies "a certain user".
- Retrieve multiple posts of a user: GET /users/:userId/posts
- Retrieve a specific post of a user: GET /users/:userId/posts/:id
- Create a post for a user: POST /users/:userId/posts
- Update a specific post of a user: PUT (or PATCH) /users/:userId/posts/:id
- Delete a specific post of a user: DELETE /users/:userId/posts/:id
This way, by looking at the URL, you can tell which resource is being targeted, and by looking at the HTTP method, you can tell what kind of operation is being performed. This is the feature of REST API.
Advantages of REST
The advantages of REST API are as follows:
Cacheable
Since REST API URLs are unique, GET caching is easy. The same URL returns the same result, so by caching the initially obtained results, performance can be improved.
Stateless
REST APIs are stateless, meaning each request is independent. This allows for easier resource release and improved scalability as there are no dependencies between requests.
Resource-oriented
REST API emphasizes manipulating resources. Therefore, by including resource identifiers in the URL, resource manipulation can be done intuitively.
Disadvantages of REST
On the other hand, REST API has the following disadvantages:
Over-fetching of Data
Typically, REST APIs return all information of each resource. In some situations, only the name might be needed, while in others, both the id and name might be necessary. As a result, the application might fetch unnecessary information, potentially leading to performance degradation.
Deep Nesting
To represent relationships, URLs may be nested. However, deep nesting can make URLs complex and reduce request readability.
For example, to retrieve "users who liked a post of a specific user," the nesting can get deep:
GET /users/:userId/posts/:postId/likes/:likeId
Versioning
When API specifications change, both the old and new versions may need to be supported simultaneously, complicating API maintenance. For REST APIs, version numbers are sometimes included at the beginning of the endpoint or specified in the query string.
Basics of GraphQL
With several challenges identified in REST APIs, GraphQL was introduced. Developed by Facebook, it was open-sourced in 2015. GraphQL is a new query language for retrieving and manipulating data, serving as an alternative to REST APIs.
Features of GraphQL
The features of GraphQL are as follows:
Query Language
GraphQL is a query language that allows clients to request only the data they need. This prevents over-fetching and allows related data to be retrieved simultaneously.
Schema
GraphQL uses a schema to define the structure and operations of data. Queries are constructed based on the schema, facilitating data retrieval and manipulation. The schema allows for features like autocomplete.
Real-time Queries
GraphQL has a subscription mechanism for real-time data retrieval. For example, it can be used to receive chat messages in real-time.
Single Endpoint
Unlike REST APIs, GraphQL uses a single endpoint, making endpoint management easier. It also allows multiple queries to be sent in a single request.
Queries and Mutations
GraphQL has two operations: queries for data retrieval and mutations for data changes. These correspond to GET and POST/PUT/DELETE in REST APIs.
REST API | GraphQL |
---|---|
GET | Query |
POST/PUT/DELETE | Mutation |
Advantages of GraphQL
The advantages of GraphQL are as follows:
Flexible Data Retrieval
GraphQL allows specifying the fields to be retrieved in the response when making a request. This prevents over-fetching and improves performance by retrieving only the necessary fields for the operation.
Bulk Retrieval of Related Data
GraphQL uses relationships to retrieve related data in bulk. For example, it can retrieve a user and their posts in a single request, reducing the need for multiple requests and network traffic.
Real-time Data Retrieval
Subscriptions enable real-time data retrieval. Unlike REST APIs that require a pull model (requests from the client), GraphQL supports a push model (notifications from the server).
Variables
GraphQL allows building dynamic queries using variables. For example, user IDs can be specified as variables to retrieve a specific user's posts, creating general-purpose queries for flexible handling.
Disadvantages of GraphQL
On the other hand, GraphQL has the following disadvantages:
Learning Curve
GraphQL has a different architecture from REST APIs, requiring learning new technologies and potentially leading to a higher learning curve compared to REST APIs.
Difficulty in Caching
Unlike REST APIs, GraphQL does not have fixed URLs, making caching more difficult. Implementing caching for query results requires client-side implementation.
Deep Nesting
GraphQL allows using relationships to retrieve related data, but deep nesting can make queries complex and reduce readability. Additionally, deep nesting can lead to performance degradation. Recursive retrieval, such as replies to posts and replies to replies, is not possible.
Handling Binary Files
GraphQL mainly retrieves data in JSON format, making it unsuitable for retrieving or sending binary files (images, videos, etc.). Handling binary files may require methods like Base64 encoding or using REST APIs with multipart/form-data format.
Comparison of REST API and GraphQL
REST API and GraphQL have different characteristics, and it is important to use them appropriately depending on the use case. The following summarizes the comparison between the two.
Performance
REST APIs have the advantage of being easily cacheable due to fixed URLs. In contrast, GraphQL allows specifying the data to be retrieved in queries, preventing over-fetching and improving performance.
Development Efficiency
GraphQL allows developers to easily specify the data needed using a query language, while REST APIs use URLs and HTTP methods for intuitive resource manipulation.
However, constructing queries on the client side can make the code complicated and reduce readability. Therefore, it is common to define queries in dedicated files to avoid this issue, leading to more reusable and generic queries.
Flexibility
GraphQL uses a schema to define the structure and operations of data, providing flexibility in data retrieval and manipulation. REST APIs focus on resource manipulation, offering intuitive resource operations.
With REST APIs, the resources that can be retrieved are determined by the server, making flexible data retrieval on the client side challenging. GraphQL, on the other hand, allows specifying the required data on the client side, enabling flexible data retrieval.
Error Handling and Security
REST API and GraphQL handle error handling and security differently.
Error Handling
REST APIs use HTTP status codes to represent errors, such as 404 (Not Found) or 500 (Internal Server Error). GraphQL returns errors as objects, which include error codes and messages.
Security
Security handling differs between REST API and GraphQL. REST APIs use HTTP methods for data operations, requiring attention to vulnerabilities such as CSRF (Cross-Site Request Forgery) and XSS (Cross-Site Scripting).
GraphQL can perform type checking for variables according to the schema, supported by server-side libraries in many cases. This allows developers to use variables safely. However, if the library does not support this, query validation is required to prevent vulnerabilities such as query injection.
Authentication and Authorization
Authentication and authorization handling also differ between REST API and GraphQL. REST APIs typically include tokens in the HTTP headers, while GraphQL can include authentication information in queries. In other words, tokens can be included in headers or passed as query variables.
Tools and Libraries
In frontend development, various tools and libraries are used to handle REST APIs and GraphQL. The following introduces tools useful for frontend development with REST and GraphQL.
Postman API Platform
Postman is a tool for testing and debugging APIs. It can send requests to REST API and GraphQL endpoints and check the responses. It is also possible to write test scripts and automate them.
Axios
Axios is an HTTP client library that makes it easy to send requests to REST APIs. It provides a Promise-based API, making it easy to handle asynchronous processing.
Apollo GraphQL
Apollo Client is a GraphQL client library that makes it easy to execute GraphQL queries and mutations. It provides various features such as caching and real-time data retrieval.
GraphQL developer tools
GraphQL developer tools is a Chrome extension that supports GraphQL development. It allows you to check GraphQL queries and schemas, and debug them.
GraphiQL
GraphiQL is a web-based IDE for executing GraphQL queries. You can write and execute queries and check the results. It also allows you to check schemas and browse documentation.
WunderGraph Cosmo
WunderGraph Cosmo is software for managing the lifecycle of GraphQL. It manages schema versions, analysis, routing, and more.
Future Trends and Outlook
In frontend development, REST API and GraphQL are currently widely adopted, but it is also important to consider future trends and outlooks.
Potential Evolution of REST API and GraphQL
The concept of REST emerged in 2000, approaching a quarter-century. Similarly, GraphQL's predecessor, FQL (Facebook Query Language), appeared in 2012. Both have evolved to solve various challenges.
The opportunities to use APIs are increasing yearly, and new technological approaches and the evolution of existing technologies are expected. Both REST APIs and GraphQL have the potential to evolve further in the future.
New Technologies and Approaches
New technologies and approaches, such as gRPC and serverless, are gaining attention. gRPC is an RPC (Remote Procedure Call) framework developed by Google, enabling fast communication. Serverless is a technology that entrusts server management to cloud providers, executing a single function.
HTTP/3 uses UDP-based QUIC (Quick UDP Internet Connections) for communication instead of traditional TCP. While QUIC's reliability is slightly lower due to using UDP, it improves communication speed and performance. APIs that align with this may emerge in the future.
These technologies and approaches are expected to open new possibilities for API development and operation.
Adaptation Strategies for Frontend Engineers
For frontend engineers, continuous learning is crucial to adapt to new technologies and approaches. Deepening knowledge about API mechanisms and data handling, and incorporating the latest technologies and tools, is required.
Conclusion
For frontend engineers, REST API and GraphQL are indispensable technologies. Understanding the characteristics, advantages, and disadvantages of both, and using them appropriately is essential. Additionally, paying attention to new technologies and approaches and continuously learning to stay up-to-date with the latest trends is necessary.
Hexabase supports both REST API and GraphQL. The TypeScript SDK uses both APIs, enabling data transmission and reception without being conscious of the API. Please consider using Hexabase.