Skip to content

Commit dd07583

Browse files
authored
Merge pull request #2602 from strapi/cms/client-doc-improvements
Expand and improve Client docs
2 parents 28ce9f6 + b8b1a9e commit dd07583

File tree

1 file changed

+239
-14
lines changed

1 file changed

+239
-14
lines changed

docusaurus/docs/cms/api/client.md

Lines changed: 239 additions & 14 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
@@ -14,6 +15,7 @@ tags:
1415
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.
1516

1617
## Getting Started
18+
1719
:::prerequisites
1820
- 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.
1921
- 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
5153

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

56+
<Tabs groupId="js-ts">
57+
<TabItem value="js" label="JavaScript">
58+
59+
With Javascript, import the `strapi` function and create a client instance:
60+
5461
```js
5562
import { strapi } from '@strapi/client';
5663

5764
const client = strapi({ baseURL: 'http://localhost:1337/api' });
5865
```
5966

60-
If you're using the Strapi Client in a browser environment, you can include it using a `<script>` tag:
67+
</TabItem>
68+
69+
<TabItem value="ts" label="TypeScript">
70+
71+
With Typescript, import the `strapi` function and create a client instance with your Strapi API base URL:
72+
73+
```typescript
74+
import { strapi } from '@strapi/client';
75+
76+
const client = strapi({ baseURL: 'http://localhost:1337/api' });
77+
```
78+
</TabItem>
79+
80+
<TabItem value="browser" label="Browser (UMD)">
81+
If you're using the Strapi Client in a browser environment, you can include it using a `<script>` tag.
6182

6283
```js title="./src/api/[apiName]/routes/[routerName].ts (e.g './src/api/restaurant/routes/restaurant.ts')"
6384
<script src="https://cdn.jsdelivr.net/npm/@strapi/client"></script>
@@ -67,11 +88,16 @@ If you're using the Strapi Client in a browser environment, you can include it u
6788
</script>
6889
```
6990

91+
</TabItem>
92+
</Tabs>
93+
94+
The `baseURL` must include the protocol (`http` or `https`). An invalid URL will throw an error `StrapiInitializationError`.
95+
7096
### Authentication
7197

7298
The Strapi Client supports different authentication strategies to access protected resources in your Strapi back end.
7399

74-
If your Strapi instance uses API tokens, configure the Strapi Client as follows:
100+
If your Strapi instance uses [API tokens](/cms/features/api-tokens), configure the Strapi Client as follows:
75101

76102
```js
77103
const client = strapi({
@@ -81,6 +107,7 @@ const client = strapi({
81107
```
82108

83109
This allows your requests to include the necessary authentication credentials automatically.
110+
If the token is invalid or missing, the client will throw an error during initialization `StrapiValidationError`.
84111

85112
## API Reference
86113

@@ -92,6 +119,7 @@ The Strapi Client provides the following key properties and methods for interact
92119
| `fetch()` | A utility method for making generic API requests similar to the native fetch API. |
93120
| `collection()` | Manages collection-type resources (e.g., blog posts, products). |
94121
| `single()` | Manages single-type resources (e.g., homepage settings, global configurations). |
122+
| `files()` | Enables upload, retrieve and management of files directly to/from the Strapi Media Library. |
95123

96124
### General purpose fetch
97125

