What's the difference between GraphQL and rest api

。_饼干妹妹 提交于 2021-02-05 09:12:06

问题


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

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?

Thanks in advance.


回答1:


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

GraphQL offers a couple of advantages over REST.

Main difference

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.

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

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

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.

Some advantages

  • As already mentioned in the question, you can reduce the amount of HTTP operations with the help of GraphQL queries (avoid underfetching).
  • By specifying exactly, which data you want to fetch, you are able to reduce the overhead being transmitted over the interface (avoid overfetching).
  • By using flexible queries with GraphQL, you're more likely to avoid coupling the interface consumer too tight to the producer by not implementing exactly the requirements of a specific consumer into a REST interface with defined endpoints.
  • Because each consumer exactly specifies which data is required with GraphQL, you can gather more detailed statistics on data usage in your backend.


来源:https://stackoverflow.com/questions/60200177/whats-the-difference-between-graphql-and-rest-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!