---
url: 'https://www.redhat.com/topics/api/what-is-graphql'
title: '一文看懂 GraphQL 是什么？都有哪些优缺点 - 红帽'
date: '2024-11-20T22:53:14+00:00'
updated: '2026-10-22T16:53:25+00:00'
type: website
summary: 'GraphQL 是一种用于应用编程接口（API）的查询语言和服务器端运行时，作为 REST 的替代方案，它可以使客户端准确地获得所需的数据，没有任何冗余。让 API 变得快速、灵活并且为开发人员提供便利。'
tags:
  - Article
  - Integration
  - 集成
image: 'https://www.redhat.com/profiles/rh/themes/redhatdotcom/img/logo-rh-og-image.png'
published: true
---
  

  

1. [主题](/zh-cn/topics "主题")
2. [集成](/zh-cn/topics/integration "集成")
3. [入门指南：什么是 GraphQL？](# "入门指南：什么是 GraphQL？")

 

 

# 入门指南：什么是 GraphQL？





 Published  2024 年 1 月 17 日•*9* 分钟阅读

已复制复制失败复制 URL





 

 

 

   

## 快速跳转

GraphQL 是什么？常见术语使用 GraphQL 的优缺点GraphQL 与开源

 

 

## GraphQL 是什么？



GraphQL 是一种用于[应用编程接口（API）](/zh-cn/topics/api/what-are-application-programming-interfaces)的查询语言和服务器端运行时，它可以使客户端准确地获得所需的数据，没有任何冗余。

## GraphQL有什么用？

GraphQL 旨在让 API 变得快速、灵活并且为开发人员提供便利。它甚至可以部署在名为 [GraphiQL](https://github.com/graphql/graphiql) 的[集成开发环境（IDE）](/zh-cn/topics/platform-engineering/what-is-ide)中。作为 [REST](/zh-cn/topics/integration/whats-the-difference-between-soap-rest) 的替代方案，GraphQL 允许开发人员构建相应的请求，从而通过单个 API 调用从多个数据源中提取数据。

此外，GraphQL 还可让 API 维护人员灵活地添加或弃用字段，而不会影响现有查询。开发人员可以使用自己喜欢的方法来构建 API，并且 GraphQL 规范将确保它们以可预测的方式在客户端发挥作用。

[有效 API 管理的 7 大关键](/zh-cn/resources/api-owners-manual-ebook "API 使用手册")





 

## 模式、解析器及其他常见的 GraphQL 术语



API 开发人员使用 GraphQL 创建一个**模式**，用于描述客户端可通过该服务查询的所有可能数据。

GraphQL 模式由对象类型组成，它表示可以请求哪种对象以及它有哪些字段。

有**查询**时，GraphQL 会根据模式对查询进行验证。随后，GraphQL 将执行经过验证的查询。

API 开发人员将模式中的每个字段附加到名为**解析器**的函数中。执行期间，系统将调用解析器来生成相应的值。

除了为 API 查询定义和验证语法外（有关概述见 [graphql-spec](https://github.com/graphql/graphql-spec) 存储库），GraphQL 把大部分决策权都留给了 API 设计人员。GraphQL 不提供有关如何存储数据或使用哪种编程语言的任何指导；开发人员可以使用PHP（[graphql-php](https://github.com/webonyx/graphql-php)）、Scala（Sangria）、Python（[Graphene Python](https://graphene-python.org/)）、Ruby（[graphql-ruby](https://github.com/rmosolgo/graphql-ruby)）、JavaScript（[graphql.js](https://www.npmjs.com/package/graphql)）等等。GraphQL 对网络、授权或分页没有任何要求。

从客户端的角度看，最常见的 GraphQL 操作可能就是**查询**和**修改**。如果按照*创建、读取、更新和删除*（CRUD）模型来审视这些操作，那么查询就等同于*读取*。其他所有操作（*创建、更新*和*删除*）均视为修改。







 

## 红帽资源











[扩展阅读](/zh-cn/resources "扩展阅读")







 

   

## 企业环境中使用 GraphQL 的优缺点 



想在业务或企业环境中试用 GraphQL？这样做既有优点，也有缺点。

### GraphQL 的优点

- GraphQL 模式会在 GraphQL 应用中设置单一事实来源。它为企业提供了一种整合其整个 API 的方法。
- 一次往返通讯可以处理多个 GraphQL 调用。客户端可得到自己所请求的内容，不会超量。
- 严格定义的数据类型可减少客户端与服务器之间的通信错误。
- GraphQL 具有自检功能。客户端可以请求一个可用数据类型的列表。这非常适合文档的自动生成。
- GraphQL 允许应用 API 进行更新优化，而无需破坏现有查询。
- 许多开源 GraphQL 扩展可提供 REST API 所不具备的功能。
- GraphQL 不指定特定的[应用架构](/zh-cn/topics/cloud-native-apps/what-is-an-application-architecture)。它能够以现有的 REST API 为基础，并与现有的 [API 管理](/zh-cn/topics/api/what-is-api-management)工具配合使用。

### GraphQL 的缺点

- 即便是熟悉 REST API 的开发人员，也需要一定时间才能掌握 GraphQL。
- GraphQL 将数据查询的大部分工作都转移到服务器端，由此增加了服务器开发人员工作的复杂度。
- 根据不同的实施方式，GraphQL 可能需要不同于 REST API 的 API 管理策略，尤其是在考虑速率限制和定价的情况下。
- 缓存机制比 REST 更加复杂。
- API 维护人员还会面临编写可维护 GraphQL 模式的额外任务。

---

### GraphQL 查询示例

想要更好地了解 GraphQL，最好的办法就是看一些查询和响应的示例。我们来看看来自 GraphQL 项目网站 [graphql.org](http://graphql.org/) 的 3 个示例。

第一个示例显示了客户端如何构建 GraphQL 查询，从而要求 API 以指定的形态返回特定字段。

```
{
  me {
    name
  }
}
```

GraphQL API 将以 JSON 格式返回如下结果：

```
{
  "me": {
    "name": "Dorothy"
  }
}
```

客户端也可以作为 GraphQL 查询的一部分来传递参数，如下例所示：

```
{
  human(id: "1000") {
    name
    location
  }
}
```

结果为：

```
{
  "data": {
    "human": {
      "name": "Dorothy,
      "location": "Kansas"
    }
  }
}
```

从这里开始，事情变得更加有趣。GraphQL 允许用户定义可复用的片段并分配变量。

假设您需要请求一个 ID 列表，然后为每个 ID 请求一系列记录。借助 GraphQL，您可以构建一个查询，然后通过单个 API 调用来提取所需的所有内容。

查询方式如下：

```
query HeroComparison($first: Int = 3) {
  leftComparison: hero(location: KANSAS) {
    ...comparisonFields
  }
  rightComparison: hero(location: OZ) {
    ...comparisonFields
  }
}
fragment comparisonFields on Character {
  name
  friendsConnection(first: $first) {
    totalCount
    edges {
      node {
        name
      }
    }
  }
}
```

  
可能生成以下结果：

```
{
  "data": {
    "leftComparison": {
      "name": "Dorothy",
      "friendsConnection": {
        "totalCount": 4,
        "edges": [
          {
            "node": {
              "name": "Aunt Em"
            }
          },
          {
            "node": {
              "name": "Uncle Henry"
            }
          },
          {
            "node": {
              "name": "Toto"
            }
          }
        ]
      }
    },
    "rightComparison": {
      "name": "Wizard",
      "friendsConnection": {
        "totalCount": 3,
        "edges": [
          {
            "node": {
              "name": "Scarecrow"
            }
          },
          {
            "node": {
              "name": "Tin Man"
            }
          },
          {
            "node": {
              "name": "Lion"
            }
          }
        ]
      }
    }
  }
}
```

如果您是 GitHub 用户，那么使用 [GitHub 的 GraphQL Explorer](https://developer.github.com/v4/explorer/) 就能快速上手 GraphQL。







 

## GraphQL 与开源



GraphQL 由 Facebook 开发，并于 2012 年首次应用于移动应用。GraphQL 规范于 2015 年实现开源。现在，它受 [GraphQL 基金会](https://foundation.graphql.org/)监管。

有大量开源项目都涉及 GraphQL。下面的列表虽不详尽，但大致涵盖了一些旨在促进 GraphQL 普及的项目。

- [Apollo](https://www.apollographql.com/)：一个包含前端客户端库（Apollo 客户端）和后端服务器框架（Apollo 服务器）的 GraphQL 平台。
- [Offix](https://offix.dev/)：一个离线客户端，即使在无法访问应用的情况下也允许执行 GraphQL 修改与查询。
- [Graphback](https://graphback.dev/)：一个用于生成支持 GraphQL 的 Node.js 服务器的命令行客户端。
- [OpenAPI-to-GraphQL](https://github.com/IBM/openapi-to-graphql)：一个用于将 OpenAPI 规范或 Swagger 所描述的 API 转换为 GraphQL 的命令行界面和库。







 

 

   











### 红帽官方博客



获取有关我们的客户、合作伙伴和社区生态系统的最新信息。











[扩展阅读](/zh-cn/blog "红帽官方博客")







   

 

 

   

### 所有红帽产品试用

我们的免费试用服务可让您亲身体验红帽的产品功能，为获得认证做好准备，或评估某个产品是否适合您的企业组织。



 

    

[扩展阅读](/zh-cn/products/trials "所有红帽产品试用") 

 

 

 

 



 

   

## 扩展阅读



  











### 什么是独立软件供应商（ISV）？



 ISV 合作伙伴，即提供各种软件和/或 SaaS 解决方案，旨在解决客户需求的独立软件供应商。 









[阅读文章](/zh-cn/topics/digital-transformation/isv-partners "article | what is an ISV?")





 

  











### 什么是应用集成？



 应用集成可将不同的系统和应用连接起来，使它们可通过交换数据和使用服务进行协作。 









[阅读文章](/zh-cn/topics/cloud-native-apps/application-integration "article | What is application integration")





 

  











### 什么是 API？



 API 是应用编程接口的缩写，它是指用于构建和集成应用软件的一组定义和协议。 









[阅读文章](/zh-cn/topics/api/what-are-application-programming-interfaces "article | what are APIs? &#91;DO NOT OVERWRITE ZH META&#93;")





 

 

 

   

### 集成 相关资源



 

### 相关内容

 

 

- 博客文章
    
     [Beyond the horizon: Navigating the bridge between today's tech and tomorrow's AI](/zh-cn/blog/beyond-horizon-navigating-bridge-between-todays-tech-and-tomorrows-ai)
- 产品规格表
    
     [Red Hat Application Foundations](/zh-cn/resources/application-foundations-datasheet)
- 案例研究
    
     [Volkswagen builds virtual test environment with Red Hat OpenShift](/zh-cn/resources/volkswagen-group-case-study)
- 成功案例
    
     [Red Hat helps Argentine government expand digital services](/zh-cn/success-stories/secretaria-de-innovacion-argentina-del-sector-publico)
 
 

 

 

 

 

### 相关文章

 

 

- [What is an independent software vendor (ISV)?](/zh-cn/topics/digital-transformation/isv-partners)
- [What is application integration?](/zh-cn/topics/cloud-native-apps/application-integration)
- [What is an API?](/zh-cn/topics/api/what-are-application-programming-interfaces)
- [What is a REST API?](/zh-cn/topics/api/what-is-a-rest-api)
- [What is middleware?](/zh-cn/topics/middleware/what-is-middleware)
- [What is Apache Kafka?](/zh-cn/topics/integration/what-is-apache-kafka)
- [Why choose Red Hat for middleware?](/zh-cn/topics/middleware/why-choose-red-hat-middleware)
- [Red Hat OpenShift application services](/zh-cn/technologies/cloud-computing/openshift/application-services)
- [What is a Kafka service?](/zh-cn/topics/integration/what-is-a-kafka-service)
- [What is streaming data?](/zh-cn/topics/integration/what-is-streaming-data)
- [Do banking APIs benefit from cloud technology?](/zh-cn/topics/api/banking-api)
- [What is a service registry?](/zh-cn/topics/integration/what-is-a-service-registry)
- [What is an event mesh?](/zh-cn/topics/integration/what-is-an-event-mesh)
- [How microservices support IT integration in healthcare](/zh-cn/topics/microservices/microservices-in-healthcare)
- [What is change data capture?](/zh-cn/topics/integration/what-is-change-data-capture)
- [Why Red Hat for APIs?](/zh-cn/topics/api/why-choose-red-hat-apis)
- [What is service-oriented architecture?](/zh-cn/topics/cloud-native-apps/what-is-service-oriented-architecture)
- [What is the Kubernetes API?](/zh-cn/topics/containers/what-is-the-kubernetes-api)
- [What is event-driven architecture?](/zh-cn/topics/integration/what-is-event-driven-architecture)
- [What is API monetization?](/zh-cn/topics/api/what-is-api-monetization)
- [REST vs. SOAP](/zh-cn/topics/integration/whats-the-difference-between-soap-rest)
- [Why choose Red Hat for integration?](/zh-cn/topics/integration/why-choose-red-hat-integration)
- [What does an API gateway do?](/zh-cn/topics/api/what-does-an-api-gateway-do)
- [What is API design?](/zh-cn/topics/api/what-is-api-design)
- [What is API management?](/zh-cn/topics/api/what-is-api-management)
- [What is API security?](/zh-cn/topics/security/api-security)
- [What is a service mesh?](/zh-cn/topics/microservices/what-is-a-service-mesh)
- [What is integration?](/zh-cn/topics/integration/what-is-integration)
 
 

 

   

[有关此主题的更多信息](/zh-cn/topics/integration "有关此主题的更多信息")