Get started with the TypeScript SDK

Learn how to set up and use the TypeScript SDK.

This step-by-step guide leads you through setting up and making API calls using the TypeScript SDK.

Requirements

To follow this guide you should have the following:

  • A commercetools Composable Commerce Project
  • An API Client
  • Node v18.17.x (or later)
  • Either npm v9.6.x (or later) or yarn v3.2.x (or later)

For more information on setting up a commercetools Composable Commerce Project or API Client, follow our Getting started with commercetools Composable Commerce guides.

Objectives of the get started guide

By the end of this guide you will have:

Placeholder values

Example code in this guide uses the following placeholder values. You should replace these placeholders with the following values.

If you do not have an API Client, follow our Get your API Client guide.

PlaceholderReplace withFrom
{projectKey}project_keyyour API Client
{clientID}client_idyour API Client
{clientSecret}secretyour API Client
{scope}scopeyour API Client
{region}your RegionHosts

Install the TypeScript SDK

Use the following commands to install SDK components from npm or Yarn.

SDKnpmYarn
SDK Clientnpm install @commercetools/ts-clientyarn add @commercetools/ts-client
HTTP APInpm install @commercetools/platform-sdkyarn add @commercetools/platform-sdk
Import APInpm install @commercetools/importapi-sdkyarn add @commercetools/importapi-sdk
Audit Log APInpm install @commercetools/history-sdkyarn add @commercetools/history-sdk

You must install the SDK Client and the HTTP API. The Import API and Audit Log API are only needed for more specific use cases.

Create a ClientBuilder file

Create a new file called BuildClient.ts and insert the following code.

This code creates a Client that is used to make API calls.

import fetch from 'node-fetch';
import {
ClientBuilder,
// Import middlewares
type AuthMiddlewareOptions, // Required for auth
type HttpMiddlewareOptions, // Required for sending HTTP requests
} from '@commercetools/ts-client';
const projectKey = '{projectKey}';
const scopes = ['{scope}'];
// Configure authMiddlewareOptions
const authMiddlewareOptions: AuthMiddlewareOptions = {
host: 'https://auth.{region}.commercetools.com',
projectKey: projectKey,
credentials: {
clientId: '{clientID}',
clientSecret: '{clientSecret}',
},
scopes,
httpClient: fetch,
};
// Configure httpMiddlewareOptions
const httpMiddlewareOptions: HttpMiddlewareOptions = {
host: 'https://api.{region}.commercetools.com',
httpClient: fetch,
};
// Export the ClientBuilder
export const ctpClient = new ClientBuilder()
.withProjectKey(projectKey) // .withProjectKey() is not required if the projectKey is included in authMiddlewareOptions
.withClientCredentialsFlow(authMiddlewareOptions)
.withHttpMiddleware(httpMiddlewareOptions)
.withLoggerMiddleware() // Include middleware for logging
.build();

Adding middleware

This example code configures authMiddlewareOptions and httpMiddlewareOptions to handle auth and HTTP requests respectively.

You can configure and use other middleware based on your requirements and add them to ctpClient with method chaining.

Screenshot of autocomplete for including middleware

You can learn more about configuring and using middleware on the Middleware page.

Create the Client

Create a new file and include the following code:

import { ctpClient } from './BuildClient';
import {
ApiRoot,
createApiBuilderFromCtpClient,
} from '@commercetools/platform-sdk';
// Create apiRoot from the imported ClientBuilder and include your Project key
const apiRoot = createApiBuilderFromCtpClient(ctpClient)
.withProjectKey({ projectKey: '{projectKey}' });
// Example call to return Project information
// This code has the same effect as sending a GET request to the commercetools Composable Commerce API without any endpoints.
const getProject = () => {
return apiRoot
.get()
.execute();
};
// Retrieve Project information and output the result to the log
getProject()
.then(console.log)
.catch(console.error);

You can now use apiRoot to build requests to the Composable Commerce API.

This code includes getProject() as an example. If you run this code, the Project is returned.

Structure your API call

Add an endpoint

Add an endpoint to apiRoot. The following targets the Shopping List endpoint:

apiRoot
.shoppingLists();

If your IDE supports auto-complete, you can see the full list of endpoints.

Screenshot of autocomplete for endpoint

If no endpoint is specified, the Project is referenced.

Query a specific entity using withID() or withKey()

To query a specific entity (such as an individual Shopping List), include its id or key using .withId() or .withKey() respectively.

apiRoot
.shoppingLists()
.withId({ ID: 'a-shoppinglist-id' });
apiRoot
.shoppingLists()
.withKey({ key: 'a-shoppinglist-key' });

Add the method

After selecting the endpoint, select a method to use. get() is used to query entities. post() is used to create and update entities. .delete() is used to delete entities.

