GraphQL 和 rest api 有什么区别 [英] What's the difference between GraphQL and rest api

查看:28
本文介绍了GraphQL 和 rest api 有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道使用 qraphQL 而不是 rest api 的所有原因是什么.

I want to know what are all reasons of qraphQL to be used instead of rest api.

据我所知,可以使用 graphQL 在一个请求中发出一组 HTTP 请求,而不是发出多个请求(以减少 HTTP 请求).

As much I know instead of making multiple requests (to reduce HTTP request), can make a group of HTTP requests in one request using graphQL.

有没有人可以再描述一下?

Can anybody describe little more, please?

提前致谢.

推荐答案

互联网上有很多文章详细介绍了这个问题.我想在这里做一个简短的概述.

There are many articles covering this question in more details available on the internet. I am trying to give a short overview here.

GraphQL 提供了几个优于 REST 的优势.

GraphQL offers a couple of advantages over REST.

主要区别

REST 界面中,一切都与资源有关.例如,您可以通过调用这样的端点来获取 ID 为 25 和 ID 83 的资源car":

In a REST interface, everything is about resources. For example, you'd get the resources "car" with ID 25 and ID 83 by calling an endpoint like this:

GET /cars/25
GET /cars/83

注意,您必须如何调用接口两次.端点(汽车")和您的资源是耦合的.

Note, how you have to call the interface twice. The endpoint ("cars") and your resource are coupled.

GraphQL 中,您可以使用以下示例查询通过一次调用获取两辆车:

In GraphQL you could get both cars with one call, using this example query:

GET /api?query={ car(ids: [25, 83]) { model, manufacturer { address } } }

请注意,您甚至如何指定要获取的确切数据(型号、制造商及其地址).与 REST 相比,端点(api")不再是特定于资源的.

Note, how you even specified the exact data you want to fetch (model, manufacturer and its address). Compared to REST, the endpoint ("api") is not resource-specific anymore.

一些优势

  • 正如问题中已经提到的,您可以在 GraphQL 查询的帮助下减少 HTTP 操作的数量(避免获取不足).
  • 通过准确指定要获取的数据,您可以减少通过接口传输的开销(避免过度获取).
  • 通过在 GraphQL 中使用灵活的查询,您更有可能避免将接口使用者与生产者耦合得太紧,因为您不会将特定使用者的要求准确地实现到具有定义端点的 REST 接口中.
  • 因为每个消费者都准确地指定了 GraphQL 需要哪些数据,所以您可以收集有关后端数据使用情况的更详细的统计数据.

这篇关于GraphQL 和 rest api 有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