Set up the Java SDK

Learn how to configure your environment for the Java SDK.

Ask about this Page
Copy for LLM
View as Markdown

After completing this module, you should be able to:

  • Use the Java SDK to work on a commercetools Project.

The following instructions help you set up your environment to develop applications with commercetools using the Java SDK.

This exercise walks you through a hands-on setup. For the full SDK reference, including Maven setup and multi-API support, see Get started with the Java SDK.
This module uses the Java v2 SDK. The Java v1 SDK was deprecated in January 2024 and no longer receives security updates or bug fixes. If you're migrating from v1, see the migration guide.

To follow along, you'll need:

  • Your preferred Java IDE
  • A Java runtime

Pay special attention to version requirements.

Install Java IDE

In this tutorial, we use the IntelliJ IDEA. In case you don’t have IntelliJ installed, then follow the instructions here. The Community Edition is free to use and sufficient for this tutorial.

Install Java runtime environment

Make sure you have a Java environment installed. You can verify it by checking in the terminal with:

java -version

Install the SDK

Let’s create a new local project using IntelliJ by following these steps:

Step 1: Create a new project

Open IntelliJ, select New Project, and choose Gradle/Java.

Step 2: Name the project

Give it a suitable name. We used demo as the project name and saved it in the IdeaProjects folder.
New project screen showing demo project being saved in the ideaprojects folder.
Next, wait for the Gradle dependencies to download. As a result, your build.gradle file should look like this:
plugins {
   id("java")
}


group = "org.example"
version = "1.0-SNAPSHOT"


repositories {
   mavenCentral()
}


dependencies {
   testImplementation(platform("org.junit:junit-bom:5.7.0"))
   testImplementation("org.junit.jupiter:junit-jupiter-engine:5.7.0")


}


tasks.test {
   useJUnitPlatform()
}

Step 3: Finish project setup

Install the commercetools Java v2 SDK by adding the dependencies listed in the Install the Java SDK section of the SDK documentation to your build.gradle file. These packages use the com.commercetools.sdk namespace introduced in v2.
In addition to the core SDK packages, you need the GraphQL, Import API, and logging dependencies for this learning path. Add the following to your build.gradle file.
The following example uses latest.release to install the latest version of each dependency. To use a specific version, replace latest.release with the version number.
ext {
    versions = [
            commercetools: "latest.release",
            slf4j: "2.0.16",
            logback: "1.5.12",
    ]
}


allprojects {
    apply plugin: 'java'
    sourceCompatibility = 1.8
    targetCompatibility = 1.8
}


repositories {
    mavenCentral()
    maven {
        url "https://packages.atlassian.com/maven-3rdparty"
    }
}


dependencies {
    implementation "com.commercetools.sdk:commercetools-http-client:${versions.commercetools}"
    implementation "com.commercetools.sdk:commercetools-sdk-java-api:${versions.commercetools}"
    implementation "com.commercetools.sdk:commercetools-graphql-api:${versions.commercetools}"
    implementation "com.commercetools.sdk:commercetools-sdk-java-importapi:${versions.commercetools}"
    implementation "org.slf4j:slf4j-api:${versions.slf4j}"
    implementation "ch.qos.logback:logback-classic:${versions.logback}"
    implementation group: 'org.json', name: 'json', version: '20200518'
    implementation 'javax.json:javax.json-api:1.1.4'
    implementation 'org.glassfish:javax.json:1.1.4'
}

Check that the installation was successful by running the following command in your IDE terminal:

./gradlew build
Do you see a BUILD SUCCESSFUL?
Terminal showing build successful.
If you do, you have successfully set up the Java v2 SDK. If you receive an error message, see Step 4 for resolving any errors.

Step 4: Resolve possible errors with the Java SDK

Check the compatibility between your Gradle and Java versions. A build error can occur if there is a mismatch between your Java environment, Gradle, and the project version.
  1. Update Gradle wrapper configuration: locate and open the gradle-wrapper.properties file within your project directory. Update the distributionUrl to use a Gradle version compatible with your Java version. See the Gradle compatibility matrix for details.
  2. Check Gradle and Java versions in IntelliJ: navigate to Settings > Build, Execution, Deployment > Build Tools > Gradle. Use the Gradle version specified in the gradle-wrapper.properties file. Select a Java version compatible with your Gradle version for the Gradle JVM.
  3. Version mismatch issues: If you encounter "package does not exist" errors, verify you're not mixing v1 and v2 SDK dependencies. The v2 SDK uses the com.commercetools.sdk package namespace, while v1 used io.sphere.sdk. Remove any v1 dependencies before proceeding.

Test your setup

Let's now check if the SDK is set up correctly or not. Make sure that you have created an API Client as we mentioned previously before continuing.

Step 5: Set up an API Client in your SDK

For the Java SDK, use the following code example to create a file called ClientService.java and place it in a folder called /impl.
package impl;

import com.commercetools.api.client.ProjectApiRoot;
import com.commercetools.api.defaultconfig.ApiRootBuilder;
import com.commercetools.api.defaultconfig.ServiceRegion;
import io.vrap.rmf.base.client.oauth2.ClientCredentials;

import java.io.IOException;

public class ClientService {

   public static ProjectApiRoot projectApiRoot;

   public static ProjectApiRoot createApiClient() throws IOException {

       String clientId = "";
       String clientSecret = "";
       String projectKey = "";

       projectApiRoot = ApiRootBuilder.of()
               .defaultClient(
                       ClientCredentials.of()
                               .withClientId(clientId)
                               .withClientSecret(clientSecret)
                               .build(),
                       ServiceRegion.{region}.getOAuthTokenUrl(),
                       ServiceRegion.{region}.getApiUrl()
               ).build(projectKey);

       return projectApiRoot;
   }
}

Then update the following values to match your API Client:

  • clientId
  • clientSecret
  • projectKey
  • ServiceRegion.{region}getOAuthTokenUrl()
  • ServiceRegion.{region}.getApiUrl()
ClientService.java file with copied code inside.

Step 6: Fetch the Customer data

Create a file called CustomerFetch.java and copy the following code. Remember to update the Customer ID.
import com.commercetools.api.client.ProjectApiRoot;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.concurrent.ExecutionException;




import static impl.ClientService.createApiClient;




public class CustomerFetch {
   public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {
       final ProjectApiRoot client = createApiClient();
       Logger logger = LoggerFactory.getLogger(CustomerFetch.class.getName());
       String customerId = "";
       logger.info(
               "Fetching the customers last name " +
                       client
                               .customers()
                               .withId(customerId)
                               .get()
                               .execute()
                               .toCompletableFuture().get()
                               .getBody()
                               .getLastName()
       );
       client.close();
   }
}
Java code copied into the customerfetch.java file.

Step 7: Execute the code

You can write your own run task or use the IDE to run the main method.

Options in IDE to run the main method.

Nice work! Customer successfully fetched!

Customer successfully fetched.