You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
**This article was last updated on September 12, 2024, to add sections on Error Handling, Batching Multiple Requests, Versioning, and Caching Strategies.**
12
+
11
13
## Introduction
12
14
13
15
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
16
18
17
19
Steps we'll cover:
18
20
19
-
-[Introduction](#introduction)
21
+
-[Architectural Style](#architectural-style)
20
22
-[Architectural Style](#architectural-style)
21
23
-[Data Fetching](#data-fetching)
22
24
-[Flexibility and Efficiency](#flexibility-and-efficiency)
25
+
-[Caching](#caching)
23
26
-[Performance](#performance)
24
27
-[Use Cases](#use-cases)
25
28
-[Summary of differences: REST vs. GraphQL](#summary-of-differences-rest-vs-graphql)
@@ -245,6 +250,63 @@ In REST, we must make two separate requests to fetch the user and the article.
245
250
246
251
```
247
252
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
+
248
310
## Flexibility and Efficiency
249
311
250
312
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
285
347
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.
286
348
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.
287
349
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
+
constcache=newInMemoryCache();
370
+
371
+
constclient=newApolloClient({
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
+
288
379
## Performance
289
380
290
381
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
336
427
|**Performance**| Great in performance but under-performs when it involves complex resource fetching. | Has high performance but underperforms in terms of caching. |
337
428
|**Use Cases**| Used mainly for not-too complex applications and also for CRUD project. | Excels greatly in complex projects and especially chat apps. |
338
429
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.
GraphQL helps clients use deprecated fields while newer clients can use updated fields.
532
+
339
533
## Conclusion
340
534
341
535
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