Skip to content

Commit 9b3ecc4

Browse files
authored
docs(blog): update rest post (#6325)
1 parent 435ab46 commit 9b3ecc4

File tree

1 file changed

+196
-2
lines changed

1 file changed

+196
-2
lines changed

documentation/blog/2023-12-03-graphql-vs-rest.md renamed to documentation/blog/2024-09-12-graphql-vs-rest.md

Lines changed: 196 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,12 @@ description: We'll explore the key differences between GraphQL and REST, and dis
44
slug: graphql-vs-rest
55
authors: chidume_nnamdi
66
tags: [dev-tools, comparison]
7-
image: https://refine.ams3.cdn.digitaloceanspaces.com/blog/2023-12-03-graphql-vs-rest/social.png
7+
image: https://refine.ams3.cdn.digitaloceanspaces.com/blog/2023-12-03-graphql-vs-rest/social-2.png
88
hide_table_of_contents: false
99
---
1010

11+
**This article was last updated on September 12, 2024, to add sections on Error Handling, Batching Multiple Requests, Versioning, and Caching Strategies.**
12+
1113
## Introduction
1214

1315
The internet is connected using a standard method called HTTP. This enabled communication between devices to be possible. Despite all these, protocols were put in place for the design and communication of these devices to be efficient. Protocols were created, SOAP, XML-RPC, etc. But the protocols that have stood the test of time are REST, coined by Roy Fielding in 2000 in his doctoral dissertation, Architectural Styles and the Design of Network-based Software Architecture, and GraphQL, a new kid on the block. These two have proven themselves over time, and they have become the most used protocols in the world.
@@ -16,13 +18,16 @@ In this article, we will explore the key differences between GraphQL and REST, a
1618

1719
Steps we'll cover:
1820

19-
- [Introduction](#introduction)
21+
- [Architectural Style](#architectural-style)
2022
- [Architectural Style](#architectural-style)
2123
- [Data Fetching](#data-fetching)
2224
- [Flexibility and Efficiency](#flexibility-and-efficiency)
25+
- [Caching](#caching)
2326
- [Performance](#performance)
2427
- [Use Cases](#use-cases)
2528
- [Summary of differences: REST vs. GraphQL](#summary-of-differences-rest-vs-graphql)
29+
- [Batching Multiple Requests](#batching-multiple-requests)
30+
- [Versioning](#versioning)
2631

2732
## Architectural Style
2833

@@ -245,6 +250,63 @@ In REST, we must make two separate requests to fetch the user and the article.
245250

246251
```
247252

253+
### Error Handling
254+
255+
Both REST and GraphQL handle errors differently. Here's how:
256+
257+
### REST Error Handling
258+
259+
REST typically uses **HTTP status codes** to indicate the success or failure of an API request. Good examples of it are `200 OK` being a successful response while `404 Not Found` and `500 Internal Server Error` spelling out errors.
260+
261+
```json
262+
GET /users/12345
263+
264+
HTTP/1.1 404 Not Found
265+
Content-Type: application/json
266+
267+
{
268+
"error": {
269+
"code": 404,
270+
"message": "User not found"
271+
}
272+
}
273+
```
274+
275+
### Error Handling in GraphQL
276+
277+
In GraphQL, the errors will be part of the response body, contrary to trying to map them through HTTP status codes. When an error occurs in any part of the execution of a GraphQL query, it can return back individual errors for fields or operations in that query.
278+
279+
```graphql
280+
{
281+
user(id: "12345") {
282+
name
283+
email
284+
}
285+
}
286+
287+
# Response
288+
289+
{
290+
"data": {
291+
"user": null
292+
},
293+
"errors": [
294+
{
295+
"message": "User not found",
296+
"locations": [
297+
{
298+
"line": 2,
299+
"column": 3
300+
}
301+
],
302+
"path": ["user"]
303+
}
304+
]
305+
}
306+
```
307+
308+
The snippet above shows a case where the `user` in the request did not exist; however, the response is valid because there is an existing `data` object and an `errors` array indicating that the `user` does not exist.
309+
248310
## Flexibility and Efficiency
249311

250312
In this section, we will discuss the flexibility and efficiency of GraphQL and REST.
@@ -285,6 +347,35 @@ GraphQL gives clients fine-grained control over the response structure. Clients
285347
Caching proves to be difficult with GraphQL. The dynamic nature of GraphQL queries makes it challenging to cache responses. The same query may be executed with different arguments, resulting in different responses. Caching becomes more complex as responses are no longer uniform, and caching mechanisms must account for the variability in queries.
286348
This can lead to cache invalidation issues and can be challenging to manage. Although tools and libraries have emerged to address these challenges, caching in GraphQL requires careful consideration.
287349

350+
## Caching
351+
352+
The approaches to caching are also very different in REST and GraphQL. REST builds on top of HTTP caching. Since REST is strongly typed, it provides with it built-in GraphQL caching. It does not have to be advanced as in the case of GraphQL, though. The above structure pertains to REST caching. REST APIs can also leverage such in-built HTTP cache mechanisms, among which there are **ETags** and **Cache-Control** headers.
353+
354+
```http
355+
GET /users/12345
356+
Cache-Control: max-age=3600
357+
ETag: "abc123"
358+
```
359+
360+
This tells the client to cache the response for one hour (`3600` seconds) and only request updates if the `ETag` is changed.
361+
362+
### GraphQL Caching
363+
364+
This might be a bit more complicated with GraphQL, since one query typically requests data from various resources, so HTTP-level caching won't work well. Instead, it would be client-side caching tools like Apollo Client or Relay.
365+
366+
**Apollo Client Example**:
367+
368+
```js
369+
const cache = new InMemoryCache();
370+
371+
const client = new ApolloClient({
372+
uri: "https://example.com/graphql",
373+
cache,
374+
});
375+
```
376+
377+
Apollo Client will take care of caching the responses to all of those queries according to a unique identifier, for example, the user `id`.
378+
288379
## Performance
289380

290381
In the last sections, we have seen how GraphQL and REST differ in terms of data fetching and flexibility. In this section, we will discuss the performance of both. Let's go!
@@ -336,6 +427,109 @@ Also, GraphQL is best suited for real-time applications. Your social media appli
336427
| **Performance** | Great in performance but under-performs when it involves complex resource fetching. | Has high performance but underperforms in terms of caching. |
337428
| **Use Cases** | Used mainly for not-too complex applications and also for CRUD project. | Excels greatly in complex projects and especially chat apps. |
338429

430+
## Batching Multiple Requests
431+
432+
One of the upsides to using GraphQL is that it allows for batching multiple requests in a single query, while REST typically requires multiple HTTP requests for each resource.
433+
434+
### REST (Multiple Requests)
435+
436+
```http
437+
# Getting data of the user
438+
GET /users/12345
439+
440+
{
441+
"id": 12345,
442+
"name": "John Doe"
443+
}
444+
445+
# Getting user's posts
446+
GET /users/12345/posts
447+
448+
[
449+
{ "id": 1, "title": "First Post" },
450+
{ "id": 2, "title": "Second Post" }
451+
]
452+
```
453+
454+
It will require two different requests for getting the user and his post.
455+
456+
### GraphQL (Single Request)
457+
458+
```graphql
459+
{
460+
user(id: "12345") {
461+
name
462+
posts {
463+
title
464+
}
465+
}
466+
}
467+
468+
# Response
469+
470+
{
471+
"data": {
472+
"user": {
473+
"name": "John Doe",
474+
"posts": [
475+
{ "title": "First Post" },
476+
{ "title": "Second Post" }
477+
]
478+
}
479+
}
480+
}
481+
```
482+
483+
In GraphQL, the record for a user and their posts is fetched with a single request, reducing network overhead.
484+
485+
## Versioning
486+
487+
Versioning in APIs is dealt with quite differently between REST and GraphQL. REST generally requires versioning for changes, where GraphQL manages this transparently.
488+
489+
### REST Versioning
490+
491+
REST APIs typically use versioning in the URL to handle changes to the API as time goes on.
492+
493+
```http
494+
# Version 1
495+
GET /api/v1/users/12345
496+
497+
# Version 2
498+
GET /api/v2/users/12345
499+
```
500+
501+
Each version can bring breaking changes, and clients would need updates to use the correct version of the API.
502+
503+
### GraphQL Versioning
504+
505+
GraphQL does not need versioning because you can deprecate the specific fields and introduce new ones without breaking existing queries.
506+
507+
```graphql
508+
{
509+
user(id: "12345") {
510+
name
511+
email
512+
phoneNumber @deprecated(reason: "Use `mobileNumber` instead")
513+
mobileNumber
514+
}
515+
}
516+
517+
# Response
518+
519+
{
520+
"data": {
521+
"user": {
522+
"name": "John Doe",
523+
"email": "[email protected]",
524+
"phoneNumber": null,
525+
"mobileNumber": "123-456-7890"
526+
}
527+
}
528+
}
529+
```
530+
531+
GraphQL helps clients use deprecated fields while newer clients can use updated fields.
532+
339533
## Conclusion
340534

341535
In this article, we started by introducing REAT and GraphQL. Next, we discussed and learned about the architectural style of REST and GraphQL. We also discussed the data fetching of both approaches. We saw different scenarios where REST and GraphQL will be used. We saw the ups and downs of each approach and how they can be used to solve different problems.

0 commit comments

Comments
 (0)