### Setup Demo Applications Source: https://github.com/strapi/client/blob/main/CONTRIBUTING.md Install dependencies, build, and set up the Strapi app for demo projects from the project's root directory. ```bash pnpm demo setup ``` -------------------------------- ### Setup Strapi App Environment File Source: https://github.com/strapi/client/blob/main/README.md Copies the example `.env.example` to `.env` for the main Strapi app if no `.env` file exists. Ensures appropriate environment configuration. ```bash pnpm demo app:env:setup ``` -------------------------------- ### Install Strapi Client with NPM Source: https://github.com/strapi/client/blob/main/README.md Install the Strapi client as a project dependency using NPM. ```bash npm install @strapi/client ``` -------------------------------- ### Install Strapi Client with pnpm Source: https://github.com/strapi/client/blob/main/README.md Install the Strapi client as a project dependency using pnpm. ```bash pnpm add @strapi/client ``` -------------------------------- ### Install Strapi Client with Yarn Source: https://github.com/strapi/client/blob/main/README.md Install the Strapi client as a project dependency using Yarn. ```bash yarn add @strapi/client ``` -------------------------------- ### Start Strapi App for Demos Source: https://github.com/strapi/client/blob/main/CONTRIBUTING.md Start the Strapi application which is used by the demo projects. This command should be run before testing individual demo applications. ```bash pnpm demo app:start ``` -------------------------------- ### Install Dependencies for Strapi App and Demos Source: https://github.com/strapi/client/blob/main/README.md Downloads and prepares all required packages for the main Strapi app and all demo applications. Ensures all necessary packages are installed. ```bash pnpm demo install ``` -------------------------------- ### Install Project Dependencies with pnpm Source: https://github.com/strapi/client/blob/main/CONTRIBUTING.md Install all necessary project dependencies using the pnpm package manager. ```bash pnpm install ``` -------------------------------- ### Full Query Parameters Example Source: https://github.com/strapi/client/blob/main/_autodocs/06-types.md Demonstrates a complete example of constructing BaseQueryParams for a Strapi client collection find request. Includes filters, field selection, population with nested fields, sorting, pagination with count, and locale. ```typescript const queryParams: BaseQueryParams = { filters: { status: 'published', category: { $in: ['tech', 'science'] }, createdAt: { $gte: '2024-01-01' } }, fields: ['title', 'excerpt', 'slug'], populate: { author: { fields: ['name', 'email'] }, comments: { fields: ['text', 'createdAt'], filters: { approved: true } } }, sort: ['createdAt:desc'], pagination: { page: 2, pageSize: 20, withCount: true }, locale: 'en' }; const articles = await client.collection('articles').find(queryParams); ``` -------------------------------- ### Example Strapi DocumentResponse Usage Source: https://github.com/strapi/client/blob/main/_autodocs/06-types.md Example demonstrating the structure of a `DocumentResponse` containing a custom `Article` type. Shows how to populate data and meta fields. ```typescript interface Article extends Document { title: string; content: string; published: boolean; } const response: DocumentResponse
= { data: { documentId: '123', title: 'Article Title', content: 'Content...', published: true, createdAt: '2024-01-01T00:00:00Z', updatedAt: '2024-01-02T00:00:00Z' }, meta: { pagination: { page: 1, pageSize: 10, pageCount: 1, total: 1 } } }; ``` -------------------------------- ### Strapi Client Invalid Configuration Examples Source: https://github.com/strapi/client/blob/main/_autodocs/11-configuration.md These examples demonstrate common configuration errors that will cause the Strapi client initialization to fail. Ensure baseURL is provided and valid, and auth is a non-empty string. ```typescript // Missing baseURL strapi({ auth: 'token' }); // Error: baseURL required ``` ```typescript // Invalid baseURL protocol strapi({ baseURL: 'ftp://api.example.com' }); // Error: must be HTTP/HTTPS ``` ```typescript // Invalid baseURL format strapi({ baseURL: 'not-a-url' }); // Error: invalid URL ``` ```typescript // Empty auth token strapi({ baseURL: 'https://api.example.com/api', auth: '' }); // Error: auth must be non-empty string ``` -------------------------------- ### Example Strapi DocumentResponseCollection Usage Source: https://github.com/strapi/client/blob/main/_autodocs/06-types.md Example demonstrating the structure of a `DocumentResponseCollection` containing multiple `Article` objects. Shows how to populate the data array and meta fields, including pagination. ```typescript const response: DocumentResponseCollection
= { data: [ { documentId: '123', title: 'First Article', content: '...', published: true, createdAt: '2024-01-01T00:00:00Z', updatedAt: '2024-01-02T00:00:00Z' }, { documentId: '124', title: 'Second Article', content: '...', published: false, createdAt: '2024-01-03T00:00:00Z', updatedAt: '2024-01-04T00:00:00Z' } ], meta: { pagination: { page: 1, pageSize: 10, pageCount: 5, total: 42 } } }; ``` -------------------------------- ### Plugin Route Example Source: https://github.com/strapi/client/blob/main/_autodocs/13-endpoints.md Demonstrates how to interact with content types managed by a plugin, where routes are prefixed with the plugin's name. ```APIDOC ## Plugin Content Type Interaction ### Description Access content types managed by plugins. The API endpoint will be prefixed with the plugin name. ### Example For a 'posts' collection within a 'blog' plugin, requests are made to `/blog/posts`. ### Code Example ```typescript const posts = client.collection('posts', { plugin: { name: 'blog' } }); // This client instance will make requests to the /blog/posts endpoint. ``` ``` -------------------------------- ### Example Commit Message Source: https://github.com/strapi/client/blob/main/CONTRIBUTING.md An example of a commit message following the Conventional Commits specification. ```text feat: added a new example feature ``` -------------------------------- ### Run Development Server in Next.js Source: https://github.com/strapi/client/blob/main/demo/next-server-components/README.md Use these commands to start the Next.js development server. Open http://localhost:3000 in your browser to view the application. ```bash npm run dev # or yarn dev # or pnpm dev # or bun dev ``` -------------------------------- ### baseURL Usage Example Source: https://github.com/strapi/client/blob/main/_autodocs/02-strapi-client.md Logs the configured base URL of the Strapi client to the console. ```typescript console.log(client.baseURL); // 'https://api.example.com/api' ``` -------------------------------- ### get() Source: https://github.com/strapi/client/blob/main/_autodocs/08-http-client.md Sends an HTTP GET request to the specified path. ```APIDOC ## get(path: string, init?: RequestInit) ### Description Sends a GET request. ### Method `GET` ### Endpoint `/{path}` ### Parameters #### Path Parameters - **path** (`string`) - Required - Relative URL path #### Query Parameters None #### Request Body None #### Parameters - **init** (`RequestInit`) - Optional - Additional fetch options #### Returns `Promise` — The HTTP response #### Example ```typescript const response = await httpClient.get('/articles'); const articles = await response.json(); ``` ``` -------------------------------- ### Example: Using Custom Headers for Requests Source: https://github.com/strapi/client/blob/main/README.md Demonstrates initializing the client with custom headers and making a request. The specified headers will be automatically included in the 'articles.find()' call. ```typescript // Initialize client with custom headers const client = strapi({ baseURL: 'http://localhost:1337/api', headers: { 'X-Request-ID': '12345', 'Accept-Language': 'en-US', }, }); // Headers will be included in all requests const articles = await client.collection('articles').find(); ``` -------------------------------- ### FilesManager Usage Example Source: https://github.com/strapi/client/blob/main/_autodocs/02-strapi-client.md Demonstrates how to use the files property to find all files or a single file by its ID. ```typescript const fileList = await client.files.find(); const singleFile = await client.files.findOne(1); ``` -------------------------------- ### Make a GET Request Source: https://github.com/strapi/client/blob/main/_autodocs/08-http-client.md Sends a GET request to a specified path. Useful for retrieving resources. ```typescript const response = await httpClient.get('/articles'); const articles = await response.json(); ``` -------------------------------- ### Check Node.js Version Source: https://github.com/strapi/client/blob/main/CONTRIBUTING.md Use this command to verify your installed Node.js version. Ensure it meets the project's requirements. ```bash node -v ``` -------------------------------- ### Strapi Client Initialization with API Token (Constructor) Source: https://github.com/strapi/client/blob/main/_autodocs/09-auth.md Example of initializing the Strapi client using the StrapiClient constructor with an API token. The token is provided within the auth object, specifying the 'api-token' strategy and its options. ```typescript const client = new StrapiClient({ baseURL: 'https://api.example.com/api', auth: { strategy: 'api-token', options: { token: 'your-api-token-here' } } }); ``` -------------------------------- ### Check pnpm Version Source: https://github.com/strapi/client/blob/main/CONTRIBUTING.md Verify that pnpm is installed and accessible in your environment. This is the required package manager for the project. ```bash pnpm -v ``` -------------------------------- ### Handle FileForbiddenError Source: https://github.com/strapi/client/blob/main/_autodocs/07-errors.md Example of how to catch and handle a FileForbiddenError when attempting an operation without the necessary permissions. ```typescript try { await client.files.delete(5); } catch (error) { if (error instanceof FileForbiddenError) { console.error('No permission to delete this file'); } } ``` -------------------------------- ### Strapi Client Debug Output Example Source: https://github.com/strapi/client/blob/main/_autodocs/11-configuration.md Observe detailed console logs during Strapi client initialization when the DEBUG environment variable is set. This output helps in understanding the client's internal processes. ```typescript import { strapi } from '@strapi/client'; // With DEBUG=strapi:* environment variable set: const client = strapi({ baseURL: 'http://localhost:1337/api', auth: 'token-123' }); // Console output: // strapi:core started the initialization process +0ms // strapi:validators:config validating the configuration +1ms // strapi:core user config passed the preflight validation +2ms // strapi:http initializing new client with base url: "http://localhost:1337/api" +1ms // strapi:core init modules +0ms // strapi:core init http module +0ms // strapi:core init auth module +0ms // strapi:auth:manager initializing a new auth manager +1ms // strapi:auth:provider:api-token validating provider configuration +0ms // strapi:core finished the client initialization process +1ms ``` -------------------------------- ### Initialize Strapi Client Source: https://github.com/strapi/client/blob/main/README.md Initialize the Strapi client with the base URL of your Strapi API. This is the basic configuration required to start interacting with your backend. ```typescript import { strapi } from '@strapi/client'; const client = strapi({ baseURL: 'http://localhost:1337/api' }); ``` -------------------------------- ### Limit Pagination Configuration Source: https://github.com/strapi/client/blob/main/_autodocs/13-endpoints.md Use this configuration for limit-based pagination, specifying the 0-based starting index and the maximum number of items to return. ```typescript pagination: { start: 0, limit: 10 } ``` -------------------------------- ### Unit Test Structure Example Source: https://github.com/strapi/client/blob/main/CONTRIBUTING.md A template for writing unit tests in TypeScript using Jest. Follows the Arrange-Act-Assert pattern for clarity and maintainability. ```typescript // example.test.ts import { ExampleClass } from '../src/example'; describe('Example Class', () => { it('should return the expected result when calling action', () => { // Arrange const input = 'inputValue'; const expected = 'smth'; const instance = new ExampleClass(); const spy = jest.spyOn(instance, 'sideEffect'); // Act const result = instance.action(input); // Assert expect(result).toBe(expected); expect(spy).toHaveBeenCalledWith(input); }); }); ``` -------------------------------- ### Integrate React-X and React-DOM ESLint Plugins Source: https://github.com/strapi/client/blob/main/demo/react-vite/README.md Install and configure eslint-plugin-react-x and eslint-plugin-react-dom for React-specific linting rules. Enable their recommended TypeScript rules. ```javascript // eslint.config.js import reactX from 'eslint-plugin-react-x'; import reactDom from 'eslint-plugin-react-dom'; export default tseslint.config({ plugins: { // Add the react-x and react-dom plugins 'react-x': reactX, 'react-dom': reactDom, }, rules: { // other rules... // Enable its recommended typescript rules ...reactX.configs['recommended-typescript'].rules, ...reactDom.configs.recommended.rules, }, }); ``` -------------------------------- ### Define Custom Document Type and Client Usage Source: https://github.com/strapi/client/blob/main/_autodocs/06-types.md Example of defining a custom document type 'BlogPost' extending the base 'Document' type and then using it with the Strapi client to fetch articles. ```typescript import type { Document } from '@strapi/client'; interface BlogPost extends Document { title: string; slug: string; content: string; excerpt: string; published: boolean; publishedAt?: string; author: { id: number; name: string; email: string; }; categories: Array<{ id: number; name: string; }>; } // Use with the client const response = await client .collection<'articles'>('articles') .find(); const posts: BlogPost[] = response.data; ``` -------------------------------- ### Authorization Header Example Source: https://github.com/strapi/client/blob/main/_autodocs/13-endpoints.md Requests can be authenticated using an 'Authorization' header with a Bearer token. The client automatically adds this header if configured with 'auth: "token"'. ```text Authorization: Bearer {api-token} ``` -------------------------------- ### Manage Single Resources with Strapi Client Source: https://github.com/strapi/client/blob/main/README.md Use the `.single()` method to get a manager for single-type resources. This manager supports finding, updating, and deleting the single document. You can specify a locale to fetch or update specific language versions. ```typescript const homepage = client.single('homepage'); // Fetch the default version of the homepage const defaultHomepage = await homepage.find(); // Fetch the spanish version of the homepage const spanishHomepage = await homepage.find({ locale: 'es' }); // Update the homepage draft content const updatedHomepage = await homepage.update( { title: 'Updated Homepage Title' }, { status: 'draft' } ); // Delete the homepage content await homepage.delete(); ``` ```typescript const homepage = client.single('homepage', { path: '/my-custom-path' }); ``` -------------------------------- ### Initialize and Use Strapi Client Source: https://github.com/strapi/client/blob/main/_autodocs/README.md Demonstrates how to initialize the Strapi client with authentication and make a basic query to a collection type. Ensure the baseURL and auth token are correctly configured. ```typescript // Initialize const client = strapi({ baseURL: 'https://api.example.com/api', auth: 'api-token' }); // Use const articles = await client.collection('articles').find({ filters: { status: 'published' }, pagination: { pageSize: 20 } }); ``` -------------------------------- ### Client Initialization Source: https://github.com/strapi/client/blob/main/_autodocs/12-quick-reference.md Demonstrates how to initialize the Strapi client with different configurations, including base URL, authentication tokens, and custom headers. ```APIDOC ## Client Initialization ### Description Initialize the Strapi client with various options. ### Usage ```typescript import { strapi } from '@strapi/client'; // Basic initialization const client = strapi({ baseURL: 'http://localhost:1337/api' }); // Initialization with an API token const clientWithToken = strapi({ baseURL: 'https://api.example.com/api', auth: 'api-token-here' }); // Initialization with custom headers const clientWithHeaders = strapi({ baseURL: 'https://api.example.com/api', auth: 'token', headers: { 'Accept-Language': 'en-US' } }); ``` ``` -------------------------------- ### Build Strapi Client Project Source: https://github.com/strapi/client/blob/main/CONTRIBUTING.md Run this command to compile the source code of the Strapi Client project. ```bash pnpm build ``` -------------------------------- ### Create Strapi Client with Valid Configuration Source: https://github.com/strapi/client/blob/main/_autodocs/11-configuration.md Use this to successfully initialize the Strapi client with all required configuration parameters. ```typescript const client = strapi({ baseURL: 'https://api.example.com/api', auth: 'abc123def456', headers: { 'X-Custom': 'value' } }); // Successfully created ``` -------------------------------- ### Build Strapi App and Demo Projects Source: https://github.com/strapi/client/blob/main/README.md Compiles the main Strapi app and all demo projects, preparing them for use. Ensures all components are compiled and ready. ```bash pnpm demo build ``` -------------------------------- ### GET /upload/files/{id} Source: https://github.com/strapi/client/blob/main/_autodocs/13-endpoints.md Retrieves a single file by its unique identifier. ```APIDOC ## GET /upload/files/{id} ### Description Retrieves a single file by ID. ### Method GET ### Endpoint /upload/files/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the file to retrieve. ### Response #### Success Response (200 OK) - **id** (integer) - Unique identifier for the file. - **documentId** (string) - Identifier for the document associated with the file. - **name** (string) - The name of the file. - **url** (string) - The URL path to the file. - **mime** (string) - The MIME type of the file. - **size** (integer) - The size of the file in bytes. - **width** (integer) - The width of the image in pixels (if applicable). - **height** (integer) - The height of the image in pixels (if applicable). - **hash** (string) - A hash of the file content. - **ext** (string) - The file extension. - **provider** (string) - The storage provider used. - **previewUrl** (string) - URL for a thumbnail or preview of the file. - **createdAt** (string) - Timestamp of file creation. - **updatedAt** (string) - Timestamp of last file update. ### Response Example ```json { "id": 1, "documentId": "file-doc-id", "name": "image.jpg", "url": "/uploads/abc123.jpg", "mime": "image/jpeg", "size": 50000, "width": 1280, "height": 720, "hash": "abc123", "ext": ".jpg", "provider": "local", "previewUrl": "/uploads/thumbs/abc123.jpg", "createdAt": "2024-01-01T00:00:00Z", "updatedAt": "2024-01-02T00:00:00Z" } ``` ### Error Responses - 404 Not Found — File doesn't exist - 500 Internal Server Error — Server error ``` -------------------------------- ### Fetch All Documents Source: https://github.com/strapi/client/blob/main/_autodocs/03-collection-manager.md Retrieve all documents from a collection. Use this to get a list of all entries. ```typescript const articles = client.collection('articles'); const result = await articles.find(); console.log(result.data); // Array of articles console.log(result.meta.pagination); // Pagination metadata ``` -------------------------------- ### Initialize Strapi Client Source: https://github.com/strapi/client/blob/main/_autodocs/12-quick-reference.md Instantiate the Strapi client with different configuration options, including base URL, authentication token, and custom headers. ```typescript import { strapi } from '@strapi/client'; // Basic const client = strapi({ baseURL: 'http://localhost:1337/api' }); ``` ```typescript // With token const client = strapi({ baseURL: 'https://api.example.com/api', auth: 'api-token-here' }); ``` ```typescript // With custom headers const client = strapi({ baseURL: 'https://api.example.com/api', auth: 'token', headers: { 'Accept-Language': 'en-US' } }); ``` -------------------------------- ### Initialize Strapi Client in Browser Source: https://github.com/strapi/client/blob/main/README.md Initialize the Strapi client in a browser environment using a script tag. Ensure the CDN URL is correct for your needs. ```html ``` -------------------------------- ### Handle URLParsingError Source: https://github.com/strapi/client/blob/main/_autodocs/07-errors.md Example of catching a URLParsingError when initializing the Strapi client with an invalid URL. ```typescript try { const client = strapi({ baseURL: 'not-a-url' }); } catch (error) { if (error instanceof URLParsingError) { console.error('Invalid URL provided'); } } ``` -------------------------------- ### Instantiate HttpClient with Configuration Source: https://github.com/strapi/client/blob/main/_autodocs/08-http-client.md Create an instance of the HttpClient by providing a configuration object. This object specifies the base URL, optional timeout, and default headers for all requests. Ensure the baseURL is a valid HTTP/HTTPS URL. ```typescript const httpClient = new HttpClient({ baseURL: 'https://api.example.com/api', timeout: 5000, headers: { 'X-Custom-Header': 'value' } }); ``` -------------------------------- ### Handle FileNotFoundError Source: https://github.com/strapi/client/blob/main/_autodocs/07-errors.md Example of how to catch and handle a FileNotFoundError when attempting to access a file that does not exist. ```typescript try { const file = await client.files.findOne(999); } catch (error) { if (error instanceof FileNotFoundError) { console.error(`File ${error.fileId} does not exist`); } } ``` -------------------------------- ### Validate Configuration at Startup Source: https://github.com/strapi/client/blob/main/_autodocs/11-configuration.md Implement configuration validation at the application's startup to catch potential issues early. This ensures the client is initialized with valid parameters before proceeding. ```typescript try { const client = strapi({ baseURL: process.env.STRAPI_API_URL, auth: process.env.STRAPI_API_TOKEN }); console.log('Client initialized successfully'); } catch (error) { console.error('Failed to initialize client:', error); process.exit(1); // Exit if critical } ``` -------------------------------- ### GET /upload/files Source: https://github.com/strapi/client/blob/main/_autodocs/13-endpoints.md Retrieves a list of all uploaded files. Supports filtering and sorting through query parameters. ```APIDOC ## GET /upload/files ### Description Retrieves a list of files. ### Method GET ### Endpoint /upload/files ### Parameters #### Query Parameters - **filters** (object) - Optional - Filters to apply to the file list. - **sort** (string) - Optional - Sorting order for the file list. ### Response #### Success Response (200 OK) - **id** (integer) - Unique identifier for the file. - **documentId** (string) - Identifier for the document associated with the file. - **name** (string) - The name of the file. - **url** (string) - The URL path to the file. - **mime** (string) - The MIME type of the file. - **size** (integer) - The size of the file in bytes. - **width** (integer) - The width of the image in pixels (if applicable). - **height** (integer) - The height of the image in pixels (if applicable). - **hash** (string) - A hash of the file content. - **ext** (string) - The file extension. - **provider** (string) - The storage provider used. - **previewUrl** (string) - URL for a thumbnail or preview of the file. - **createdAt** (string) - Timestamp of file creation. - **updatedAt** (string) - Timestamp of last file update. ### Response Example ```json [ { "id": 1, "documentId": "file-doc-id", "name": "image.jpg", "url": "/uploads/abc123.jpg", "mime": "image/jpeg", "size": 50000, "width": 1280, "height": 720, "hash": "abc123", "ext": ".jpg", "provider": "local", "previewUrl": "/uploads/thumbs/abc123.jpg", "createdAt": "2024-01-01T00:00:00Z", "updatedAt": "2024-01-02T00:00:00Z" } ] ``` ### Error Responses - 403 Forbidden — Insufficient permissions - 500 Internal Server Error — Server error ``` -------------------------------- ### GET /resource-name Source: https://github.com/strapi/client/blob/main/_autodocs/13-endpoints.md Retrieves the single-type document. This endpoint allows fetching the content of a unique resource. ```APIDOC ## GET /resource-name ### Description Retrieves the single-type document. ### Method GET ### Endpoint `/{resourceName}` ### Parameters #### Query Parameters - **fields** (string) - Optional - Comma-separated list of fields to include in the response. - **populate** (string) - Optional - Comma-separated list of relations to populate. - **locale** (string) - Optional - The locale of the content to retrieve. - **status** (string) - Optional - The status of the content to retrieve (e.g., 'draft', 'published'). ### Response #### Success Response (200 OK) - **data** (object) - The single-type document content. - **documentId** (string) - The unique identifier of the document. - **title** (string) - The title of the document. - **description** (string) - The description of the document. - **createdAt** (string) - The creation timestamp. - **updatedAt** (string) - The last update timestamp. - **meta** (object) - Metadata about the response. ### Response Example ```json { "data": { "documentId": "single-doc-id", "title": "Homepage Title", "description": "...", "createdAt": "2024-01-01T00:00:00Z", "updatedAt": "2024-01-02T00:00:00Z" }, "meta": {} } ``` ### Error Responses - 400 Bad Request — Invalid query parameters - 401 Unauthorized — Authentication required - 403 Forbidden — Insufficient permissions - 404 Not Found — Single-type document doesn't exist - 500 Internal Server Error — Server error ``` -------------------------------- ### Production Build Check Source: https://github.com/strapi/client/blob/main/CONTRIBUTING.md Check the production build process by cleaning and building the project. ```bash NODE_ENV=production pnpm build:clean ``` -------------------------------- ### Configure Strapi Client with Direct Constructor Source: https://github.com/strapi/client/blob/main/_autodocs/11-configuration.md For advanced configuration, use the `StrapiClient` constructor directly. Specify the `baseURL`, and optionally configure `auth` with a `strategy` and `options`, or provide custom `headers`. ```typescript const client = new StrapiClient({ baseURL: string, auth?: { strategy: string, options?: unknown }, headers?: Record }); ``` -------------------------------- ### Handling StrapiValidationError Source: https://github.com/strapi/client/blob/main/_autodocs/07-errors.md Catches and logs configuration validation errors. This is useful for debugging invalid client setup. ```typescript try { const client = strapi({ baseURL: 'ftp://invalid.com/api', // Invalid protocol auth: '' // Empty token }); } catch (error) { if (error instanceof StrapiValidationError) { console.error('Config validation failed:', error.message); } } ``` -------------------------------- ### Client Initialization Source: https://github.com/strapi/client/blob/main/_autodocs/INDEX.md Initialize the Strapi client with your API endpoint and authentication token. ```APIDOC ## Client Initialization ### Description Initialize the Strapi client with your API endpoint and authentication token. ### Method ```typescript strapi({ baseURL: string, auth: string }) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { strapi } from '@strapi/client'; const client = strapi({ baseURL: 'https://api.example.com/api', auth: 'your-api-token' }); ``` ### Response #### Success Response (200) Returns an initialized Strapi client instance. #### Response Example ```json { "client": "StrapiClientInstance" } ``` ``` -------------------------------- ### GET /resource-name/{documentId} Source: https://github.com/strapi/client/blob/main/_autodocs/13-endpoints.md Retrieves a single document by its ID. Supports field selection, population, locale, and status. ```APIDOC ## GET /resource-name/{documentId} ### Description Retrieves a single document by ID. ### Method GET ### Endpoint `/{resourceName}/{documentId}` ### Parameters #### Path Parameters - **documentId** (string) - Required - The ID of the document to retrieve. #### Query Parameters - **fields** (array) - Optional - Fields to include in the response. - **populate** (array) - Optional - Relations to populate. - **locale** (string) - Optional - Locale for the entry. - **status** (string) - Optional - Status of the entry (e.g., `published`, `draft`). ### Response #### Success Response (200 OK) - **data** (object) - The requested document. - **documentId** (string) - The unique identifier of the document. - **title** (string) - The title of the document. - **content** (string) - The content of the document. - **createdAt** (string) - The creation timestamp. - **updatedAt** (string) - The last update timestamp. - **meta** (object) - Metadata about the response. ### Response Example ```json { "data": { "documentId": "123", "title": "Article Title", "content": "...", "createdAt": "2024-01-01T00:00:00Z", "updatedAt": "2024-01-02T00:00:00Z" }, "meta": {} } ``` ### Error Responses - 400 Bad Request — Invalid query parameters - 401 Unauthorized — Authentication required - 403 Forbidden — Insufficient permissions - 404 Not Found — Document doesn't exist - 500 Internal Server Error — Server error ``` -------------------------------- ### Seed Strapi Demo App Database Source: https://github.com/strapi/client/blob/main/README.md Populates the Strapi app with sample data. Use this to add default content. ```bash pnpm demo app:seed ``` -------------------------------- ### Handling StrapiInitializationError Source: https://github.com/strapi/client/blob/main/_autodocs/07-errors.md Catches and logs errors that occur during Strapi client initialization. This helps diagnose setup issues. ```typescript try { const client = new StrapiClient({ baseURL: 'invalid-url', auth: { strategy: 'unknown-strategy', options: {} } }); } catch (error) { if (error instanceof StrapiInitializationError) { console.error('Failed to initialize client:', error.message); console.error('Cause:', error.cause); } } ``` -------------------------------- ### Retrieve a List of Files Source: https://github.com/strapi/client/blob/main/_autodocs/13-endpoints.md Use this to get a list of all uploaded files. Supports filtering and sorting via query parameters. ```typescript await client.files.find(queryParams) ``` -------------------------------- ### Fetch Single Document by ID Source: https://github.com/strapi/client/blob/main/_autodocs/03-collection-manager.md Retrieve a single document using its unique identifier. Use this to get a specific entry. ```typescript const article = await articlesManager.findOne('article-123'); console.log(article.data.title); ``` -------------------------------- ### Run All Unit Tests Source: https://github.com/strapi/client/blob/main/CONTRIBUTING.md Execute all unit tests in the project using pnpm. This command is the standard way to verify code changes. ```bash pnpm test ``` -------------------------------- ### GET /resource-name Source: https://github.com/strapi/client/blob/main/_autodocs/13-endpoints.md Retrieves multiple documents from a collection. Supports filtering, field selection, population, sorting, pagination, locale, and status. ```APIDOC ## GET /resource-name ### Description Retrieves multiple documents from a collection. ### Method GET ### Endpoint `/{resourceName}` ### Parameters #### Query Parameters - **filters** (object) - Optional - Filters to apply to the query. - **fields** (array) - Optional - Fields to include in the response. - **populate** (array) - Optional - Relations to populate. - **sort** (array) - Optional - Fields to sort by. - **pagination** (object) - Optional - Pagination parameters. - **locale** (string) - Optional - Locale for the entries. - **status** (string) - Optional - Status of the entries (e.g., `published`, `draft`). ### Response #### Success Response (200 OK) - **data** (array) - An array of documents. - **documentId** (string) - The unique identifier of the document. - **title** (string) - The title of the document. - **content** (string) - The content of the document. - **createdAt** (string) - The creation timestamp. - **updatedAt** (string) - The last update timestamp. - **meta** (object) - Metadata about the response, including pagination. - **pagination** (object) - Pagination details. - **page** (number) - Current page number. - **pageSize** (number) - Number of items per page. - **pageCount** (number) - Total number of pages. - **total** (number) - Total number of items. ### Response Example ```json { "data": [ { "documentId": "123", "title": "Article Title", "content": "...", "createdAt": "2024-01-01T00:00:00Z", "updatedAt": "2024-01-02T00:00:00Z" } ], "meta": { "pagination": { "page": 1, "pageSize": 10, "pageCount": 5, "total": 42 } } } ``` ### Error Responses - 400 Bad Request — Invalid query parameters - 401 Unauthorized — Missing or invalid authentication - 403 Forbidden — Insufficient permissions - 500 Internal Server Error — Server error ``` -------------------------------- ### create() Source: https://github.com/strapi/client/blob/main/_autodocs/08-http-client.md Creates a clone of the HTTP client with optional interceptor filtering and configuration overrides. ```APIDOC ## create() ### Description Creates a clone of the HTTP client with optional interceptor filtering. ### Method Signature ```typescript public create( baseConfig?: Partial, includeInterceptors?: boolean ): HttpClient ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **baseConfig** (`Partial`) - Optional - Configuration overrides for the new client. - **includeInterceptors** (`boolean`) - Optional - Defaults to `true`. Whether to include interceptors from the original client. ### Returns `HttpClient` — A new HttpClient instance ### Example ```typescript // Clone with same config and interceptors const cloned = httpClient.create(); // Clone with modified config, no interceptors const cleanClient = httpClient.create( { baseURL: 'https://other-api.example.com' }, false ); ``` ## Type Definitions ### HttpClientConfig Configuration for the HTTP client. ```typescript interface HttpClientConfig { baseURL: string; timeout?: number; headers?: Record; } ``` | Property | Type | Required | Default | Description | |---|---|---|---|---| | baseURL | `string` | Yes | — | Base URL for requests | | timeout | `number` | No | 30000 | Request timeout in ms | | headers | `Record` | No | — | Default headers | ### InterceptorManagerMap Container for request and response interceptor managers. ```typescript interface InterceptorManagerMap { request: RequestInterceptorManager; response: ResponseInterceptorManager; } ``` ### RequestInterceptorPayload Payload passed to request interceptors. ```typescript type RequestInterceptorPayload = { request: Request } ``` ### ResponseInterceptorPayload Payload passed to response interceptors. ```typescript type ResponseInterceptorPayload = { response: Response; request: Request } ``` ``` -------------------------------- ### Get HTTP Client Timeout Source: https://github.com/strapi/client/blob/main/_autodocs/08-http-client.md Retrieves the current request timeout value in milliseconds. Useful for understanding request timing constraints. ```typescript console.log(httpClient.timeout); // 5000 ``` -------------------------------- ### Advanced Strapi Client Configuration with Direct Constructor Source: https://github.com/strapi/client/blob/main/_autodocs/11-configuration.md Use the direct constructor for advanced configuration, including custom authentication strategies like 'api-token' with specific options. ```typescript import { StrapiClient } from '@strapi/client'; const client = new StrapiClient({ baseURL: 'https://api.example.com/api', auth: { strategy: 'api-token', options: { token: 'my-api-token' } }, headers: { 'X-API-Version': 'v1' } }); ``` -------------------------------- ### Basic Strapi Client Initialization Source: https://github.com/strapi/client/blob/main/_autodocs/01-client-factory.md Initializes the Strapi client with the required baseURL. Ensure the baseURL is a valid HTTP or HTTPS URL. ```typescript import { strapi } from '@strapi/client'; const client = strapi({ baseURL: 'http://localhost:1337/api' }); ``` -------------------------------- ### Get HTTP Client Headers Source: https://github.com/strapi/client/blob/main/_autodocs/08-http-client.md Retrieves the current default headers set for the HTTP client. Useful for inspecting or verifying default headers. ```typescript console.log(httpClient.headers); // { 'X-Custom-Header': 'value' } ``` -------------------------------- ### Users Collection Operations Source: https://github.com/strapi/client/blob/main/_autodocs/12-quick-reference.md Provides examples for performing CRUD operations on the 'users' collection, including creating, finding, updating, and deleting users. ```APIDOC ## Users Collection ```typescript // Users are automatically detected as users-permissions plugin const users = client.collection('users'); // Create user const user = await users.create({ username: 'john', email: 'john@example.com', password: 'SecurePass123!', role: 1 }); // Find users const allUsers = await users.find(); // Find by numeric ID (users-permissions accepts both string and numeric IDs) const userById = await users.findOne(123); // Update user const updated = await users.update(123, { username: 'jane' }); // Delete user await users.delete(123); ``` ``` -------------------------------- ### Include Strapi Client in Browser Source: https://github.com/strapi/client/blob/main/_autodocs/INDEX.md This snippet shows how to include the Strapi client using a CDN and initialize it for use in a web browser. Ensure your project supports the fetch API. ```html ``` -------------------------------- ### Watch for Changes and Rebuild Strapi Client Project Source: https://github.com/strapi/client/blob/main/CONTRIBUTING.md Execute this command to automatically rebuild the project whenever changes are detected in the `src` folder. ```bash pnpm watch ``` -------------------------------- ### Initialize Strapi Client Source: https://github.com/strapi/client/blob/main/_autodocs/INDEX.md Import and initialize the Strapi client with your API endpoint and authentication token. This is the first step before making any requests. ```typescript import { strapi } from '@strapi/client'; const client = strapi({ baseURL: 'https://api.example.com/api', auth: 'your-api-token' }); ``` -------------------------------- ### Strapi Client in Node.js Source: https://github.com/strapi/client/blob/main/_autodocs/12-quick-reference.md Import and initialize the Strapi client using environment variables for the base URL and authentication token. ```javascript import { strapi } from '@strapi/client'; const client = strapi({ baseURL: process.env.STRAPI_URL, auth: process.env.STRAPI_TOKEN }); async function main() { const articles = await client.collection('articles').find(); console.log(articles); } main().catch(console.error); ``` -------------------------------- ### Run Linting Source: https://github.com/strapi/client/blob/main/CONTRIBUTING.md Execute the linting command to fix code style issues. ```bash pnpm lint:fix ``` -------------------------------- ### Get Current Authentication Strategy Source: https://github.com/strapi/client/blob/main/_autodocs/09-auth.md Read-only getter for the currently active authentication strategy. Returns the strategy name as a string or undefined if no strategy is set. ```typescript public get strategy(): string | undefined ``` ```typescript authManager.strategy; // 'api-token' or undefined ``` -------------------------------- ### Fetch All Files Source: https://github.com/strapi/client/blob/main/_autodocs/05-files-manager.md Retrieve all files from the Media Library. Access the 'name' and 'url' properties from the returned file objects. ```typescript const client = strapi({ baseURL: 'http://localhost:1337/api' }); const allFiles = await client.files.find(); console.log(allFiles[0].name); // File name console.log(allFiles[0].url); // File URL ``` -------------------------------- ### Get HTTP Client Base URL Source: https://github.com/strapi/client/blob/main/_autodocs/08-http-client.md Retrieves the current base URL configured for the HTTP client. Useful for debugging or dynamic URL construction. ```typescript console.log(httpClient.baseURL); // 'https://api.example.com/api' ``` -------------------------------- ### Configure Strapi Client with Factory Function Source: https://github.com/strapi/client/blob/main/_autodocs/11-configuration.md Use the `strapi()` factory function for recommended client configuration. Ensure `baseURL` is a valid HTTP/HTTPS URL. The `auth` option accepts an API token for Bearer authentication, and `headers` can include custom HTTP headers. ```typescript const client = strapi({ baseURL: string, auth?: string, headers?: Record }); ``` -------------------------------- ### Fetch Single Document with Populate Source: https://github.com/strapi/client/blob/main/_autodocs/03-collection-manager.md Retrieve a single document and populate its relations with specific fields. Use this to get detailed information about a single entry and its related data. ```typescript const articleWithComments = await articlesManager.findOne('article-123', { populate: { comments: true, author: { fields: ['name', 'email'] } } }); ``` -------------------------------- ### Check Code Formatting Source: https://github.com/strapi/client/blob/main/CONTRIBUTING.md Verify if the code adheres to Prettier formatting rules by running this command. ```bash pnpm format:check ``` -------------------------------- ### Clone Strapi Client Repository with Git Source: https://github.com/strapi/client/blob/main/CONTRIBUTING.md Use this command to clone the Strapi Client repository using the standard Git command-line tool. ```bash git clone https://github.com/strapi/client.git cd client ``` -------------------------------- ### Combined Filtering and Sorting Source: https://github.com/strapi/client/blob/main/_autodocs/05-files-manager.md Apply both filtering and sorting to retrieve specific files. This example fetches image files containing 'avatar' in their name, sorted by creation date descending. ```typescript const imageFiles = await client.files.find({ filters: { mime: { $contains: 'image' }, name: { $contains: 'avatar' } }, sort: 'createdAt:desc' }); ``` -------------------------------- ### Strapi Client Configuration with Environment Variables Source: https://github.com/strapi/client/blob/main/_autodocs/11-configuration.md Configure the Strapi client using environment variables for baseURL, API token, and custom headers. This promotes secure and flexible configuration. ```typescript import { strapi } from '@strapi/client'; const client = strapi({ baseURL: process.env.STRAPI_API_URL || 'http://localhost:1337/api', auth: process.env.STRAPI_API_TOKEN, headers: process.env.CUSTOM_HEADERS ? JSON.parse(process.env.CUSTOM_HEADERS) : undefined }); ``` -------------------------------- ### Mock Flaky URL Validator Source: https://github.com/strapi/client/blob/main/CONTRIBUTING.md An example of a mock class extending a base validator, designed to simulate unexpected errors during validation. Useful for testing error handling scenarios. ```typescript import { URLValidator } from '../../../src/validators'; /** * Class representing a FlakyURLValidator which extends URLValidator. * * This validator is designed to throw an error unexpectedly upon validation and should only be used in test suites. */ export class MockFlakyURLValidator extends URLValidator { validate() { throw new Error('Unexpected error'); } } ``` -------------------------------- ### Format Code Source: https://github.com/strapi/client/blob/main/CONTRIBUTING.md Run the code formatting command to ensure consistent code style. ```bash pnpm format:write ``` -------------------------------- ### StrapiClient Constructor Source: https://github.com/strapi/client/blob/main/_autodocs/02-strapi-client.md Initializes a new instance of the StrapiClient. It requires a configuration object and optionally accepts a validator, authentication manager, and an HTTP client factory for advanced customization. ```APIDOC ## StrapiClient Constructor ### Description Initializes a new instance of the StrapiClient. It requires a configuration object and optionally accepts a validator, authentication manager, and an HTTP client factory for advanced customization. ### Parameters #### Parameters - **config** (`StrapiClientConfig`) - Required - Client configuration including baseURL and optional auth settings - **validator** (`StrapiConfigValidator`) - Optional - Validator instance for configuration validation (internal dependency injection) - **authManager** (`AuthManager`) - Optional - Authentication manager for handling auth strategies (internal dependency injection) - **httpClientFactory** (`(config) => HttpClient`) - Optional - Optional factory function to create the HTTP client (for advanced use) ### Throws - **StrapiInitializationError** — If configuration validation fails or auth setup fails ``` -------------------------------- ### Pagination loop Source: https://github.com/strapi/client/blob/main/_autodocs/12-quick-reference.md Demonstrates how to paginate through a collection by iterating through pages until all data is fetched. ```APIDOC ## Common Patterns - Pagination loop ```typescript let page = 1; let hasMore = true; const allArticles = []; while (hasMore) { const { data, meta } = await client.collection('articles').find({ pagination: { page, pageSize: 50 } }); allArticles.push(...data); hasMore = page < meta.pagination.pageCount; page++; } ``` ``` -------------------------------- ### Clone Strapi Client Repository with GitHub CLI Source: https://github.com/strapi/client/blob/main/CONTRIBUTING.md Use this command to clone the Strapi Client repository using the GitHub command-line interface. ```bash gh repo clone strapi/client cd client ``` -------------------------------- ### Manage Collection Resources with Strapi Client Source: https://github.com/strapi/client/blob/main/README.md Use the `.collection()` method to get a manager for collection-type resources. This manager supports finding, creating, updating, and deleting entries. It can also handle special content-types like users from the users-permissions plugin. ```typescript const articles = client.collection('articles'); // Fetch all english articles sorted by title const allArticles = await articles.find({ locale: 'en', sort: 'title', }); // Fetch a single article const singleArticle = await articles.findOne('article-document-id'); // Create a new article const newArticle = await articles.create({ title: 'New Article', content: '...' }); // Update an existing article const updatedArticle = await articles.update('article-document-id', { title: 'Updated Title' }); // Delete an article await articles.delete('article-id'); ``` ```typescript // Auto-detected as users-permissions - no configuration needed! const users = client.collection('users'); // Create a new user await users.create({ username: 'john', email: 'john@example.com', password: 'SecurePass123!', role: 1, }); // Find users const allUsers = await users.find(); // Update a user await users.update('user-id', { username: 'john_updated' }); ``` ```typescript const articles = client.collection('articles', { path: '/my-custom-path' }); ``` -------------------------------- ### Make a POST Request Source: https://github.com/strapi/client/blob/main/_autodocs/08-http-client.md Sends a POST request to a specified path with an optional body and RequestInit options. Commonly used for creating new resources. ```typescript const response = await httpClient.post( '/articles', JSON.stringify({ title: 'New Article' }), { headers: { 'Content-Type': 'application/json' } } ); ``` -------------------------------- ### Generic Fetch Source: https://github.com/strapi/client/blob/main/_autodocs/12-quick-reference.md Demonstrates how to make a generic fetch request to a custom endpoint using the client, including specifying the HTTP method and request body. ```APIDOC ## Generic Fetch ```typescript // Custom endpoint const response = await client.fetch('/custom-endpoint', { method: 'POST', body: JSON.stringify({ data: '...' }) }); const data = await response.json(); ``` ```