Skip to content

Commit 817bc84

Browse files
committed
Improve structure
so that the new upload-related information better fits with the existing information architecture
1 parent f8f75be commit 817bc84

File tree

1 file changed

+130
-57
lines changed

1 file changed

+130
-57
lines changed

docusaurus/docs/cms/api/client.md

Lines changed: 130 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
---
22
title: Strapi Client
33
description: The Strapi Client library simplifies interactions with your Strapi back end, providing a way to fetch, create, update, and delete content.
4+
toc_max_heading_level: 4
45
displayed_sidebar: cmsSidebar
56
tags:
67
- API
@@ -51,20 +52,22 @@ To use the Strapi Client in your project, install it as a dependency using your
5152

5253
To start interacting with your Strapi back end, initialize the Strapi Client and set the base API URL:
5354

54-
With Javascript, require the `strapi` function and create a client instance:
5555
<Tabs groupId="js-ts">
5656
<TabItem value="js" label="JavaScript">
5757

58+
With Javascript, require the `strapi` function and create a client instance:
59+
5860
```js
5961
import { strapi } from '@strapi/client';
6062

6163
const client = strapi({ baseURL: 'http://localhost:1337/api' });
6264
```
65+
6366
</TabItem>
6467

68+
<TabItem value="ts" label="TypeScript">
6569

6670
With Typescript, import the `strapi` function and create a client instance with your Strapi API base URL:
67-
<TabItem value="ts" label="TypeScript">
6871

6972
```typescript
7073
import { strapi } from '@strapi/client';
@@ -73,17 +76,20 @@ const client = strapi({ baseURL: 'http://localhost:1337/api' });
7376
```
7477
</TabItem>
7578

76-
77-
If you're using the Strapi Client in a browser environment, you can include it using a `<script>` tag.
7879
<TabItem value="browser" label="Browser (UMD)">
80+
If you're using the Strapi Client in a browser environment, you can include it using a `<script>` tag.
81+
7982
```js title="./src/api/[apiName]/routes/[routerName].ts (e.g './src/api/restaurant/routes/restaurant.ts')"
8083
<script src="https://cdn.jsdelivr.net/npm/@strapi/client"></script>
8184

8285
<script>
8386
const client = strapi.strapi({ baseURL: 'http://localhost:1337/api' });
8487
</script>
8588
```
89+
8690
</TabItem>
91+
</Tabs>
92+
8793
The `baseURL` must include the protocol (`http` or `https`). An invalid URL will throw an error `StrapiInitializationError`.
8894

8995

