Skip to main content

REST API:人口和字段选择

¥REST API: Population & Field Selection

默认情况下,REST API 不填充任何关系、媒体字段、组件或动态区域。使用 populate 参数 填充特定字段,使用 select 参数 仅返回特定字段和查询结果。

¥The REST API by default does not populate any relations, media fields, components, or dynamic zones. Use the populate parameter to populate specific fields and the select parameter to return only specific fields with the query results.

💡 提示

Strapi 利用 qs 解析嵌套对象的能力来创建更复杂的查询。

¥Strapi takes advantage of the ability of the qs library to parse nested objects to create more complex queries.

直接使用 qs 生成复杂的查询,而不是手动创建它们。本文档中的示例展示了如何使用 qs

¥Use qs directly to generate complex queries instead of creating them manually. Examples in this documentation showcase how you can use qs.

如果你更喜欢使用我们的在线工具而不是在计算机上使用 qs 生成查询,你也可以使用 交互式查询构建器

¥You can also use the interactive query builder if you prefer playing with our online tool instead of generating queries with qs on your machine.

🏗 正在进行的工作

Strapi v4 文档最近包含了有关如何使用 populate 参数的更详细描述,包括 广泛的 API 参考其他指南。这些 v4 页面目前正在移植并适应 Strapi 5 文档,以便示例反映新的数据响应格式。

¥Strapi v4 docs very recently included a more extensive description of how to use the populate parameter, including an extensive API reference and additional guides. These v4 pages are currently being ported and adapted to Strapi 5 docs so that examples reflect the new data response format.

与此同时,你可以相信当前页面的内容是准确的,因为它已经反映了新的 Strapi 5 扁平响应格式(有关详细信息,请参阅 重大变更条目REST API 介绍);当前页面尚未像其 v4 版本那样完整。

¥In the meantime, you can trust the content of the present page as accurate as it already reflects the new Strapi 5, flattened response format (see breaking change entry and REST API introduction for details); the present page is just not as complete as its v4 equivalent yet.

字段选择

¥Field selection

查询可以接受 fields 参数来仅选择某些字段。默认情况下,仅返回以下 字段类型

¥Queries can accept a fields parameter to select only some fields. By default, only the following types of fields are returned:

  • 字符串类型:字符串、文本、富文本、枚举、电子邮件、密码和 uid,

    ¥string types: string, text, richtext, enumeration, email, password, and uid,

  • 日期类型:日期、时间、日期时间和时间戳,

    ¥date types: date, time, datetime, and timestamp,

  • 号码类型:整数、大整数、浮点数和小数,

    ¥number types: integer, biginteger, float, and decimal,

  • 通用类型:布尔值、数组和 JSON。

    ¥generic types: boolean, array, and JSON.

使用案例参数语法示例
选择单个字段fields=name
选择多个字段fields[0]=name&fields[1]=description
✏️ 注意

字段选择不适用于关系、媒体、组件或动态区域字段。要填充这些字段,请使用 populate 参数

¥Field selection does not work on relational, media, component, or dynamic zone fields. To populate these fields, use the populate parameter.

Example request: Return only name and description fields

GET /api/restaurants?fields[0]=name&fields[1]=description

JavaScript 查询(使用 qs 库构建):

¥JavaScript query (built with the qs library):

上面的查询 URL 是使用 qs 构建的。qs 可以在你的计算机上本地运行,如以下代码示例所示,或者你也可以使用我们的 交互式查询构建器 在线工具。

¥The query URL above was built using the qs library. qs can be run locally on your machine, as shown in the following code example, or you can use our interactive query builder online tool.



const qs = require('qs');




const query = qs.stringify(


{
fields: ['name', 'description'],
},
{
encodeValuesOnly: true, // prettify URL
}
);

await request(`/api/users?${query}`);
Example response
{
"data": [
{
"id": 4,
"Name": "Pizzeria Arrivederci",
"Description": [
{
"type": "paragraph",
"children": [
{
"type": "text",
"text": "Specialized in pizza, we invite you to rediscover our classics, such as 4 Formaggi or Calzone, and our original creations such as Do Luigi or Nduja."
}
]
}
],
"documentId": "lr5wju2og49bf820kj9kz8c3"
},
// …
],
"meta": {
"pagination": {
"page": 1,
"pageSize": 25,
"pageCount": 1,
"total": 4
}
}
}

人口

¥Population

默认情况下,REST API 不会填充任何类型的字段,因此它不会填充关系、媒体字段、组件或动态区域,除非你传递 populate 参数来填充各种字段类型。

¥The REST API by default does not populate any type of fields, so it will not populate relations, media fields, components, or dynamic zones unless you pass a populate parameter to populate various field types.

populate 参数可以单独使用,也可以使用 与多个操作符结合 对总体进行更多控制。

¥The populate parameter can be used alone or in combination with with multiple operators to have much more control over the population.

提醒

必须为正在填充的内容类型启用 find 权限。如果角色无权访问内容类型,则不会填充该角色(有关如何为内容类型启用 find 权限的其他信息,请参阅 用户指南)。

¥The find permission must be enabled for the content-types that are being populated. If a role doesn't have access to a content-type it will not be populated (see User Guide for additional information on how to enable find permissions for content-types).

✏️ 注意