@@ -114,6 +142,9 @@ Collection types in Strapi are entities with multiple entries (e.g., a blog with
114142
| `delete(documentID, queryParams?)` | Update an existing document. |
115143

116144
**Usage examples:**
145+
<Tabs groupId="js-ts">
146+
<TabItem value="js" label="JavaScript">
147+
117148
```js
118149
const articles = client.collection('articles');
119150

@@ -136,14 +167,17 @@ const updatedArticle = await articles.update('article-document-id', { title: 'Up
136167
await articles.delete('article-id');
137168
```
138169

170+
</TabItem>
171+
</Tabs>
172+
139173
### Working with single types
140174

141175
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:
142176
| Parameter | Description |
143177
| ----------| -------------------------------------------------------------------------------------------- |
144178
| `find(queryParams?)` | Fetch the document. |
145179
| `update(documentID, data, queryParams?)` | Update the document. |
146-
| `delete(queryParams?) ` | Remove the document. |
180+
| `delete(queryParams?)` | Remove the document. |
147181

148182
**Usage examples:**
149183
```js
@@ -165,20 +199,25 @@ const updatedHomepage = await homepage.update(
165199
await homepage.delete();
166200
```
167201

168-
### Working with files <NewBadge />
202+
### Working with files
169203

170204
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.
171205

172-
The following methods are available for working with files:
206+
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:
173207

174208
| Method | Description |
175209
|--------|-------------|
176-
| `find(params?)` | Retrieves a list of file metadata based on optional query parameters |
177-
| `findOne(fileId)` | Retrieves the metadata for a single file by its ID |
178-
| `update(fileId, fileInfo)` | Updates metadata for an existing file |
179-
| `delete(fileId)` | Deletes a file by its ID |
210+
| [`find(params?)`](#find) | Retrieves a list of file metadata based on optional query parameters |
211+
| [`findOne(fileId)`](#findone) | Retrieves the metadata for a single file by its ID |
212+
| [`update(fileId, fileInfo)`](#update) | Updates metadata for an existing file |
213+
| [`upload(file, options)`](#upload) | Uploads a file (Blob or Buffer) with an optional `options` object for metadata |
214+
| [`delete(fileId)`](#delete) | Deletes a file by its ID |
180215

181-
**Usage examples:**
216+
#### `find`
217+
218+
The `strapi.client.files.find()` method retrieves a list of file metadata based on optional query parameters.
219+
220+
The method can be used as follows:
182221

183222
```js
184223
// Initialize the client
@@ -199,19 +238,192 @@ const imageFiles = await client.files.find({
199238
},
200239
sort: ['name:asc'], // Sort by name in ascending order
201240
});
241+
```
242+
243+
#### `findOne` {#findone}
244+
245+
The `strapi.client.files.findOne()` method retrieves the metadata for a single file by its id.
246+
247+
The method can be used as follows:
248+
249+
```js
250+
// Initialize the client
251+
const client = strapi({
252+
baseURL: 'http://localhost:1337/api',
253+
auth: 'your-api-token',
254+
});
202255

203256
// Find file metadata by ID
204257
const file = await client.files.findOne(1);
205-
console.log(file.name); // The file name
206-
console.log(file.url); // The file URL
258+
console.log(file.name);
259+
console.log(file.url);
207260
console.log(file.mime); // The file MIME type
261+
```
262+
263+
#### `update`
264+
265+
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.
266+
267+
The methods can be used as follows:
268+
269+
```js
270+
// Initialize the client
271+
const client = strapi({
272+
baseURL: 'http://localhost:1337/api',
273+
auth: 'your-api-token',
274+
});
208275

209276
// Update file metadata
210277
const updatedFile = await client.files.update(1, {
211278
name: 'New file name',
212279
alternativeText: 'Descriptive alt text for accessibility',
213280
caption: 'A caption for the file',
214281
});
282+
```
283+
284+
#### `upload` <NewBadge /> {#upload}
285+
286+
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.
287+
288+
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`.
289+
290+
##### Method Signature
291+
292+
```js
293+
async upload(file: Blob, options?: BlobUploadOptions): Promise<MediaUploadResponse>
294+
async upload(file: Buffer, options: BufferUploadOptions): Promise<MediaUploadResponse>
295+
```
296+
297+
- For `Blob` uploads, `options` is optional and may include `fileInfo` for metadata.
298+
- For `Buffer` uploads, `options` must include `filename` and `mimetype`, and may include `fileInfo`.
299+
300+
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).
301+
302+
<Tabs>
303+
<TabItem value="browser" label="Upload a file with the browser">
304+
305+
You can upload a file use through the browser as follows:
306+
307+
```js
308+
const client = strapi({ baseURL: 'http://localhost:1337/api' });
309+
310+
const fileInput = document.querySelector('input[type="file"]');
311+
const file = fileInput.files[0];
312+
313+
try {
314+
const result = await client.files.upload(file, {
315+
fileInfo: {
316+
alternativeText: 'A user uploaded image',
317+
caption: 'Uploaded via browser',
318+
},
319+
});
320+
console.log('Upload successful:', result);
321+
} catch (error) {
322+
console.error('Upload failed:', error);
323+
}
324+
```
325+
326+
</TabItem>
327+
328+
<TabItem value="node" label="Upload a file with Node.js">
329+
330+
With Node.js, you can either upload a blob or a buffer, as in the following examples:
331+
332+
<Tabs>
333+
<TabItem value="node-blob" label="Uploading a Blob">
334+
335+
```js
336+
import { readFile } from 'fs/promises';
337+
338+
const client = strapi({ baseURL: 'http://localhost:1337/api' });
339+
340+
const filePath = './image.png';
341+
const mimeType = 'image/png';
342+
const fileContentBuffer = await readFile(filePath);
343+
const fileBlob = new Blob([fileContentBuffer], { type: mimeType });
344+
345+
try {
346+
const result = await client.files.upload(fileBlob, {
347+
fileInfo: {
348+
name: 'Image uploaded as Blob',
349+
alternativeText: 'Uploaded from Node.js Blob',
350+
caption: 'Example upload',
351+
},
352+
});
353+
console.log('Blob upload successful:', result);
354+
} catch (error) {
355+
console.error('Blob upload failed:', error);
356+
}
357+
```
358+
359+
</TabItem>
360+
361+
<TabItem value="node-buffer" label="Uploading a Buffer">
362+
363+
```js
364+
import { readFile } from 'fs/promises';
365+
366+
const client = strapi({ baseURL: 'http://localhost:1337/api' });
367+
368+
const filePath = './image.png';
369+
const fileContentBuffer = await readFile(filePath);
370+
371+
try {
372+
const result = await client.files.upload(fileContentBuffer, {
373+
filename: 'image.png',
374+
mimetype: 'image/png',
375+
fileInfo: {
376+
name: 'Image uploaded as Buffer',
377+
alternativeText: 'Uploaded from Node.js Buffer',
378+
caption: 'Example upload',
379+
},
380+
});
381+
console.log('Buffer upload successful:', result);
382+
} catch (error) {
383+
console.error('Buffer upload failed:', error);
384+
}
385+
```
386+
387+
</TabItem>
388+
</Tabs>
389+
390+
</TabItem>
391+
</Tabs>
392+
393+
##### Response Structure
394+
395+
The `strapi.client.files.upload()` method returns an array of file objects, each with fields such as:
396+
397+
```json
398+
{
399+
"id": 1,
400+
"name": "image.png",
401+
"alternativeText": "Uploaded from Node.js Buffer",
402+
"caption": "Example upload",
403+
"mime": "image/png",
404+
"url": "/uploads/image.png",
405+
"size": 12345,
406+
"createdAt": "2025-07-23T12:34:56.789Z",
407+
"updatedAt": "2025-07-23T12:34:56.789Z"
408+
}
409+
```
410+
411+
:::note Additional response fields
412+
The upload response includes additional fields beyond those shown above. See the complete FileResponse interface in the <ExternalLink to="https://github.com/strapi/client/blob/main/src/files/types.ts" text="client source code"/> for all available fields.
413+
:::
414+
415+
#### `delete`
416+
417+
The `strapi.client.files.delete()` method deletes a file by its ID.
418+
419+
The method can be used as follows:
420+
421+
```js
422+
// Initialize the client
423+
const client = strapi({
424+
baseURL: 'http://localhost:1337/api',
425+
auth: 'your-api-token',
426+
});
215427

216428
// Delete a file by ID
217429
const deletedFile = await client.files.delete(1);
@@ -220,6 +432,19 @@ console.log('Deleted file ID:', deletedFile.id);
220432
console.log('Deleted file name:', deletedFile.name);
221433
```
222434

435+
<br/>
436+
437+
## Handling Common Errors
438+
439+
The following errors might occur when sending queries through the Strapi Client:
440+
441+
| Error | Description |
442+
|-------|-------------|
443+
| Permission Errors | If the authenticated user does not have permission to upload or manage files, a `FileForbiddenError` is thrown. |
444+
| HTTP Errors|If the server is unreachable, authentication fails, or there are network issues, an `HTTPError` is thrown. |
445+
| 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. |
446+
447+
223448
:::strapi Additional information
224-
More details about the Strapi Strapi Client might be found in the <ExternalLink to="https://github.com/strapi/client/blob/main/README.md" text="package's README"/>.
225-
:::
449+
More details about the Strapi Client may be found in the <ExternalLink to="https://github.com/strapi/client/blob/main/README.md" text="package's README"/>.
450+
:::

0 commit comments

Comments
 (0)