@@ -139,6 +145,7 @@ Collection types in Strapi are entities with multiple entries (e.g., a blog with
139145
**Usage examples:**
140146
<Tabs groupId="js-ts">
141147
<TabItem value="js" label="JavaScript">
148+
142149
```js
143150
const articles = client.collection('articles');
144151

@@ -160,6 +167,7 @@ const updatedArticle = await articles.update('article-document-id', { title: 'Up
160167
// Delete an article
161168
await articles.delete('article-id');
162169
```
170+
163171
</TabItem>
164172
</Tabs>
165173

@@ -192,16 +200,96 @@ const updatedHomepage = await homepage.update(
192200
await homepage.delete();
193201
```
194202

195-
## FilesManager use in the Client
203+
### Working with files
204+
205+
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.
206+
207+
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:
208+
209+
| Method | Description |
210+
|--------|-------------|
211+
| [`find(params?)`](#find) | Retrieves a list of file metadata based on optional query parameters |
212+
| [`findOne(fileId)`](#findOne) | Retrieves the metadata for a single file by its ID |
213+
| [`update(fileId, fileInfo)`](#update) | Updates metadata for an existing file |
214+
| [`upload(type, options)`](#upload) | Uploads a file, specifying:<ul><li>`type` which can be `file`, `fileContentBuffer`, or `fileBlob`</li><li>and an additional `options` object</li></ul> |
215+
| [`delete(fileId)`](#delete) | Deletes a file by its ID |
216+
217+
#### `find`
218+
219+
The `strapi.client.files.find()` method retrieves a list of file metadata based on optional query parameters.
220+
221+
The method can be used as follows:
222+
223+
```js
224+
// Initialize the client
225+
const client = strapi({
226+
baseURL: 'http://localhost:1337/api',
227+
auth: 'your-api-token',
228+
});
229+
230+
// Find all file metadata
231+
const allFiles = await client.files.find();
232+
console.log(allFiles);
233+
234+
// Find file metadata with filtering and sorting
235+
const imageFiles = await client.files.find({
236+
filters: {
237+
mime: { $contains: 'image' }, // Only get image files
238+
name: { $contains: 'avatar' }, // Only get files with 'avatar' in the name
239+
},
240+
sort: ['name:asc'], // Sort by name in ascending order
241+
});
242+
```
243+
244+
#### `findOne`
196245

197-
### Media File Upload <NewBadge />
246+
The `strapi.client.files.findOne()` method retrieves the metadata for a single file by its id.
198247

199-
The Strapi Client provides media file upload functionality through the `FilesManager`, accessible as `client.files`.
248+
The method can be used as follows:
200249

201-
The `client.files.upload()` method allows you to upload media files (such as images, videos, or documents) to your Strapi backend. It supports uploading files as `Blob` (in browsers or Node.js) or as `Buffer` (in Node.js). The method also supports attaching metadata to the uploaded file, such as `alternativeText` and `caption`.
250+
```js
251+
// Initialize the client
252+
const client = strapi({
253+
baseURL: 'http://localhost:1337/api',
254+
auth: 'your-api-token',
255+
});
202256

257+
// Find file metadata by ID
258+
const file = await client.files.findOne(1);
259+
console.log(file.name);
260+
console.log(file.url);
261+
console.log(file.mime); // The file MIME type
262+
```
263+
264+
#### `update`
203265

204-
### Method Signature
266+
The `strapi.client.files.findOne()` method updates metadata for an existing filei, accepting 2 parameters, the `fileId`, and an object containing options such as the name, alternative text, and caption for the media.
267+
268+
The methods can be used as follows:
269+
270+
```js
271+
// Initialize the client
272+
const client = strapi({
273+
baseURL: 'http://localhost:1337/api',
274+
auth: 'your-api-token',
275+
});
276+
277+
// Update file metadata
278+
const updatedFile = await client.files.update(1, {
279+
name: 'New file name',
280+
alternativeText: 'Descriptive alt text for accessibility',
281+
caption: 'A caption for the file',
282+
});
283+
```
284+
285+
286+
#### `upload` <NewBadge />
287+
288+
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.
289+
290+
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`.
291+
292+
##### Method Signature
205293

206294
```js
207295
async upload(file: Blob, options?: BlobUploadOptions): Promise<MediaUploadResponse>
@@ -213,9 +301,10 @@ async upload(file: Buffer, options: BufferUploadOptions): Promise<MediaUploadRes
213301

214302
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).
215303

216-
**Usage examples:**
304+
<Tabs>
305+
<TabItem value="browser" label="Upload a file with the browser">
217306

218-
#### Uploading a File in the Browser
307+
You can upload a file use through the browser as follows:
219308

220309
```js
221310
const client = strapi({ baseURL: 'http://localhost:1337/api' });
@@ -236,7 +325,14 @@ try {
236325
}
237326
```
238327

239-
#### Uploading a Blob in Node.js
328+
</TabItem>
329+
330+
<TabItem value="node" label="Upload a file with Node.js">
331+
332+
With Node.js, you can either upload a blob or a buffer, as in the following examples:
333+
334+
<Tabs>
335+
<TabItem value="node-blob" label="Uploading a Blob">
240336

241337
```js
242338
import { readFile } from 'fs/promises';
@@ -262,7 +358,9 @@ try {
262358
}
263359
```
264360

265-
#### Uploading a Buffer in Node.js
361+
</TabItem>
362+
363+
<TabItem value="node-buffer" label="Uploading a Buffer">
266364

267365
```js
268366
import { readFile } from 'fs/promises';
@@ -288,10 +386,15 @@ try {
288386
}
289387
```
290388

389+
</TabItem>
390+
</Tabs>
391+
392+
</TabItem>
393+
</Tabs>
291394

292-
### Response Structure
395+
##### Response Structure
293396

294-
The upload method returns an array of file objects, each with fields such as:
397+
The `strapi.client.files.upload()` method returns an array of file objects, each with fields such as:
295398

296399
```json
297400
{
@@ -307,21 +410,11 @@ The upload method returns an array of file objects, each with fields such as:
307410
}
308411
```
309412

413+
#### `delete`
310414

311-
### Managing files
415+
The `strapi.client.files.delete()` method deletes a file by its ID.
312416

313-
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.
314-
315-
The following methods are available for working with files:
316-
317-
| Method | Description |
318-
|--------|-------------|
319-
| `find(params?)` | Retrieves a list of file metadata based on optional query parameters |
320-
| `findOne(fileId)` | Retrieves the metadata for a single file by its ID |
321-
| `update(fileId, fileInfo)` | Updates metadata for an existing file |
322-
| `delete(fileId)` | Deletes a file by its ID |
323-
324-
**Usage examples:**
417+
The method can be used as follows:
325418

326419
```js
327420
// Initialize the client
@@ -330,44 +423,24 @@ const client = strapi({
330423
auth: 'your-api-token',
331424
});
332425

333-
// Find all file metadata
334-
const allFiles = await client.files.find();
335-
console.log(allFiles);
336-
337-
// Find file metadata with filtering and sorting
338-
const imageFiles = await client.files.find({
339-
filters: {
340-
mime: { $contains: 'image' }, // Only get image files
341-
name: { $contains: 'avatar' }, // Only get files with 'avatar' in the name
342-
},
343-
sort: ['name:asc'], // Sort by name in ascending order
344-
});
345-
346-
// Find file metadata by ID
347-
const file = await client.files.findOne(1);
348-
console.log(file.name); // The file name
349-
console.log(file.url); // The file URL
350-
console.log(file.mime); // The file MIME type
351-
352-
// Update file metadata
353-
const updatedFile = await client.files.update(1, {
354-
name: 'New file name',
355-
alternativeText: 'Descriptive alt text for accessibility',
356-
caption: 'A caption for the file',
357-
});
358-
359426
// Delete a file by ID
360427
const deletedFile = await client.files.delete(1);
361428
console.log('File deleted successfully');
362429
console.log('Deleted file ID:', deletedFile.id);
363430
console.log('Deleted file name:', deletedFile.name);
364431
```
365432

433+
<br/>
434+
366435
## Handling Common Errors
367436

368-
- **Permission Errors:** If the authenticated user does not have permission to upload or manage files, a `FileForbiddenError` is thrown.
369-
- **HTTP Errors:** If the server is unreachable, authentication fails, or there are network issues, an `HTTPError` is thrown.
370-
- **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.
437+
The following errors might occur when sending queries through the Strapi Client:
438+
439+
| Error | Description |
440+
|-------|-------------|
441+
| Permission Errors | If the authenticated user does not have permission to upload or manage files, a `FileForbiddenError` is thrown. |
442+
| HTTP Errors|If the server is unreachable, authentication fails, or there are network issues, an `HTTPError` is thrown. |
443+
| 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. |
371444

372445

373446
:::strapi Additional information

0 commit comments

Comments
 (0)