GraphQL API 查询语言

精选 GraphQL 常用指令与核心速查备忘单,涵盖高频用法、配置参数与实用技巧。 本速查备忘单提供了 GraphQL 的简要概览与核心语法速查。

#🚀 入门指引

#概念大纲

  • 一种替代传统 RESTful API 的现代设计标准
  • GraphQL 是一种用于 API 的声明式查询语言 (Query Language)
  • 使用清晰共享的术语定义 GraphQL API Schema 结构
  • 客户端发起 query/mutation 查询或修改数据
  • GraphQL 语法可直接表达复杂的实体关联关系
  • 支持在各种编程语言中实现 GraphQL 服务

#Schema 核心概念

关键字 详细含义与功能说明
schema GraphQL Schema 架构定义
query 读取和遍历数据
mutation 修改数据或触发操作
subscription 事件发生时监听执行查询 (订阅)

#内置标量类型 (Built-in Scalar Types)

类型名称 数据类型说明
Int 带符号的 32 位整型数
Float 带符号的双精度浮点数
String UTF-8 字符序列字符串
Boolean 布尔值 (true 或 false)
ID 唯一标识符对象 (ID)

#类型定义关键字 (Type Definitions)

关键字 含义与类型分类
scalar 自定义标量类型 (Scalar Type)
type 对象类型 (Object Type)
interface 接口类型 (Interface Type)
union 联合类型 (Union Type)
enum 枚举类型 (Enum Type)
input 输入对象类型 (Input Object Type)

#类型修饰符 (Type Modifiers)

语法修饰 详细含义说明
String 可空字符串 (Nullable String)
String! 非空字符串 (Non-null String)
[String] 元素可空的字符串列表 (List of nullable Strings)
[String]! 列表本身不可空,元素可空的列表
[String!]! 列表本身及元素均不可空的字符串列表

#输入参数 (Input Arguments)

基础输入参数 (Basic Input)

type Query {
    users(limit: Int): [User]
}

带默认值的输入参数 (Input with 默认值)

type Query {
    users(limit: Int = 10): [User]
}

多参数输入 (Input with multiple arguments)

type Query {
    users(limit: Int, sort: String): [User]
}

组合多参数与默认值 (Input with multiple arguments and defaults)

type Query {
    users(limit: Int = 10, sort: String): [User]
}
type Query {
    users(limit: Int, sort: String = "asc"): [User]
}
type Query {
    users(limit: Int = 10, sort: String = "asc"): [User]
}

#输入类型 (Input Types)

input ListUsersInput {
    limit: Int
    since_id: ID
}
type Mutation {
    users(params: ListUsersInput): [User]!
}

#自定义标量类型 (Custom Scalars)

scalar Url
type User {
    name: String
    homepage: Url
}

#接口继承 (Interfaces)

interface Foo {
    is_foo: Boolean
}
interface Goo {
    is_goo: Boolean
}
type Bar implements Foo {
    is_foo: Boolean
    is_bar: Boolean
}
type Baz implements Foo, Goo {
    is_foo: Boolean
    is_goo: Boolean
    is_baz: Boolean
}

对象实现一个或多个 Interface 接口

#联合类型 (Unions)

type Foo {
    name: String
}
type Bar {
    is_bar: String
}
union SingleUnion = Foo
union MultipleUnion = Foo | Bar
type Root {
    single: SingleUnion
    multiple: MultipleUnion
}

一个或多个 Object 对象的联合体

#枚举类型

enum USER_STATE {
    NOT_FOUND
    ACTIVE
    INACTIVE
    SUSPENDED
}
type Root {
    stateForUser(userID: ID!): USER_STATE!
    users(state: USER_STATE, limit: Int = 10): [User]
}

#🔗 参考资源