# REST API参考

> Source: https://strapi.nodejs.cn/cms/api/rest

🌐 REST API reference

Strapi 的 REST API 会自动为内容类型生成端点，使用 GET、POST、PUT 和 DELETE 方法来获取、创建、更新和删除文档，并支持过滤、排序、字段选择和关联填充。

🌐 Strapi's REST API automatically generates endpoints for content-types to fetch, create, update, and delete documents using GET, POST, PUT, and DELETE methods, with support for filtering, sorting, field selection, and relation population.

REST API 允许通过 API 端点访问 [内容类型](/cms/backend-customization/models)。Strapi 在创建内容类型时会自动创建 [API 端点](#endpoints)。在查询 API 端点时可以使用 [API 参数](/cms/api/rest/parameters) 来优化结果。

🌐 The REST API allows accessing the [content-types](/cms/backend-customization/models) through API endpoints. Strapi automatically creates [API endpoints](#endpoints) when a content-type is created. [API parameters](/cms/api/rest/parameters) can be used when querying API endpoints to refine the results.

本节文档是针对内容类型的 REST API 参考。我们还提供了针对特定用例的[指南](/cms/api/rest/guides/intro)。

🌐 This section of the documentation is for the REST API reference for content-types. We also have [guides](/cms/api/rest/guides/intro) available for specific use cases.

:::prerequisites

所有内容类型默认都是私有的，需要将其设为公开，或者查询需要使用适当权限进行认证。有关更多详细信息，请参阅[快速入门指南](/cms/quick-start#step-10-set-roles--permissions)、[用户与权限功能](/cms/features/users-permissions#roles)用户指南，以及[API 令牌配置文档](/cms/features/api-tokens)。

🌐 All content types are private by default and need to be either made public or queries need to be authenticated with the proper permissions. See the [Quick Start Guide](/cms/quick-start#step-10-set-roles--permissions), the user guide for the [Users & Permissions feature](/cms/features/users-permissions#roles), and [API tokens configuration documentation](/cms/features/api-tokens) for more details.

:::

:::note

默认情况下，REST API 响应仅包含顶层字段，不会填充任何关系、媒体字段、组件或动态区域。使用 [`populate` 参数](/cms/api/rest/populate-select) 来填充特定字段。确保为要填充的关系的字段授予查找权限。

🌐 By default, the REST API responses only include top-level fields and does not populate any relations, media fields, components, or dynamic zones. Use the [`populate` parameter](/cms/api/rest/populate-select) to populate specific fields. Ensure that the find permission is given to the field(s) for the relation(s) you populate.

:::

:::tip Performance best practices

对于生产环境的应用，要有意地进行数据获取：使用显式填充，限制填充深度，并在路由中间件中集中填充逻辑。请参阅 Strapi 博客上的  [Building High-Performance Strapi Applications](https://strapi.io/blog/building-high-performance-strapi-applications-common-pitfalls-and-best-practices)  获取完整指南。

:::

:::strapi Strapi Client

[Strapi 客户端](/cms/api/client) 库简化了与你的 Strapi 后端的交互，提供了一种获取、创建、更新和删除内容的方式。

🌐 The [Strapi Client](/cms/api/client) library simplifies interactions with your Strapi back end, providing a way to fetch, create, update, and delete content.

:::

## 端点 {#endpoints}

🌐 Endpoints

对于每个 Content-Type，会自动生成以下端点：

🌐 For each Content-Type, the following endpoints are automatically generated:

<details>
<summary>复数 API ID 与单数 API ID:</summary>

在下表中：

🌐 In the following tables:

- `:singularApiId` 指内容类型中“API ID（单数）”字段的值，
- 而 `:pluralApiId` 指的是内容类型的“API ID（复数）”字段的值。

这些值是在内容类型构建器中创建内容类型时定义的，并且可以在管理面板编辑内容类型时找到（参见 [用户指南](/cms/features/content-type-builder#creating-content-types)）。例如，对于“文章”内容类型，默认情况下：

🌐 These values are defined when creating a content-type in the Content-Type Builder, and can be found while editing a content-type in the admin panel (see [User Guide](/cms/features/content-type-builder#creating-content-types)). For instance, by default, for an "Article" content-type:

- `:singularApiId` 将是 `article`
- `:pluralApiId` 将是 `articles`

</details>

| 方法 | URL | 描述 |
| --- | --- | --- |
| `GET` | `/api/:pluralApiId` | [获取文档列表](#get-all) |
| `POST` | `/api/:pluralApiId` | [创建文档](#create) |
| `GET` | `/api/:pluralApiId/:documentId` | [获取文档](#get) |
| `PUT` | `/api/:pluralApiId/:documentId` | [更新文档](#update) |
| `DELETE` | `/api/:pluralApiId/:documentId` | [删除文档](#delete) |
| 方法 | URL | 描述 |
| --- | --- | --- |
| `GET` | `/api/:singularApiId` | [获取文档](#get) |
| `PUT` | `/api/:singularApiId` | [更新/创建文档](#update) |
| `DELETE` | `/api/:singularApiId` | [删除文档](#delete) |

:::strapi Upload API

上传包（为[媒体库功能](/cms/features/media-library)提供支持）有一个特定的 API，可通过其[`/api/upload`端点](/cms/api/rest/upload)访问。

🌐 The Upload package (which powers the [Media Library feature](/cms/features/media-library)) has a specific API accessible through its [`/api/upload` endpoints](/cms/api/rest/upload).

:::

:::note

[组件](/cms/backend-customization/models#components-json) 没有 API 端点。

:::

## 请求 {#requests}

🌐 Requests

:::strapi Strapi 5 vs. Strapi v4

Strapi 5 的内容 API 与 Strapi v4 有 2 个主要区别：

🌐 Strapi 5's Content API includes 2 major differences with Strapi v4:

- 响应格式已被扁平化，这意味着属性不再嵌套在 `data.attributes` 对象中，而是可以直接在 `data` 对象的第一层访问（例如，内容类型的“title”属性可以使用 `data.title` 访问）。
- Strapi 5 现在使用 **文档**  ，并且文档通过它们的 `documentId` 访问（详情请参见 [重大更改条目](/cms/migration/v4-to-v5/breaking-changes/use-document-id)）

:::

请求以对象形式返回响应，通常包含以下键：

🌐 Requests return a response as an object which usually includes the following keys:

- `data`：响应数据本身，可以是：
  - 单个文档，作为具有以下键的对象：
    - `id`（整数）
    - `documentId`（字符串），这是在查询特定文档时使用的唯一标识符，
    - 属性（每个属性的类型取决于该属性，详细信息请参阅 [models attributes](/cms/backend-customization/models#model-attributes) 文档）
    - `meta`（对象）
  - 文档列表，作为对象数组
  - 自定义响应
- `meta`（对象）：有关分页、发布状态、可用语言环境等的信息。
- `error`（对象，_可选_）：关于请求抛出的任何[错误](/cms/error-handling)的信息

:::note

某些插件（包括用户和权限以及上传）可能不遵循此响应格式。

🌐 Some plugins (including Users & Permissions and Upload) may not follow this response format.

:::

### 获取文档 {#get-all}

🌐 Get documents 

:::tip Tip: Strapi 5 vs. Strapi 4

在 Strapi 5 中，响应格式已被扁平化，属性可以直接从 `data` 对象访问，而不再嵌套在 `data.attributes` 中。

🌐 In Strapi 5 the response format has been flattened, and attributes are directly accessible from the `data` object instead of being nested in `data.attributes`.

在迁移到 Strapi 5 时，你可以传递一个可选的头（参见[相关破坏性更改](/cms/migration/v4-to-v5/breaking-changes/new-response-format)）。

🌐 You can pass an optional header while you're migrating to Strapi 5 (see the [related breaking change](/cms/migration/v4-to-v5/breaking-changes/new-response-format)).

:::

#### GET /api/:pluralApiId — 列出文件

返回分页的文档列表。支持过滤、排序、字段选择和关联填充。

**Parameters:**
- `sort` (string | string[]): Sort by field. Use `field:asc` or `field:desc`
- `filters` (object): Filter with operators: `$eq`, `$contains`, `$gt`, `$lt`. See filtering (/cms/api/rest/filters).
- `populate` (string | object): Relations and components to include. Use `*` for all. See populate (/cms/api/rest/populate-select).
- `fields` (string[]): Select specific fields to return. See field selection (/cms/api/rest/populate-select#field-selection).
- `pagination[page]` (integer): Page number. Default: `1`
- `pagination[pageSize]` (integer): Items per page. Default `25`, max `100`
- `locale` (string): Locale of the documents to fetch. See locale (/cms/api/rest/locale).
- `status` (string): `published` or `draft`. See status (/cms/api/rest/status).
- `publicationFilter` (string): Query documents by the relationship between their draft and published versions. See publicationFilter (/cms/api/rest/publication-filter).

```bash
curl 'http://localhost:1337/api/restaurants' \
  -H 'Authorization: Bearer <token>'
```
```js
const response = await fetch(
  'http://localhost:1337/api/restaurants',
  {
    headers: {
      Authorization: 'Bearer <token>',
    },
  }
);
const data = await response.json();
```

```json
{
  "data": [
    {
      "id": 2,
      "documentId": "hgv1vny5cebq2l3czil1rpb3",
      "Name": "BMK Paris Bamako",
      "Description": null,
      "createdAt": "2024-03-06T13:42:05.098Z",
      "updatedAt": "2024-03-06T13:42:05.098Z",
      "publishedAt": "2024-03-06T13:42:05.103Z",
      "locale": "en"
    },
    {
      "id": 4,
      "documentId": "znrlzntu9ei5onjvwfaalu2v",
      "Name": "Biscotte Restaurant",
      "createdAt": "2024-03-06T13:43:30.172Z",
      "updatedAt": "2024-03-06T13:43:30.172Z",
      "publishedAt": "2024-03-06T13:43:30.175Z",
      "locale": "en"
    }
  ],
  "meta": {
    "pagination": { "page": 1, "pageSize": 25, "pageCount": 1, "total": 2 }
  }
}
```

### 获取文档 {#get}

🌐 Get a document 

:::strapi Strapi 5 vs. Strapi v4

在 Strapi 5 中，特定文档可以通过其 `documentId` 来访问。

🌐 In Strapi 5, a specific document is reached by its `documentId`.

:::

#### GET /api/:pluralApiId/:documentId — 获取文件

通过其 documentId 返回单个文档。支持字段选择和关系填充。

**Parameters:**
- `pluralApiId` (string, required): Plural API ID of the content-type (e.g. `restaurants`)
- `documentId` (string, required): Unique document identifier

```bash
curl 'http://localhost:1337/api/restaurants/znrlzntu9ei5onjvwfaalu2v' \
  -H 'Authorization: Bearer <token>'
```
```js
const response = await fetch(
  'http://localhost:1337/api/restaurants/znrlzntu9ei5onjvwfaalu2v',
  {
    headers: {
      Authorization: 'Bearer <token>',
    },
  }
);
const data = await response.json();
```

```json
{
  "data": {
    "id": 6,
    "documentId": "znrlzntu9ei5onjvwfaalu2v",
    "Name": "Biscotte Restaurant",
    "Description": [
      {
        "type": "paragraph",
        "children": [{ "type": "text", "text": "Welcome to Biscotte restaurant! Restaurant Biscotte offers a cuisine based on fresh, quality products." }]
      }
    ],
    "createdAt": "2024-02-27T10:19:04.953Z",
    "updatedAt": "2024-03-05T15:52:05.591Z",
    "publishedAt": "2024-03-05T15:52:05.600Z",
    "locale": "en"
  },
  "meta": {}
}
```
```json
{
  "data": null,
  "error": {
    "status": 404,
    "name": "NotFoundError",
    "message": "Document not found"
  }
}
```

### 创建文档 {#create}

🌐 Create a document 

如果安装了[国际化 (i18n) 插件](/cms/features/internationalization)，则可以使用 POST 请求向 REST API [创建本地化文档](/cms/api/rest/locale#rest-delete)。

🌐 If the [Internationalization (i18n) plugin](/cms/features/internationalization) is installed, it's possible to use POST requests to the REST API to [create localized documents](/cms/api/rest/locale#rest-delete).

:::note

在创建文档时，你可以定义其关系及其顺序（有关更多详细信息，请参见[通过 REST API 管理关系](/cms/api/rest/relations.md)）。

🌐 While creating a document, you can define its relations and their order (see [Managing relations through the REST API](/cms/api/rest/relations.md) for more details).

:::

:::info Dynamic zones

当你提交（POST）一个文档时，动态区域数组中的每个对象都必须包含该变体的 UID（例如 `shared.slider`）的 `__component`。将 `__component` 放在表示动态区域中一行的对象上。该对象内部的嵌套字段应当与使用 `populate` 获取同一文档时返回的 JSON 相匹配，因此除非模式将该层级视为另一个区别结构，否则不要在内部对象上放置 `__component`。

🌐 When you POST a document, each object inside a dynamic zone array must include `__component` with that variant's UID (for example `shared.slider`). Put `__component` on the object that represents one row in the dynamic zone. Nested fields inside that object should mirror the JSON you get back when the same document is fetched with `populate` so you do not place `__component` on inner objects unless the schema treats that level as another discriminated structure.

:::

#### POST /api/:pluralApiId — 创建一个文档

创建一个新文档并返回它。在请求正文中将字段值放入数据对象中。

**Parameters:**
- `data` (object, required): Object containing the field values for the new document

```bash
curl -X POST \
  'http://localhost:1337/api/restaurants' \
  -H 'Authorization: Bearer <token>' \
  -H 'Content-Type: application/json' \
  -d '{
    "data": {
      "Name": "Restaurant D",
      "Description": [
        {
          "type": "paragraph",
          "children": [{ "type": "text", "text": "A very short description goes here." }]
        }
      ]
    }
  }'
```
```js
const response = await fetch(
  'http://localhost:1337/api/restaurants',
  {
    method: 'POST',
    headers: {
      Authorization: 'Bearer <token>',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      data: {
        Name: 'Restaurant D',
        Description: [
          {
            type: 'paragraph',
            children: [{ type: 'text', text: 'A very short description goes here.' }],
          },
        ],
      },
    }),
  }
);
const data = await response.json();
```

```json
{
  "data": {
    "documentId": "bw64dnu97i56nq85106yt4du",
    "Name": "Restaurant D",
    "Description": [
      {
        "type": "paragraph",
        "children": [{ "type": "text", "text": "A very short description goes here." }]
      }
    ],
    "createdAt": "2024-03-05T16:44:47.689Z",
    "updatedAt": "2024-03-05T16:44:47.689Z",
    "publishedAt": "2024-03-05T16:44:47.687Z",
    "locale": "en"
  },
  "meta": {}
}
```

### 更新文档 {#update}

🌐 Update a document 

:::note NOTES

* 即使安装了[国际化 (i18n) 插件](/cms/features/internationalization)，目前仍然无法[更新文档的语言环境](/cms/api/rest/locale#rest-update)。
* 在更新文档时，你可以定义其关系及其顺序（有关更多详细信息，请参见[通过 REST API 管理关系](/cms/api/rest/relations)）。

:::

:::info Dynamic zones

你发送到[动态区域](/cms/backend-customization/models#dynamic-zones)的每个条目必须包含 `__component`，其值为目标组件的 UID（例如 `shared.media`）。Strapi 使用该字段在你创建或更新区域中的项目时选择组件的模式；如果没有它，写入操作可能会验证失败或返回成功但不更改数据。请使用内容类型生成器中显示的每个组件的 UID。

🌐 Each entry you send for a [dynamic zone](/cms/backend-customization/models#dynamic-zones) must include `__component` with the target component's UID (for example `shared.media`). Strapi uses that field to pick the component schema when you create or update items in the zone; without it, writes can fail validation or return success without changing data. Use the UID shown in the Content-Type Builder for each component in the zone.

:::

#### PUT /api/:pluralApiId/:documentId — 更新文档

通过 documentId 部分更新文档并返回其值。发送 null 值以清除字段。

**Parameters:**
- `data` (object, required): Object containing the field values to update

```bash
curl -X PUT \
  'http://localhost:1337/api/restaurants/hgv1vny5cebq2l3czil1rpb3' \
  -H 'Authorization: Bearer <token>' \
  -H 'Content-Type: application/json' \
  -d '{
    "data": {
      "Name": "BMK Paris Bamako",
      "Description": [
        {
          "type": "paragraph",
          "children": [{ "type": "text", "text": "A very short description goes here." }]
        }
      ]
    }
  }'
```
```js
const response = await fetch(
  'http://localhost:1337/api/restaurants/hgv1vny5cebq2l3czil1rpb3',
  {
    method: 'PUT',
    headers: {
      Authorization: 'Bearer <token>',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      data: {
        Name: 'BMK Paris Bamako',
        Description: [
          {
            type: 'paragraph',
            children: [{ type: 'text', text: 'A very short description goes here.' }],
          },
        ],
      },
    }),
  }
);
const data = await response.json();
```

```json
{
  "data": {
    "id": 9,
    "documentId": "hgv1vny5cebq2l3czil1rpb3",
    "Name": "BMK Paris Bamako",
    "Description": [
      {
        "type": "paragraph",
        "children": [{ "type": "text", "text": "A very short description goes here." }]
      }
    ],
    "createdAt": "2024-03-06T13:42:05.098Z",
    "updatedAt": "2024-03-06T14:16:56.883Z",
    "publishedAt": "2024-03-06T14:16:56.895Z",
    "locale": "en"
  },
  "meta": {}
}
```

### 删除文档 {#delete}

🌐 Delete a document 

#### DELETE /api/:pluralApiId/:documentId — 删除文档

通过文档ID永久删除文档。此操作不可撤销。

**Parameters:**
- `pluralApiId` (string, required): Plural API ID (e.g. `restaurants`)
- `documentId` (string, required): Document ID of the entry to delete

```bash
curl -X DELETE \
  'http://localhost:1337/api/restaurants/bw64dnu97i56nq85106yt4du' \
  -H 'Authorization: Bearer <token>'
```
```js
const response = await fetch(
  'http://localhost:1337/api/restaurants/bw64dnu97i56nq85106yt4du',
  {
    method: 'DELETE',
    headers: {
      Authorization: 'Bearer <token>',
    },
  }
);
```
