graphql和rest
What is GraphQL? Why You Should Care About GraphQL?
什么是GraphQL? 为什么您应该关心GraphQL?
什么是GraphQL? (What Is GraphQL?)
GraphQL is a kind of Query syntax that defines the way any server-side data needs to be fetched using API’s
GraphQL是一种查询语法,它定义了需要使用API获取任何服务器端数据的方式
GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools.
GraphQL为您的API中的数据提供完整且易于理解的描述,使客户能够准确地询问他们需要什么,仅此而已,使随着时间的推移更容易开发API并启用强大的开发人员工具。
GraphQL具有三个主要特征: (GraphQL has three main characteristics:)
- It lets the client describe exactly what kind of data it is interested in. 它使客户端可以准确描述其感兴趣的数据类型。
- One can source data from multiple data sources. 一个人可以从多个数据源中获取数据。
- It uses a type system to describe data. 它使用类型系统来描述数据。
Practically speaking, the GraphQL layer lives between the client and one or more data sources, receiving client requests, and fetching the necessary data according to your instructions.
实际上,GraphQL层位于客户端和一个或多个数据源之间,接收客户端请求,并根据您的指令获取必要的数据。
它是如何工作的? (How Does It Work?)
In Order to understand as a layman, how does GraphQL works at a higher level, we need to first understand REST API’s
为了理解外行,GraphQL如何在更高层次上工作,我们需要首先了解REST API的
什么是REST?(What Is REST?)
REST is an acronym for REpresentational State Transfer. It is an architectural style for distributed hypermedia systems and was first presented by Roy Fielding in 2000
REST是RE表象小号泰特贸易交接的缩写。 它是分布式超媒体系统的体系结构样式,由Roy Fielding于2000年首次提出。
我们来看一个用例: (Let’s take a use case:)
- You are hungry and you want to east pizza, but also you want to have your favorite tomato ketchup, to spice p your taste buds. Also, you want to have an energy drink to complement your appetite. Now these three items are supposed to be sourced from three different sources which in this case is 您饿了,您想东披萨,但同时您也想要自己喜欢的番茄酱,来调味您的味蕾。 另外,您想喝些能量饮料来补充胃口。 现在这三个项目应该来自三个不同的来源,在这种情况下是
- Dominos Pizza多米诺比萨
- Karana store for ketchupKarana番茄酱店
- And Fragrance For Room to create an ambiance worth enjoying和芬芳的客房营造出值得享受的氛围
因此,如果必须使用REST API:(So if REST API has to be used :)
As these three items are to be sourced from three different sources, In Rest we will have to make three different REST API calls
由于这三个项目将来自三个不同的来源,因此在Rest中,我们将不得不进行三个不同的REST API调用
Fig 1.0 图1.0GraphQL:单个端点,需要单个API调用: (GraphQL: Single End Point, Single API call is required:)
In GraphQL, you just need to make one API call with a single endpoint, called GraphQL. Here the GraphQL endpoint is like your Google assistant, to whom you have passed the location and items info with the single API call, rest is taken care by that assistant to help you serve your appetite needs,
在GraphQL中,您只需要使用一个称为GraphQL的端点进行一个API调用。 这里的GraphQL端点就像您的Google助手一样,您已经通过一个API调用将位置和商品信息传递给了它,该助手会照顾您的休息时间以帮助您满足食欲,
Fig 2.0 图2.0This personal assistant has its own structured language to talk to all the server resources which we call A Query language.
该个人助理具有自己的结构化语言,可与我们称为查询语言的所有服务器资源进行对话。
为什么选择GraphQL? (Why GraphQL?)
- With GraphQL, you can be very specific to your need. 使用GraphQL,您可以非常满足您的需求。
You Ask & You Get What You Really Need
您问与得到您真正需要的
- With It, you always get the predictable results有了它,您始终可以获得可预测的结果
- Sigle endpoint is all you need to source multiple resources.您可以通过Sigle端点来获取多种资源。
As per the official graphQL site:
根据官方图QL网站:
While typical REST APIs require loading from multiple URLs, GraphQL APIs get all the data your app needs in a single request. Apps using GraphQL can be quick even on slow mobile network connections.
虽然典型的REST API需要从多个URL进行加载,但是GraphQL API可以在单个请求中获取应用程序需要的所有数据。 即使在缓慢的移动网络连接下,使用GraphQL的应用程序也可以快速运行。
- Frontend apps, using GraphQL are fast and stable because they control the data they get, not the server. 使用GraphQL的前端应用程序快速且稳定,因为它们控制获取的数据而不是服务器。
- Unlike REST API, where you ave multiple operation types, GET, POST, DELETE, PATCH, in GraphQL you just need a POST method which queries only a single endpoint. 与REST API不同,在REST API中,您拥有多种操作类型(GET,POST,DELETE,PATCH),而在GraphQL中,您只需要一种POST方法即可,该方法仅查询单个端点。
- In GraphQL One can make changes to the existing API to help it evolve without versioning. 在GraphQL中,可以对现有API进行更改以帮助其发展而无需版本控制。
- Unlike REST, by allowing you to define a schema, GraphQL gives you a lot of benefits, like automatic validation and introspection. 与REST不同,GraphQL通过允许您定义架构,为您带来了很多好处,例如自动验证和自省。
One can add new fields and types to their GraphQL API without impacting many of their existing queries. Aging fields can be deprecated and hidden from tools. By using a single evolving version
可以在不影响其许多现有查询的情况下,向其GraphQL API添加新的字段和类型。 可以不使用老化字段,并且可以从工具中隐藏它们。 通过使用一个不断发展的版本
As per graphql website:
根据graphql网站:
GraphQL APIs give apps continuous access to new features and encourage cleaner, more maintainable server code.
GraphQL API使应用程序可以连续访问新功能,并鼓励使用更干净,更可维护的服务器代码。
GraphQL的关键组件是什么? (What Are The Key Components Of GraphQL?)
Here are some of the key the Server Side Components, where GraphQL exists as an endpoint.
这是一些服务器端组件的关键,其中GraphQL作为端点存在。
Queries
查询
Schemas and Types
模式和类型
resolver
解析器
查询:(Queries:)
The request one makes to the GraphQL endpoint happens in the form of the query structure.
对GraphQL端点的请求以查询结构的形式发生。
A GraphQL query is a request coming from the application to fetch data from database or legacy APIs.
GraphQL查询是来自应用程序的请求,用于从数据库或旧版API中获取数据。
For the example, in Fig2.0 the query will look like
对于该示例,在图2.0中,查询看起来像
query { graphql { pizza saltednuts Fragrance }}
So a query in GraphQL comprises documents and underlying operations like mutation, a subscription that is understood well by a GraphQL execution engine.
因此,GraphQL中的查询包括文档和诸如变异的基础操作,这种订阅是GraphQL执行引擎很好理解的。
架构: (Schema:)
For any GraphQL server-side implementation, Scheme plays a crucial role in describing the functionality available for front-end clients that connect to it.
对于任何GraphQL服务器端实现,Scheme在描述可用于连接到它的前端客户端的功能时都起着至关重要的作用。
The most basic components of a GraphQL schema are object types, which just represent a kind of object you can fetch from your service, and what fields it has.
GraphQL模式的最基本组成部分是对象类型,它们仅表示您可以从服务中获取的一种对象以及它具有的字段。
In the GraphQL schema language, we can represent them as shown below
在GraphQL模式语言中,我们可以如下所示表示它们
Example :
范例:
type Query {
welcome:String
students:[Student]
}
type Student {
id:ID!
firstName:String
lastName:String
class:String
enrollId:String
}
The root of the schema here is the Query type. The query has two fields − welcome string and Student array that returns String and a list of students respectively. Students here GraphQL Object type since it contains multiple fields. The ID field is declared as non-nullable.
模式的根在这里是查询类型。 该查询具有两个字段-Welcome String和Student数组,分别返回String和学生列表。 这里的学生GraphQL对象类型,因为它包含多个字段。 ID字段声明为不可为空。
解析器: (Resolver:)
Your GraphQL endpoint has to be told, where to find the requested data or fetch the data from. Resolver facilitates this knowhow to the GraphQL endpoint. Resolver comprises of the method responsible to generate a response for a GraphQL query. Every resolver method in a GraphQL schema looks like
必须告知您的GraphQL端点,从哪里可以找到所请求的数据或从中获取数据。 解析器有助于GraphQL终结点的专有技术。 解析程序包括负责为GraphQL查询生成响应的方法。 GraphQL模式中的每个解析器方法如下
A resolver tells GraphQL how and where to retrieve the data w.r.t to a given field.
解析器告诉GraphQL如何以及在何处检索给定字段的数据。
fieldName:(root, args, context, info) => { result }
The key concept to understand here is that with GraphQL, your API schema and your database schemas are decoupled.
在这里要理解的关键概念是,使用GraphQL, API模式和数据库模式是分离的。
One can write a custom code within the resolver method, which can also help us to make any desired modification of the database content. This kind of process executed by any resolver is known to be they’re known as mutation resolvers.
可以在resolver方法中编写自定义代码,这也可以帮助我们对数据库内容进行任何所需的修改。 任何解析器执行的这种过程都称为变异解析器。
REST API与GraphQL: (REST API Vs GraphQL :)
Before we dig deeper into comparing these two API paradigms, let’s see what are some of the commonality between these two :
在深入比较这两种API范例之前,让我们看一下这两种API之间的共同点是什么:
相似度: (Similarity :)
- They both are the standard specifications to develop and consumer API’s 它们都是开发和消费者API的标准规范
- They both use Http, protocol.它们都使用Http协议。
- Both Exchanges the JSON data 两者都交换JSON数据
- Any server-side languages or any front-end framework works perfectly with both. Like you can use node, PHP, Python, Springboot, etc to write your web services and this service can be consumed by any front-end mobile application or web application irrespective of which language or framework that application is built with. 任何服务器端语言或任何前端框架都可以完美地与这两者一起使用。 就像您可以使用节点,PHP,Python,Springboot等来编写您的Web服务一样,任何前端移动应用程序或Web应用程序都可以使用此服务,而不管该应用程序使用哪种语言或框架。
- REST & GraphQL both supports statelessness. REST和GraphQL都支持无状态。
GraphQL和REST API之间的区别: (Differences Between GraphQL & REST API:)
- GraphQL only supports the POST method while REST support GET, POST, DELETE, PATCH, etc. GraphQL仅支持POST方法,而REST支持GET,POST,DELETE,PATCH等。
- Unlike REST, GraphQL returns result only in JSON representation 与REST不同,GraphQL仅以JSON表示形式返回结果
In the case of data retrieval from the server: Unlike GraphQL, REST API can end up making requests to multiple endpoints, whereas, GraphQL, only has a single endpoint with which one has to access at the time data fetching on a server.
在从服务器检索数据的情况下:与GraphQL不同,REST API最终可能会向多个端点发出请求,而GraphQL仅具有一个端点,在服务器上获取数据时必须使用该端点进行访问。
例如 : (For Example :)
In REST:
在REST中:
/students/:id, can be one api format to fetch a student
/ students /:id,可以是一种api格式 吸引学生
/students/:id, can be one api format to fetch a student - /student/:id/siblings, can be another API endpoint to fetch the siblings of the given student
/ students /:id,可以是一种api格式 获取学生-/ student /:id / siblings ,可以是另一个API端点来获取给定学生的同胞
但是在GraphQL中:(But in GraphQL :)
You just need to make a single call to the single GraphQL endpoint, which will be like /graphql
with the following query:
您只需要对单个GraphQL端点进行一次调用,将类似于/graphql
并带有以下查询:
{
student {
name: string
siblings {
name: string
class: string
}
}
}
The case of an extra parameter: Over & Under Data Retrieval
额外参数的情况:Over&Under数据检索
While using REST API, if the schema is not well planned or due to unavoidable context, you may end up fetching the parameters in the response which may even be not required at the client-side interface. But this can be easily handled with GraphQL It gives you the power to get the desired result by being selective at the time of asking from the server.
在使用REST API时,如果架构规划不当或由于不可避免的上下文所致,您可能最终会在响应中获取参数,而客户端接口甚至可能不需要这些参数。 但这可以通过GraphQL轻松处理。它通过在向服务器询问时进行选择,使您能够获得所需的结果。
Having said that it is important to notice that :
话虽如此,重要的是要注意:
If one is pretty clear of what is the client-side requirement, one can with the use of HTTP2 can design REST API in such a way that there will be little to no over-fetching and zero impact on the performance.
如果完全清楚客户端的要求是什么,则可以使用HTTP2来设计REST API,这样几乎不会发生过度获取,并且对性能的影响为零。
Server-Side Caching: The Case Of State Management
服务器端缓存:状态管理的情况
In graphQL server and client, the app is generally coupled, when client-side coding is being done, the state of the application is not controlled by the server. Unlike REST, GraphQL has no caching mechanism in place, hence leaving the clients with the responsibility of taking care of caching on their front-end.
在graphQL服务器和客户端中,应用通常是耦合的,当客户端编码完成时,应用的状态不受服务器控制。 与REST不同,GraphQL没有适当的缓存机制,因此,客户有责任照顾前端的缓存。
GraphQL的缺点:GraphQL是明显的赢家吗? (Cons Of GraphQL: IS GraphQL The Clear Winner?)
Is everything Rossy about GraphQL, no not at all, it would be an extreme exaggeration if one claimes that. It is imperative to understand that it boils down to the use case of the developer or an organization. if they are looking for a backend system where they require a structured and disciplined approach and if the API developer has mastered this skill-set to support it, REST can always do what GraphQL do.
一切都罗西约GraphQL,无不是的话,那将是一个极端的夸张,如果一个claimes这一点。 必须将其归结为开发人员或组织的用例。 如果他们正在寻找需要结构化和规范化方法的后端系统,并且API开发人员已经掌握了支持该技能的技能,则REST可以始终执行GraphQL的工作。
If the application is very complex and any interface of the application requires loads of data to be fetched at one go, to avoid many network calls, GraphQL can be the way out, but if one simply wants to separate the data retrieval concern they can break the same into multiple API’s Using REST and can have better control over what they need if making multiple API call is not an issue for them.
如果应用程序非常复杂,并且应用程序的任何接口都需要一次性获取大量数据,那么可以避免GraphQL,这是避免麻烦的方法,但是如果只是想分离数据检索问题,它们可能会中断。多个API的“使用REST”中也是如此,如果对他们来说不存在多个API调用,则可以更好地控制它们所需的内容。
So here the question of which one is better than the other is not very relevant, just finalize what you want? How much you want? What is the tradeoff between speed, consistency, and discipline? And then architect your system requirements accordingly.
所以在这里,哪个比另一个更好的问题不是很相关,只是确定您想要什么? 你要多少? 速度,一致性和纪律性之间的权衡是什么? 然后相应地设计系统需求。
GraphQL有其自身的局限性和约束 (GraphQL has it’s own limitations and constraints)
- Not suitable if one needs to handle the response in the format other than JSON如果需要以JSON以外的格式处理响应,则不适合
- Not very well suited to tackle the issues of the distributed system不太适合解决分布式系统的问题
- When it comes to scalable architecture like microservices, the REST Paradigm is pretty well suited, GraphQL may struggle here.当涉及微服务之类的可扩展架构时,REST Paradigm非常适合,GraphQL可能会在这里遇到困难。
Error Handling: Unlike REST Error handling is not very intuitive and straightforward. Depending on the HTTP status code like 404, 503, 500, we can easily tell what are those errors signifying, while in GraphQL, when operated over HTTP, we will always get a
200 OK
response status. When an error occurs while processing GraphQL queries, the complete error message is sent to the client with the response.错误处理:与REST不同,错误处理不是很直观和直接。 根据404、503、500之类的HTTP状态代码,我们可以轻松地分辨出这些错误表示什么,而在GraphQL中,当通过HTTP操作时,我们将始终获得
200 OK
响应状态。 在处理GraphQL查询时发生错误时,完整的错误消息将与响应一起发送到客户端。In a simple application, GraphQL is not very intuitive to use. It complicates the stuff due to the requirement to handle - Types, Queries, Mutators Resolvers, High-order components. which may not be easy to manage when it comes to maintainability
在一个简单的应用程序中,GraphQL的使用不是很直观。 由于需要处理,它使内容变得复杂-类型,查询,Mutators解析器,高阶组件。 就可维护性而言,这可能不容易管理
- It’s easier to use cache management at web side with REST as compared to GraphQL与GraphQL相比,通过REST在Web端使用缓存管理更加容易
谁都在使用GraphQL?(Who all are using GraphQL?)
根据graphql网站: (As per graphql site :)
Almost more than 90 big to mid-level companies are already taking the benefit of GraphQL
几乎90多家大中型公司已经在利用GraphQL
Airbnb
爱彼迎
Facebook
脸书
Intuit
直觉
Coursera
Coursera
Shopify
Shopify
twitter
推特
Starbucks
星巴克
Rakuten
乐天
are some of the big-name who has been an early adopter of GraphQL
是GraphQL的早期采用者中的一些知名人士
Please visit on GraphQL to know more :
请访问GraphQL以了解更多信息:
https://graphql.org/users/
https://graphql.org/users/
下一步是什么? (What’s Next?)
Hands-on use case of GrpahQL and transforming REST API into GraphQL structure. We will also do some performance benchmarking in the series of Web services.
动手使用GrpahQL的用例,并将REST API转换为GraphQL结构。 我们还将在一系列Web服务中进行一些性能基准测试。
Till then, stay tuned and keep learning. Anyone looking to contribute there, please reach out and I will be happy to add you as a writer on Life Learning publication, which I have just started to help learners out there
直到那时,请继续关注并继续学习。 任何希望在此做出贡献的人,请与我们联系。我很乐意将您添加为“生活学习”出版物的作家,我刚刚开始帮助那里的学习者
Thanks a lot…..
非常感谢…..
翻译自: https://medium.com/the-programmer/rest-api-vs-graphql-fetch-what-you-want-a7c96c446dbf
graphql和rest