apiRoot
.shoppingLists()
.withId({ ID: 'a-shoppinglist-id' })
.get();

Adding parameters and payloads

When querying entities, include parameters within get(). When creating and updating entities, include parameters and payloads within post().

When getting the Shopping List endpoint, you can include optional parameters to modify what Shopping Lists are returned:

Screenshot of autocomplete for get() to the ShoppingList endpoint

When posting to the Shopping List endpoint, you must include a body payload. This payload (ShoppingListDraft) creates a new Shopping List:

Screenshot of autocomplete for post() to the ShoppingList endpoint

When posting to a specific Shopping List, you must include a body payload. This payload (ShoppingListUpdate) updates the specified Shopping List:

Screenshot of autocomplete for post() to a specific ShoppingList

.execute() .then() .catch()

.execute() sends the API request.

.then() adds functionality that should follow the API request. In the following example code, then() is used to output the response to the console.

.catch() assists with debugging and error handling.

apiRoot
.shoppingLists()
.withId({ ID: 'a-shoppinglist-id' })
.get()
.execute()
.then(({ body }) => {
console.log(JSON.stringify(body));
})
.catch(console.error);

Using the TypeScript SDK in the browser

You can use the TypeScript SDK as an embedded Universal Module Definition (UMD) module or an imported package in a frontend framework/library such as React.

As an embedded UMD module

Create an HTML file and insert the following code:

<!DOCTYPE html>
<html lang="en">
<head>
<title>TypeScript SDK Examples</title>
<script src="https://unpkg.com/browse/@commercetools/ts-client@latest/dist/commercetools-ts-client.umd.js"></script>
<script src="https://unpkg.com/@commercetools/platform-sdk@latest/dist/commercetools-platform-sdk.umd.js"></script>
</head>
<body>
<!-- Click this button to return the Project details -->
<p>
<button onclick="getProjectDetails()">Get Project Information</button>
</p>
<!-- This text is overwritten when getProjectDetails() finishes -->
<p id="details">
Click the above button to display the Project information.
</p>
</body>
<script>
// Enter your API client configuration
var oauthUri = 'https://auth.{region}.commercetools.com';
var baseUri = 'https://api.{region}.commercetools.com';
var credentials = {
clientId: '{clientID}',
clientSecret: '{clientSecret}',
};
var projectKey = '{projectKey}';
// Builds the client
var { ClientBuilder } = window['@commercetools/ts-client'];
var client = new ClientBuilder()
.defaultClient(baseUri, credentials, oauthUri, projectKey)
.build();
var { createApiBuilderFromCtpClient } =
window['@commercetools/platform-sdk'];
var apiRoot = createApiBuilderFromCtpClient(client).withProjectKey({
projectKey,
});
// Returns the Project details
function getProjectDetails() {
apiRoot
.get()
.execute()
.then(function ({ body }) {
window.document.getElementById('details').innerHTML =
JSON.stringify(body);
});
}
</script>
</html>

When loaded in your web browser this page displays a button that, when clicked, returns your Project information.

The getProjectDetails() function is similar to code examples within this get started guide. Consult the previous code examples to add further functionality to the HTML document.

As an imported package

The following code example is for React TypeScript. Use the following code in the App.tsx file.

import React, { useState, useEffect } from 'react';
import { ClientBuilder, type Client } from '@commercetools/ts-client';
import {
createApiBuilderFromCtpClient,
ApiRoot,
} from '@commercetools/platform-sdk';
const BASE_URI = 'https://api.{region}.commercetools.com';
const OAUTH_URI = 'https://auth.{region}.commercetools.com';
const PROJECT_KEY = '{projectKey}';
const CREDENTIALS = {
clientId: '{clientID}',
clientSecret: '{clientSecret}',
};
export function App() {
const [projectDetails, setProjectDetails] = useState({});
// Create client
const getClient = (): Client => {
return new ClientBuilder()
.defaultClient(BASE_URI, CREDENTIALS, OAUTH_URI, PROJECT_KEY)
.build();
};
// Get apiRoot
const getApiRoot = (client: Client): ApiRoot => {
return createApiBuilderFromCtpClient(client);
};
useEffect(function () {
const client = getClient();
const apiRoot = getApiRoot(client);
apiRoot
.withProjectKey({ projectKey: PROJECT_KEY })
.get()
.execute()
.then(({ body }) => {
setProjectDetails(body);
})
.catch(console.error);
}, []);
return (
<div>
<h2>Project details for {PROJECT_KEY}:</h2>
<pre>{JSON.stringify(projectDetails, null, 2)}</pre>
</div>
);
}

Next steps

Try our example code

Continue learning about the TypeScript SDK by checking our SDK code examples. You will find example code for creating, querying, and updating Customers and Products.

Set up a demo application

The Me Endpoint Checkout app demonstrates how to use the Me endpoints to create an example web store.