目前无法仅通过请求返回 id 数组。

¥It's currently not possible to return just an array of ids with a request.

🤓 填充指南

REST API 指南 部分包含有关填充参数的各种可能用例的更详细信息:

¥The REST API guides section includes more detailed information about various possible use cases for the populate parameter:

  • 了解填充 指南通过图表、比较和实际示例详细解释了填充的工作原理。

    ¥The Understanding populate guide explains in details how populate works, with diagrams, comparisons, and real-world examples.

  • 如何填充创建者字段 指南提供了有关如何将 createdByupdatedBy 字段添加到查询响应中的分步说明。

    ¥The How to populate creator fields guide provides step-by-step instructions on how to add createdBy and updatedBy fields to your queries responses.

下表总结了可能的填充用例及其关联的参数语法,并链接到了解填充指南的各部分,其中包括更详细的说明:

¥The following table sums up possible populate use cases and their associated parameter syntaxes, and links to sections of the Understanding populate guide which includes more detailed explanations:

使用案例参数语法示例详细解释请阅读
填充所有内容,深度为 1 层,包括媒体字段、关系、组件和动态区域populate=*填充所有关系和字段,深 1 层
填充一个关系,
1 层深
populate=a-relation-name为特定关系填充 1 层深度
填充多个关系,
深 1 层
populate[0]=relation-name&populate[1]=another-relation-name&populate[2]=yet-another-relation-name为特定关系填充 1 层深度
填充一些深层次的关系populate[root-relation-name][populate][0]=nested-relation-name为特定关系填充多个深度级别
填充组件populate[0]=component-name填充组件
填充组件及其嵌套组件之一populate[0]=component-name&populate[1]=component-name.nested-component-name填充组件
填充动态区域(仅填充其第一级元素)populate[0]=dynamic-zone-name填充动态区域
使用精确定义、详细的填充策略填充动态区域及其嵌套元素和关系populate[dynamic-zone-name][on][component-category.component-name][populate][relation-name][populate][0]=field-name填充动态区域
💡 提示

构建具有多级填充的复杂查询的最简单方法是使用我们的 交互式查询构建器 工具。

¥The easiest way to build complex queries with multiple-level population is to use our interactive query builder tool.

将 Population 与其他运算符结合起来

¥Combining Population with other operators

通过利用 populate 运算符,可以在总体查询中组合其他运算符,例如 字段选择filterssort

¥By utilizing the populate operator it is possible to combine other operators such as field selection, filters, and sort in the population queries.

提醒

总体和分页运算符不能组合使用。

¥The population and pagination operators cannot be combined.

使用字段选择填充

¥Populate with field selection

fieldspopulate 可以组合。

¥fields and populate can be combined.

Example request

GET /api/articles?fields[0]=title&fields[1]=slug&populate[headerImage][fields][0]=name&populate[headerImage][fields][1]=url

JavaScript 查询(使用 qs 库构建):

¥JavaScript query (built with the qs library):

上面的查询 URL 是使用 qs 构建的。qs 可以在你的计算机上本地运行,如以下代码示例所示,或者你也可以使用我们的 交互式查询构建器 在线工具。

¥The query URL above was built using the qs library. qs can be run locally on your machine, as shown in the following code example, or you can use our interactive query builder online tool.



const qs = require('qs');




const query = qs.stringify(


{
fields: ['title', 'slug'],
populate: {
headerImage: {
fields: ['name', 'url'],
},
},
},
{
encodeValuesOnly: true, // prettify URL
}
);

await request(`/api/articles?${query}`);
Example response
{
"data": [
{
"id": 1,
"documentId": "h90lgohlzfpjf3bvan72mzll",
"title": "Test Article",
"slug": "test-article",
"headerImage": {
"id": 1,
"documentId": "cf07g1dbusqr8mzmlbqvlegx",
"name": "17520.jpg",
"url": "/uploads/17520_73c601c014.jpg"
}
}
],
"meta": {
// ...
}
}

填充过滤

¥Populate with filtering

filterspopulate 可以组合。

¥filters and populate can be combined.

Example request

GET /api/articles?populate[categories][sort][0]=name%3Aasc&populate[categories][filters][name][$eq]=Cars

JavaScript 查询(使用 qs 库构建):

¥JavaScript query (built with the qs library):

上面的查询 URL 是使用 qs 构建的。qs 可以在你的计算机上本地运行,如以下代码示例所示,或者你也可以使用我们的 交互式查询构建器 在线工具。

¥The query URL above was built using the qs library. qs can be run locally on your machine, as shown in the following code example, or you can use our interactive query builder online tool.



const qs = require('qs');




const query = qs.stringify(


{
populate: {
categories: {
sort: ['name:asc'],
filters: {
name: {
$eq: 'Cars',
},
},
},
},
},
{
encodeValuesOnly: true, // prettify URL
}
);

await request(`/api/articles?${query}`);
Example response
{
"data": [
{
"id": 1,
"documentId": "a1b2c3d4e5d6f7g8h9i0jkl",
"title": "Test Article",
// ...
"categories": {
"data": [
{
"id": 2,
"documentId": "jKd8djla9ndalk98hflj3",
"name": "Cars"
// ...
}
]
}
}
}
],
"meta": {
// ...
}
}