Skip to main content

GraphQL API

☑️ Prerequisites

要使用 GraphQL API,请安装 GraphQL 插件。

¥To use the GraphQL API, install the GraphQL plugin.

GraphQL API 允许执行查询和突变,以通过 Strapi 的 GraphQL 插件content-types 进行交互。结果可以是 filteredsortedpaginated

¥The GraphQL API allows performing queries and mutations to interact with the content-types through Strapi's GraphQL plugin. Results can be filtered, sorted and paginated.

统一响应格式

¥Unified response format

响应与 GraphQL API 是统一的,因为:

¥Responses are unified with the GraphQL API in that:

  • 返回单个条目信息的查询和突变主要使用 XxxEntityResponse 类型

    ¥queries and mutations that return information for a single entry mainly use a XxxEntityResponse type

  • 为多个条目返回 i️信息的查询和突变主要使用 XxxEntityResponseCollection 类型,其中除了数据本身之外还包括 meta 信息(带有 pagination

    ¥queries and mutations that return i️nformation for multiple entries mainly use a XxxEntityResponseCollection type, which includes meta information (with pagination) in addition to the data itself

响应还可以包括 error(参见 错误处理文档)。

¥Responses can also include an error (see error handling documentation).

Example: Response formats for queries and mutations with an example 'Article' content-type
type ArticleEntityResponse {
data: ArticleEntity
}

type ArticleEntityResponseCollection {
data: [ArticleEntityResponse!]!
meta: ResponseCollectionMeta!
}

query {
article(...): ArticleEntityResponse # find one
articles(...): ArticleEntityResponseCollection # find many
}

mutation {
createArticle(...): ArticleEntityResponse # create
updateArticle(...): ArticleEntityResponse # update
deleteArticle(...): ArticleEntityResponse # delete
}

查询

¥Queries

GraphQL 中的查询用于获取数据而不修改数据。

¥Queries in GraphQL are used to fetch data without modifying it.

我们假设 影子增删改查 功能已启用。对于每个模型,GraphQL 插件都会自动生成模仿基本 CRUD 操作(findMany、findOne、创建、更新、删除)的查询和突变。

¥We assume that the Shadow CRUD feature is enabled. For each model, the GraphQL plugin auto-generates queries and mutations that mimics basic CRUD operations (findMany, findOne, create, update, delete).

获取单个条目

¥Fetch a single entry

单个条目可以通过其 id 找到。

¥Single entries can be found by their id.

Example query: Find the entry with id 1
query {
document(id: 1) {
data {
id
attributes {
title
categories {
data {
id
attributes {
name
}
}
}
}
}
}
}

获取多个条目

¥Fetch multiple entries

Example query: Find all documents and populate 'categories' relation with the 'name' attribute
query {
documents {
data {
id
attributes {
title
categories {
data {
id
attributes {
name
}
}
}
}
}
meta {
pagination {
page
pageSize
total
pageCount
}
}
}
}

获取动态区域数据

¥Fetch dynamic zone data

动态区域是 graphql 中的联合类型,因此需要使用片段来查询字段。

¥Dynamic zones are union types in graphql so you need to use fragments to query the fields.

query {
restaurants {
data {
attributes {
dynamiczone {
__typename
...on ComponentDefaultClosingperiod {
label
}
}
}
}
}
}

突变

¥Mutations

GraphQL 中的突变用于修改数据(例如创建、更新、删除数据)。

¥Mutations in GraphQL are used to modify data (e.g. create, update, delete data).

创建一个新条目

¥Create a new entry

mutation createArticle {
createArticle(data: { title: "Hello"}) {
data {
id
attributes {
title
}
}
}
}

突变的实现还支持关系属性。例如,你可以创建一个新的 User 并将许多 Restaurant 附加到它,方法如下编写查询:

¥The implementation of the mutations also supports relational attributes. For example, you can create a new User and attach many Restaurant to it by writing your query like this:

mutation {
createUser(
data: {
username: "John"
email: "john@doe.com"
restaurants: ["1", "2"]
}
) {
data {
id
attributes {
username
email
restaurants {
data {
id
attributes {
name
description
price
}
}
}
}
}
}
}

更新现有条目

¥Update an existing entry

mutation updateArticle {
updateArticle(id: "1", data: { title: "Hello" }) {
data {
id
attributes {
title
}
}
}
}

你还可以通过传递 ID 或 ID 数组(取决于关系)来更新关系属性。

¥You can also update relational attributes by passing an ID or an array of IDs (depending on the relationship).

mutation {
updateRestaurant(
id: "5b5b27f8164f75c29c728110"
data: {
chef: "1" // User ID
}
}) {
data {
id
attributes {
chef {
data {
attributes {
username
email
}
}
}
}
}
}
}

