GraphQL Cheatsheet - GraphQL Query Language & API Reference

GraphQL API 设计必备语法都在这里了,从查询定义到 Schema 类型系统,按类别分类整理,写代码时直接复制。

Languages·42 commands·Last updated 2026-07-21
Back to Languages

查询 Query 9

{ user { id name } }
基础查询
{ user(id: 1) { name } }
带参数查询
{ users { id name posts { title } } }
嵌套查询
query GetUser($id: ID!) { user(id: $id) { name } }
带变量的查询
{ user { name email } posts { title } }
多字段查询
{ user(id: 1) { name @include(if: $withName) } }
条件包含字段
{ user(id: 1) { name @skip(if: $skipName) } }
条件跳过字段
{ me: user(id: 1) { name } you: user(id: 2) { name } }
别名查询同类型多字段
{ users(first: 10) { edges { node { name } } } }
连接式分页查询

变更 Mutation 5

mutation { createUser(name: "Alice") { id } }
基础变更
mutation CreateUser($input: CreateUserInput!) { createUser(input: $input) { id } }
带变量的变更
mutation { updateUser(id: 1, name: "Bob") { id name } }
更新操作
mutation { deleteUser(id: 1) { id } }
删除操作
mutation { bulkCreate(input: [{ name: "A" }, { name: "B" }]) { id } }
批量创建操作

订阅 Subscription 3

subscription { newMessage { content } }
订阅新消息
subscription { userUpdated(id: 1) { name } }
订阅用户更新
subscription($roomId: ID!) { messageAdded(roomId: $roomId) { id content } }
带变量的订阅

类型系统 Schema 10

type User { id: ID! name: String! email: String }
定义对象类型
input CreateUserInput { name: String! email: String! }
定义输入类型
enum Role { ADMIN USER GUEST }
定义枚举
union SearchResult = User | Post
定义联合类型
interface Node { id: ID! }
定义接口
type User implements Node { id: ID! name: String! }
实现接口
scalar DateTime
自定义标量类型
type Query { user(id: ID!): User }
定义查询根
type Mutation { createUser(input: CreateUserInput!): User }
定义变更根
directive @auth(requires: Role!) on FIELD_DEFINITION
自定义指令声明

片段与指令 5

fragment UserFields on User { id name email }
定义片段
{ user { ...UserFields } }
使用片段
{ user { ...UserFields ... on Admin { permissions } } }
内联片段处理联合类型
@deprecated(reason: "Use newField")
标记字段废弃
@cacheControl(maxAge: 3600)
缓存指令

内省与验证 Introspection 5

{ __schema { types { name } } }
查询所有类型
{ __type(name: "User") { fields { name type { name } } } }
查询单个类型字段
{ __schema { queryType { name } mutationType { name } } }
查询根类型
{ __type(name: "User") { fields { name args { name type { name } } } } }
查询字段参数
{ __schema { directives { name locations } } }
查询所有指令

高级特性 5

query($id: ID!, $withPosts: Boolean!) { user(id: $id) { name posts @include(if: $withPosts) { title } } }
变量与指令组合
{ users(first: 10, after: "cursor") { pageInfo { hasNextPage endCursor } } }
Relay 风格分页
{ user { name } } # 期望 user.name,错误会被聚合返回
错误与数据同时返回
query @cost(complexity: 10) { user { name } }
查询复杂度指令
extend type User { age: Int }
扩展已有类型(类型扩展)

💡 Tips

  • GraphQL 查询返回的字段由客户端决定,服务端不需要返回所有字段。
  • 变量用 $ 前缀,在查询外部定义,避免字符串拼接。
  • Schema 定义语言(SDL)是 GraphQL 的核心,先定义类型再实现解析器。
  • 内省查询(__schema/__type)可用于生成 TypeScript 类型与代码提示工具。
  • 分页推荐采用 Relay 连接规范(edges/node/pageInfo),兼顾向前与向后翻页。