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

查看:110
本文介绍了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?

谢谢.

推荐答案

有很多关于此问题的文章,可以从Internet上获得更多详细信息.我想在这里做一个简短的概述.

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天全站免登陆