diff --git a/docusaurus/docs/cms/api/client.md b/docusaurus/docs/cms/api/client.md
index 2875b562d4..1d4782ff31 100644
--- a/docusaurus/docs/cms/api/client.md
+++ b/docusaurus/docs/cms/api/client.md
@@ -1,6 +1,7 @@
---
title: Strapi Client
description: The Strapi Client library simplifies interactions with your Strapi back end, providing a way to fetch, create, update, and delete content.
+toc_max_heading_level: 4
displayed_sidebar: cmsSidebar
tags:
- API
@@ -14,6 +15,7 @@ tags:
The Strapi Client library simplifies interactions with your Strapi back end, providing a way to fetch, create, update, and delete content. This guide walks you through setting up the Strapi Client, configuring authentication, and using its key features effectively.
## Getting Started
+
:::prerequisites
- A Strapi project has been created and is running. If you haven't set one up yet, follow the [Quick Start Guide](/cms/quick-start) to create one.
- You know the URL of the Content API of your Strapi instance (e.g., `http://localhost:1337/api`).
@@ -51,13 +53,32 @@ To use the Strapi Client in your project, install it as a dependency using your
To start interacting with your Strapi back end, initialize the Strapi Client and set the base API URL:
+
+
+
+With Javascript, import the `strapi` function and create a client instance:
+
```js
import { strapi } from '@strapi/client';
const client = strapi({ baseURL: 'http://localhost:1337/api' });
```
-If you're using the Strapi Client in a browser environment, you can include it using a `
@@ -67,11 +88,16 @@ If you're using the Strapi Client in a browser environment, you can include it u
```
+
+
+
+The `baseURL` must include the protocol (`http` or `https`). An invalid URL will throw an error `StrapiInitializationError`.
+
### Authentication
The Strapi Client supports different authentication strategies to access protected resources in your Strapi back end.
-If your Strapi instance uses API tokens, configure the Strapi Client as follows:
+If your Strapi instance uses [API tokens](/cms/features/api-tokens), configure the Strapi Client as follows:
```js
const client = strapi({
@@ -81,6 +107,7 @@ const client = strapi({
```
This allows your requests to include the necessary authentication credentials automatically.
+If the token is invalid or missing, the client will throw an error during initialization `StrapiValidationError`.
## API Reference
@@ -92,6 +119,7 @@ The Strapi Client provides the following key properties and methods for interact
| `fetch()` | A utility method for making generic API requests similar to the native fetch API. |
| `collection()` | Manages collection-type resources (e.g., blog posts, products). |
| `single()` | Manages single-type resources (e.g., homepage settings, global configurations). |
+| `files()` | Enables upload, retrieve and management of files directly to/from the Strapi Media Library. |
### General purpose fetch
@@ -114,6 +142,9 @@ Collection types in Strapi are entities with multiple entries (e.g., a blog with
| `delete(documentID, queryParams?)` | Update an existing document. |
**Usage examples:**
+
+
+
```js
const articles = client.collection('articles');
@@ -136,6 +167,9 @@ const updatedArticle = await articles.update('article-document-id', { title: 'Up
await articles.delete('article-id');
```
+
+
+
### Working with single types
Single types in Strapi represent unique content entries that exist only once (e.g., the homepage settings or site-wide configurations). The Strapi Client provides a `single()` method to interact with these resources, with the following methods available:
@@ -143,7 +177,7 @@ Single types in Strapi represent unique content entries that exist only once (e.
| ----------| -------------------------------------------------------------------------------------------- |
| `find(queryParams?)` | Fetch the document. |
| `update(documentID, data, queryParams?)` | Update the document. |
-| `delete(queryParams?) ` | Remove the document. |
+| `delete(queryParams?)` | Remove the document. |
**Usage examples:**
```js
@@ -165,20 +199,25 @@ const updatedHomepage = await homepage.update(
await homepage.delete();
```
-### Working with files
+### Working with files
The Strapi Client provides access to the [Media Library](/cms/features/media-library) via the `files` property. This allows you to retrieve and manage file metadata without directly interacting with the REST API.
-The following methods are available for working with files:
+The following methods are available for working with files. Click on the method name in the table to jump to the corresponding section with more details and examples:
| Method | Description |
|--------|-------------|
-| `find(params?)` | Retrieves a list of file metadata based on optional query parameters |
-| `findOne(fileId)` | Retrieves the metadata for a single file by its ID |
-| `update(fileId, fileInfo)` | Updates metadata for an existing file |
-| `delete(fileId)` | Deletes a file by its ID |
+| [`find(params?)`](#find) | Retrieves a list of file metadata based on optional query parameters |
+| [`findOne(fileId)`](#findone) | Retrieves the metadata for a single file by its ID |
+| [`update(fileId, fileInfo)`](#update) | Updates metadata for an existing file |
+| [`upload(file, options)`](#upload) | Uploads a file (Blob or Buffer) with an optional `options` object for metadata |
+| [`delete(fileId)`](#delete) | Deletes a file by its ID |
-**Usage examples:**
+#### `find`
+
+The `strapi.client.files.find()` method retrieves a list of file metadata based on optional query parameters.
+
+The method can be used as follows:
```js
// Initialize the client
@@ -199,12 +238,40 @@ const imageFiles = await client.files.find({
},
sort: ['name:asc'], // Sort by name in ascending order
});
+```
+
+#### `findOne` {#findone}
+
+The `strapi.client.files.findOne()` method retrieves the metadata for a single file by its id.
+
+The method can be used as follows:
+
+```js
+// Initialize the client
+const client = strapi({
+ baseURL: 'http://localhost:1337/api',
+ auth: 'your-api-token',
+});
// Find file metadata by ID
const file = await client.files.findOne(1);
-console.log(file.name); // The file name
-console.log(file.url); // The file URL
+console.log(file.name);
+console.log(file.url);
console.log(file.mime); // The file MIME type
+```
+
+#### `update`
+
+The `strapi.client.files.update()` method updates metadata for an existing file, accepting 2 parameters, the `fileId`, and an object containing options such as the name, alternative text, and caption for the media.
+
+The methods can be used as follows:
+
+```js
+// Initialize the client
+const client = strapi({
+ baseURL: 'http://localhost:1337/api',
+ auth: 'your-api-token',
+});
// Update file metadata
const updatedFile = await client.files.update(1, {
@@ -212,6 +279,151 @@ const updatedFile = await client.files.update(1, {
alternativeText: 'Descriptive alt text for accessibility',
caption: 'A caption for the file',
});
+```
+
+#### `upload` {#upload}
+
+The Strapi Client provides media file upload functionality through the `FilesManager`, accessible through the `strapi.client.files.upload()` method. The method allows you to upload media files (such as images, videos, or documents) to your Strapi backend.
+
+The method supports uploading files as `Blob` (in browsers or Node.js) or as `Buffer` (in Node.js only). The method also supports attaching metadata to the uploaded file, such as `alternativeText` and `caption`.
+
+##### Method Signature
+
+```js
+async upload(file: Blob, options?: BlobUploadOptions): Promise
+async upload(file: Buffer, options: BufferUploadOptions): Promise
+```
+
+- For `Blob` uploads, `options` is optional and may include `fileInfo` for metadata.
+- For `Buffer` uploads, `options` must include `filename` and `mimetype`, and may include `fileInfo`.
+
+The response is an array of file objects, each containing details such as `id`, `name`, `url`, `size`, and `mime` [source](https://github.com/strapi/client/blob/60a0117e361346073bed1959d354c7facfb963b3/src/files/types.ts).
+
+
+
+
+You can upload a file use through the browser as follows:
+
+```js
+const client = strapi({ baseURL: 'http://localhost:1337/api' });
+
+const fileInput = document.querySelector('input[type="file"]');
+const file = fileInput.files[0];
+
+try {
+ const result = await client.files.upload(file, {
+ fileInfo: {
+ alternativeText: 'A user uploaded image',
+ caption: 'Uploaded via browser',
+ },
+ });
+ console.log('Upload successful:', result);
+} catch (error) {
+ console.error('Upload failed:', error);
+}
+```
+
+
+
+
+
+With Node.js, you can either upload a blob or a buffer, as in the following examples:
+
+
+
+
+```js
+import { readFile } from 'fs/promises';
+
+const client = strapi({ baseURL: 'http://localhost:1337/api' });
+
+const filePath = './image.png';
+const mimeType = 'image/png';
+const fileContentBuffer = await readFile(filePath);
+const fileBlob = new Blob([fileContentBuffer], { type: mimeType });
+
+try {
+ const result = await client.files.upload(fileBlob, {
+ fileInfo: {
+ name: 'Image uploaded as Blob',
+ alternativeText: 'Uploaded from Node.js Blob',
+ caption: 'Example upload',
+ },
+ });
+ console.log('Blob upload successful:', result);
+} catch (error) {
+ console.error('Blob upload failed:', error);
+}
+```
+
+
+
+
+
+```js
+import { readFile } from 'fs/promises';
+
+const client = strapi({ baseURL: 'http://localhost:1337/api' });
+
+const filePath = './image.png';
+const fileContentBuffer = await readFile(filePath);
+
+try {
+ const result = await client.files.upload(fileContentBuffer, {
+ filename: 'image.png',
+ mimetype: 'image/png',
+ fileInfo: {
+ name: 'Image uploaded as Buffer',
+ alternativeText: 'Uploaded from Node.js Buffer',
+ caption: 'Example upload',
+ },
+ });
+ console.log('Buffer upload successful:', result);
+} catch (error) {
+ console.error('Buffer upload failed:', error);
+}
+```
+
+
+
+
+
+
+
+##### Response Structure
+
+The `strapi.client.files.upload()` method returns an array of file objects, each with fields such as:
+
+```json
+{
+ "id": 1,
+ "name": "image.png",
+ "alternativeText": "Uploaded from Node.js Buffer",
+ "caption": "Example upload",
+ "mime": "image/png",
+ "url": "/uploads/image.png",
+ "size": 12345,
+ "createdAt": "2025-07-23T12:34:56.789Z",
+ "updatedAt": "2025-07-23T12:34:56.789Z"
+}
+```
+
+:::note Additional response fields
+The upload response includes additional fields beyond those shown above. See the complete FileResponse interface in the for all available fields.
+:::
+
+#### `delete`
+
+The `strapi.client.files.delete()` method deletes a file by its ID.
+
+The method can be used as follows:
+
+```js
+// Initialize the client
+const client = strapi({
+ baseURL: 'http://localhost:1337/api',
+ auth: 'your-api-token',
+});
// Delete a file by ID
const deletedFile = await client.files.delete(1);
@@ -220,6 +432,19 @@ console.log('Deleted file ID:', deletedFile.id);
console.log('Deleted file name:', deletedFile.name);
```
+
+
+## Handling Common Errors
+
+The following errors might occur when sending queries through the Strapi Client:
+
+| Error | Description |
+|-------|-------------|
+| Permission Errors | If the authenticated user does not have permission to upload or manage files, a `FileForbiddenError` is thrown. |
+| HTTP Errors|If the server is unreachable, authentication fails, or there are network issues, an `HTTPError` is thrown. |
+| Missing Parameters|When uploading a `Buffer`, both `filename` and `mimetype` must be provided in the options object. If either is missing, an error is thrown. |
+
+
:::strapi Additional information
-More details about the Strapi Strapi Client might be found in the .
-:::
\ No newline at end of file
+More details about the Strapi Client may be found in the .
+:::