dotCMS API Client - @dotcms/client
The @dotcms/client
is a JavaScript/TypeScript library for interacting with a dotCMS instance. It allows you to easily fetch pages, content, and navigation information in JSON format, as well as to make complex queries on content collections.
This client library provides a streamlined, promise-based interface to fetch pages and navigation API.
Features
- Easy-to-use methods to interact with dotCMS pages and the Navigation API.
- Support for custom actions to communicate with the dotCMS page editor.
- Comprehensive TypeScript typings for better development experience.
dotCMS API Client
Installation
To get started, install the client via npm or yarn:
npm install @dotcms/client
Or using Yarn:
yarn add @dotcms/client
Usage
@dotcms/client
supports both ES modules and CommonJS. You can import it using either syntax:
ES Modules
import { DotCmsClient } from '@dotcms/client';
CommonJS
const { DotCmsClient } = require('@dotcms/client');
Initialization
First, initialize the client with your dotCMS instance details.
const client = DotCmsClient.init({
dotcmsUrl: 'https://your-dotcms-instance.com',
authToken: 'your-auth-token',
siteId: 'your-site-id'
});
Fetching a Page
You can retrieve the elements of any page in your dotCMS system in JSON format using the client.page.get()
method.
const pageData = await client.page.get({
path: '/your-page-path',
language_id: 1,
personaId: 'optional-persona-id'
});
Fetching Navigation
Retrieve the dotCMS file and folder tree to get information about the navigation structure.
const navData = await client.nav.get({
path: '/',
depth: 2,
languageId: 1
});
Fetching a Collection of Content
The getCollection
method allows you to fetch a collection of content items (sometimes called "contentlets") using a builder pattern for complex queries.
Basic Usage
Here’s a simple example to fetch content from a collection:
import { DotCmsClient } from '@dotcms/client';
const client = DotCmsClient.init({
dotcmsUrl: 'https://your-dotcms-instance.com',
authToken: 'your-auth-token'
});
const collectionResponse = await client.content
.getCollection('Blog')
.limit(10)
.page(1)
.fetch();
console.log(collectionResponse.contentlets);
Sorting Content
You can sort the content by any field in ascending or descending order:
const sortedResponse = await client.content
.getCollection('Blog')
.sortBy([{ field: 'title', order: 'asc' }])
.fetch();
Filtering by Language
If you need to filter content by language, you can specify the language
parameter:
const languageFilteredResponse = await client.content
.getCollection('Blog')
.language(2)
.fetch();
Using Complex Queries
You can build more complex queries using the query builder. For example, filter by author
and title
:
const complexQueryResponse = await client.content
.getCollection('Blog')
.query((qb) => qb.field('author').equals('John Doe').and().field('title').equals('Hello World'))
.fetch();
Fetching Draft Content
To only fetch draft content, use the draft()
method:
const draftContentResponse = await client.content
.getCollection('Blog')
.draft()
.fetch();
Setting Depth for Relationships
To fetch content with a specific relationship depth, use the depth()
method:
const depthResponse = await client.content
.getCollection('Blog')
.depth(2)
.fetch();
Combining Multiple Methods
You can combine multiple methods to build more complex queries. For example, limit results, sort them, and filter by author:
const combinedResponse = await client.content
.getCollection('Blog')
.limit(5)
.page(2)
.sortBy([{ field: 'title', order: 'asc' }])
.query((qb) => qb.field('author').equals('John Doe'))
.depth(1)
.fetch();
Error Handling Example
To handle errors gracefully, you can use a try-catch
block around your API calls. Here’s an example:
try {
const pageData = await client.page.get({
path: '/your-page-path',
languageId: 1
});
} catch (error) {
console.error('Failed to fetch page data:', error);
}
This ensures that any errors that occur during the fetch (e.g., network issues, invalid paths, etc.) are caught and logged properly.
When fetching large collections of content, pagination is key to managing the number of results returned:
const paginatedResponse = await client.content
.getCollection('Blog')
.limit(10)
.page(2)
.fetch();
API Reference
Detailed documentation of the @dotcms/client
methods, parameters, and types can be found below:
DotCmsClient.init(config: ClientConfig): DotCmsClient
Initializes the dotCMS client with the specified configuration.
DotCmsClient.page.get(options: PageApiOptions): Promise<unknown>
Retrieves the specified page's elements from your dotCMS system in JSON format.
DotCmsClient.nav.get(options: NavApiOptions): Promise<unknown>
Retrieves information about the dotCMS file and folder tree.
DotCmsClient.content.getCollection(contentType: string): CollectionBuilder<T>
Creates a builder to filter and fetches a collection of content items for a specific content type.
Parameters
contentType
(string): The content type to retrieve.
Returns
CollectionBuilder<T>
: A builder instance for chaining filters and executing the query.
Contributing
GitHub pull requests are the preferred method to contribute code to dotCMS. Before any pull requests can be accepted, an automated tool will ask you to agree to the dotCMS Contributor's Agreement.
Licensing
dotCMS comes in multiple editions and as such is dual licensed. The dotCMS Community Edition is licensed under the GPL 3.0 and is freely available for download, customization and deployment for use within organizations of all stripes. dotCMS Enterprise Editions (EE) adds a number of enterprise features and is available via a supported, indemnified commercial license from dotCMS. For the differences between the editions, see the feature page.
Support
If you need help or have any questions, please open an issue in the GitHub repository.
Documentation
Always refer to the official dotCMS documentation for comprehensive guides and API references.
Getting Help