This is the early access documentation preview for Custom Views. This documentation might not be in sync with our official documentation.

SDK code examples

Try our example SDK code.

Example SDK code on this page assumes you have set up your SDK as described in the get started guide of your respective SDK. You may need to modify some code if your environment differs.

Overview

The following SDK code examples demonstrate how to carry out basic commerce tasks such as creating, updating, and querying Customers and Products with commercetools SDKs. These code examples can be easily adapted and built upon to help you integrate commercetools Composable Commerce into your code base.

Manage Customers

Create a Customer

A CustomerDraft must be created and posted to the Customers endpoint to create a Customer.

CustomerDrafts have two required fields: email and password.

After posting the CustomerDraft, the API returns a CustomerSignInResult. This contains the new Customer and an optional Cart (which is null in these examples). These code examples get the Customer then output its id.

Create a Customer
// Create a CustomerDraft with the required fields (email address and password)
CustomerDraft newCustomerDetails = CustomerDraft
.builder()
.email("sdk@example.com")
.password("password")
.build();
// Post the CustomerDraft and get the new Customer
Customer customer = apiRoot
.customers()
.post(newCustomerDetails)
.executeBlocking()
.getBody()
.getCustomer();
// Output the Customer ID
String customerID = customer.getId();
System.out.println(customerID);

{customerID} is used as a placeholder in following examples.

Query a Customer

Your new Customer can be queried by including its id after the Customers endpoint. This example code outputs the Customer's email address, but every field within the Customer can be accessed.

Query a Customer
// Query a Customer by their ID
Customer queryCustomer = apiRoot
.customers()
.withId("{customerID}")
.get()
.executeBlocking()
.getBody();
// Output the Customer's email address
String customerEmail = queryCustomer.getEmail();
System.out.println(customerEmail);

If you query a resource with an id or key that does not exist, the API returns a 404 Not Found error. This may cause your program to crash.

Add a Customer name

A CustomerUpdate, which contains the current version of the Customer and an array/collection of update actions, must be posted to the specified Customer to update its values.

The required update actions for changing a Customer's first and second names are Set First Name and Set Last Name.

Update a Customer
// Create the CustomerUpdate with the current version of the Customer and add the actions
CustomerUpdate customerUpdate = CustomerUpdate
.builder()
// The version of a new Customer is 1. This value is incremented every time an update action is applied to the Customer. If the specified version does not match the current version, the request returns an error.
.version(1l)
.plusActions(actionBuilder ->
actionBuilder.setFirstNameBuilder().firstName("John")
)
.plusActions(actionBuilder ->
actionBuilder.setLastNameBuilder().lastName("Smith")
)
.build();
// Post the CustomerUpdate and return the updated Customer
Customer updatedCustomer = apiRoot
.customers()
.withId("{customerID}")
.post(customerUpdate)
.executeBlocking()
.getBody();
// Output the updated Customer's full name
String updatedCustomerName =
updatedCustomer.getFirstName() + " " + updatedCustomer.getLastName();
System.out.println(updatedCustomerName);

Find a Customer by their email address

As the email of a Customer is unique, it is a dependable way to find a Customer.

Customers can be found by their email address by querying the Customers endpoint with a where parameter and a Query Predicate.

This example code returns a CustomerPagedQueryResponse that contains a results array. If a Customer exists with the email, results will contain one entry and this Customer's id is output to the console.

Find a Customer by email address
// Search for Customers whose email address matches the predicate variable
CustomerPagedQueryResponse customerToFind = apiRoot
.customers()
.get()
.withWhere("email = :customerEmail", "customerEmail", "sdk@example.com")
.executeBlocking()
.getBody();
// As email addresses must be unique, either 0 or 1 Customers will be returned.
// If 0, then no Customer exists with this email address.
if (customerToFind.getCount() == 0) {
System.out.println("This email address has not been registered.");
} else {
// Since there can be only one Customer resource in the result, it must be the first entry of the results array. This outputs the Customer's id.
String customerID = customerToFind.getResults().get(0).getId();
System.out.println(customerID);
}