删除条目

¥Delete an entry

mutation deleteArticle {
deleteArticle(id: 1) {
data {
id
attributes {
title
}
}
}
}

过滤器

¥Filters

查询可以接受具有以下语法的 filters 参数:

¥Queries can accept a filters parameter with the following syntax:

filters: { field: { operator: value } }

也可以使用逻辑运算符(andornot)并接受对象数组。

¥Logical operators (and, or, not) can also be used and accept arrays of objects.

可以使用以下运算符:

¥The following operators are available:

运算符描述
eq平等的
ne不等于
lt少于
lte小于或等于
gt比...更棒
gte大于或等于
in包含在数组中
notIn不包含在数组中
contains包含,区分大小写
notContains不包含,区分大小写
containsi包含,不区分大小写
notContainsi不包含,不区分大小写
null一片空白
notNull不为空
between在。。。之间
startsWith以。。开始
endsWith以。。结束
and逻辑 and
or逻辑 or
not逻辑 not
Example query with filters
{
documents(filters: { name: { eq: "test" }, or: [{ price: { gt: 10 }}, { title: { startsWith: "Book" }}] }) {
data {
id
}
}
}

排序

¥Sorting

查询可以接受具有以下语法的 sort 参数:

¥Queries can accept a sort parameter with the following syntax:

  • 基于单个值排序:sort: "value"

    ¥to sort based on a single value: sort: "value"

  • 根据多个值进行排序:sort: ["value1", "value2"]

    ¥to sort based on multiple values: sort: ["value1", "value2"]

排序顺序可以定义为 :asc(升序,默认,可省略)或 :desc(降序)。

¥The sorting order can be defined with :asc (ascending order, default, can be omitted) or :desc (for descending order).

Example request: Sorting on title by ascending order
{
documents(sort: "title") {
data {
id
}
}
}
Example request: Sorting on title by descending order
{
documents(sort: "title:desc") {
data {
id
}
}
}
Example request: Sorting on title by ascending order, then on price by descending order
{
documents(sort: ["title:asc", "price:desc"]) {
data {
id
}
}
}

分页

¥Pagination

查询可以接受 pagination 参数。结果可以按页或按偏移量分页。

¥Queries can accept a pagination parameter. Results can be paginated either by page or by offset.

✏️ 注意

分页方法不能混合。始终使用 pagepageSizestartlimit

¥Pagination methods can not be mixed. Always use either page with pageSize or start with limit.

按页分页

¥Pagination by page

范围描述默认
pagination[page]页码1
pagination[pageSize]页面大小10
Example query: Pagination by page
{
documents(pagination: { page: 1, pageSize: 10 }) {
data {
id
}
meta {
pagination {
page
pageSize
pageCount
total
}
}
}
}

按偏移量分页

¥Pagination by offset

范围描述默认最大限度
pagination[start]起始值0*
pagination[limit]要返回的实体数量10-1
Example query: Pagination by offset
{
documents(pagination: { start: 20, limit: 30 }) {
data {
id
}
meta {
pagination {
start
limit
}
}
}
}
💡 提示

pagination[limit] 的默认值和最大值可以是带有 graphql.config.defaultLimitgraphql.config.maxLimit 键的 ./config/plugins.js 中配置 文件。

¥The default and maximum values for pagination[limit] can be configured in the ./config/plugins.js file with the graphql.config.defaultLimit and graphql.config.maxLimit keys.