Manage Products

Creating Products requires more steps than creating Customers. This is due to how Products are modeled in Composable Commerce.

Before a Product can be created, you must first create a ProductType.

Create a ProductType

A ProductTypeDraft must be created and posted to the ProductTypes endpoint to create a ProductType.

ProductTypeDrafts have two required fields: name and description.

After posting the ProductTypeDraft, the API returns the new ProductType. These code examples output the new ProductType's id.

Create a ProductType
// Create a ProductTypeDraft with the required fields (name and description)
ProductTypeDraft newProductTypeDetails = ProductTypeDraft
.builder()
.name("The name of your ProductType")
.description("The description of your ProductType")
.build();
// Post the ProductTypeDraft and get the new ProductType
ProductType productType = apiRoot
.productTypes()
.post(newProductTypeDetails)
.executeBlocking()
.getBody();
// Output the ProductType ID
String productTypeID = productType.getId();
System.out.println(productTypeID);

{productTypeID} is used as a placeholder in following examples.

Create a Product

A ProductDraft must be created and posted to the Products endpoint to create a Product.

ProductDrafts have three required fields: name, productType, and slug.

After posting the ProductDraft, the API returns the new Product. These code examples output the new Product's id.

Create a Product
// Create a ProductDraft with the required fields (name, productType, and slug)
ProductDraft newProductDetails = ProductDraft
.builder()
.name(stringBuilder ->
stringBuilder
.addValue("en", "English name for your Product")
.addValue("de", "German name for your Product")
)
.productType(typeBuilder -> typeBuilder.id({productTypeID}))
.slug(stringBuilder ->
stringBuilder
.addValue("en", "human-readable-url-for-english-product")
.addValue("de", "human-readable-url-for-german-product")
)
.build();
// Post the ProductDraft and get the new Product
Product product = apiRoot
.products()
.post(newProductDetails)
.executeBlocking()
.getBody();
// Output the Product ID
String productID = product.getId();
System.out.println(productID);

{productID} is used as a placeholder in following examples.

Query your Product

Your new Product can be queried by including its id after the Product endpoint. This example code outputs the Product's version, but every field within the Product can be accessed.

Query a Product
// Query a Product by its ID
Product queryProduct = apiRoot
.products()
.withId("{productID}")
.get()
.executeBlocking()
.getBody();
// Output the Product's version
System.out.println(queryProduct.getVersion());

Add a Product key

Keys are user-defined unique identifiers that make it easier to manage various resources in your Project. By assigning keys to Products, you can query and update Products using a human-friendly identifier instead of a randomly generated ID. You can also potentially use keys to sync your Products with their identifiers in external databases.

A ProductUpdate, which contains the current version of the Product and an array/collection of update actions must be posted to the specified Product to update its values.

Adding a key to a Product requires the Set Key update action.

Update a Product with a new key
// Create the ProductUpdate with the current version of the Product and the update actions
ProductUpdate productUpdate = ProductUpdate
.builder()
// The version of a new Product is 1. This value is incremented every time an update action is applied to the Product. If the specified version does not match the current version, the request returns an error.
.version(1l)
.plusActions(actionBuilder ->
actionBuilder.setKeyBuilder().key("new-product-key")
)
.build();
// Post the ProductUpdate and return the updated Product
Product updatedProduct = apiRoot
.products()
.withId("{productID}")
.post(productUpdate)
.executeBlocking()
.getBody();
// Output the updated Product's key
String updatedProductKey = updatedProduct.getKey();
System.out.println(updatedProductKey);

Return a Product by its Key

Your Product can now be queried by including its key after the Products endpoint. This example code outputs the Product's current English name.

Query a Product by its key
Product findProductByKey = apiRoot
.products()
.withKey("{productKey}")
.get()
.executeBlocking()
.getBody();
// Output the Product's current English name
String productName = findProductByKey
.getMasterData()
.getCurrent()
.getName()
.get("en");
System.out.println(productName);