# 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. For a guided walkthrough of SDK resource management with best practices, see [Manage resources with the SDK](https://docs.commercetools.com/learning-composable-commerce-developer-essentials/manage-resources-with-the-sdk/overview.md) in the Developer Essentials learning path. ## HTTP API The following SDK code examples demonstrate how to perform basic tasks such as creating, updating, and querying [Customers](https://docs.commercetools.com/api/projects/customers.md) and [Products](https://docs.commercetools.com/api/projects/products.md). You can adapt and build upon these code examples to help integrate commercetools into your code base. ### Manage Customers #### Create a Customer To create a Customer, post a [CustomerDraft](https://docs.commercetools.com/urn?urn=ctp%3Aapi%3Atype%3ACustomerDraft) to the Customers endpoint. CustomerDrafts have two required fields: `email` and `password`. After posting the CustomerDraft, the API returns a [CustomerSignInResult](https://docs.commercetools.com/urn?urn=ctp%3Aapi%3Atype%3ACustomerSignInResult). 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`. ```java // 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); ``` ```ts const createCustomer = () => { return apiRoot .customers() .post( { // The CustomerDraft is the object within the body body: { email: 'sdk@example.com', password: 'examplePassword', }, }) .execute(); }; // Create the customer and output the Customer ID createCustomer() .then(({ body }) => { console.log(body.customer.id); }) .catch(console.error); ``` ```php withEmail('sdk@example.com') ->withPassword('password') ->build(); // Post the CustomerDraft and get the new Customer $customer = $apiRoot ->customers() ->post($newCustomerDetails) ->execute() ->getCustomer(); // Output the Customer ID $customerID = $customer->getId(); echo $customerID; ``` ```cs // The following import is required: // using commercetools.Sdk.Api.Models.Customers; // Create a CustomerDraft with the required fields (email address and password) var newCustomerDetails = new CustomerDraft() { Email = "sdk@example.com", Password = "password" }; // Post the CustomerDraft and get the new Customer var customer = projectApiRoot .Customers() .Post(newCustomerDetails) .ExecuteAsync() .Result .Customer; // Output the Customer ID Console.WriteLine(customer.Id); ``` `{customerID}` is a placeholder in the following examples. #### Query a Customer You can query the Customer by including its `id` after the Customers endpoint. This example code outputs the Customer's `email`, but you can access every field within the Customer. ```java // 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); ``` ```ts // Return a Customer based on their ID const queryCustomer = (customerID: string) => { return apiRoot .customers() .withId({ ID: customerID }) .get() .execute(); }; // Query the Customer and output the Customer's email address queryCustomer('{customerID}') .then(({ body }) => { console.log(body.email); }) .catch(console.error); ``` ```php customers() ->withId('{customerID}') ->get() ->execute(); // Output the Customer's email address $customerEmail = $queryCustomer->getEmail(); echo $customerEmail; ``` ```cs // Get a Customer by their ID var queryCustomer = projectApiRoot .Customers() .WithId("{customerID}") .Get() .ExecuteAsync() .Result; // Output the Customer's email address var customerEmail = queryCustomer.Email; Console.WriteLine(customerEmail); ``` If you query a resource with an `id` or `key` that does not exist, the API returns a [Not Found](https://docs.commercetools.com/api/errors.md#404-not-found) error. This may cause your program to crash. #### Add a Customer name To update a Customer, post a `CustomerUpdate`, which contains the current version of the Customer and an array/collection of update actions, to the specified Customer. The required update actions for changing a Customer's first and second names are [Set First Name](https://docs.commercetools.com/api/projects/customers.md#set-first-name) and [Set Last Name](https://docs.commercetools.com/api/projects/customers.md#set-last-name). ```java // 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 increments every time the API applies an update action 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); ``` ```ts const updateCustomerName = (customerID: string) => { return apiRoot .customers() .withId({ ID: customerID }) .post({ // The CustomerUpdate is the object within the body body: { // The version of a new Customer is 1. This value increments every time the API applies an update action to the Customer. If the specified version does not match the current version, the request returns an error. version: 1, actions: [ { action: 'setFirstName', firstName: 'John', }, { action: 'setLastName', lastName: 'Smith', }, ], }, }) .execute(); }; // Update the customer and output the updated Customer's full name updateCustomerName('{customerID}') .then(({ body }) => { console.log(body.firstName + ' ' + body.lastName); }) .catch(console.error); ``` ```php add( (new CustomerSetFirstNameActionBuilder())->withFirstName('John')->build(), ) ->add( (new CustomerSetLastNameActionBuilder())->withLastName('Smith')->build(), ); // Create the CustomerUpdate with the current version of the Customer and the actions $customerUpdate = (new CustomerUpdateBuilder()) // The version of a new Customer is 1. This value increments every time the API applies an update action to the Customer. If the specified `withVersion` value does not match the current version, the request returns an error. ->withVersion(1) ->withActions($updateCollection) ->build(); // Post the CustomerUpdate and return the updated Customer $customerToUpdate = $apiRoot ->customers() ->withId('{customerID}') ->post($customerUpdate) ->execute(); // Output the updated Customer's full name $updatedCustomerName = $customerToUpdate->getFirstName() . ' ' . $customerToUpdate->getLastName(); echo $updatedCustomerName; ``` ```cs // The following import is required: // using commercetools.Sdk.Api.Models.Customers; // Create a list of update actions and add the setFirstName and setLastName actions var updateActions = new List { new CustomerSetFirstNameAction() { FirstName="John" }, new CustomerSetLastNameAction() { LastName="Smith" } }; // Create the CustomerUpdate with the current version of the Customer and the list of update actions var customerUpdate = new CustomerUpdate() { // The version of a new Customer is 1. This value increments every time the API applies an update action to the Customer. If the specified version does not match the current version, the request returns an error. Version = 1, Actions = updateActions }; // Post the CustomerUpdate and return the updated Customer var customerToUpdate = projectApiRoot .Customers() .WithId("{customerID}") .Post(customerUpdate) .ExecuteAsync() .Result; // Output the updated Customer's full name var updatedCustomerName = customerToUpdate.FirstName + " " + customerToUpdate.LastName; Console.WriteLine(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. You can find Customers by their email address by querying the Customers endpoint with a `where` parameter and a [Query Predicate](https://docs.commercetools.com/api/predicates/query.md). This example code returns a [CustomerPagedQueryResponse](https://docs.commercetools.com/urn?urn=ctp%3Aapi%3Atype%3ACustomerPagedQueryResponse) 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. ```java // 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, this returns either 0 or 1 Customers. // If 0, then no Customer exists with this email address. if (customerToFind.getCount() == 0) { System.out.println("This email address is not 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); } ``` ```ts // Search for Customers whose email address matches the Query Predicate const returnCustomerByEmail = (customerEmail: string) => { return apiRoot .customers() .get({ queryArgs: { where: `email="${customerEmail}"`, }, }) .execute(); }; returnCustomerByEmail('sdk@example.com') .then(({ body }) => { // As email addresses must be unique, this returns either 0 or 1 Customers. // If 0, then no Customer exists with this email address. if (body.results.length == 0) { console.log('This email address is not 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. console.log(body.results[0].id); } }) .catch(console.error); ``` ```php customers() ->get() ->withWhere('email="sdk@example.com"') ->execute(); // As email addresses must be unique, this returns either 0 or 1 Customers. // If 0, then no Customer exists with this email address. if ($customerToFind->getCount() == 0) { echo 'This email address is not 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. $customerID = $customerToFind->getResults()[0]->getId(); echo $customerID; } ``` ```cs // Search for Customers whose email address matches the Query Predicate var customerToFind = projectApiRoot .Customers() .Get() .WithWhere(@$"email=""sdk@example.com""") .ExecuteAsync() .Result; // As email addresses must be unique, this returns either 0 or 1 Customers. // If 0, then no Customer exists with this email address. if (customerToFind.Count == 0) { Console.WriteLine("This email address is not 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. var customerID = customerToFind.Results[0].Id; Console.WriteLine(customerID); } ``` ### Manage Products Creating Products requires more steps than creating Customers. This is due to [how Products are modeled](https://docs.commercetools.com/learning-model-your-product-catalog/product-modeling/overview.md). You must first create a [ProductType](https://docs.commercetools.com/api/projects/productTypes.md) before you create a Product. #### Create a ProductType To create a ProductType, post a [ProductTypeDraft](https://docs.commercetools.com/urn?urn=ctp%3Aapi%3Atype%3AProductTypeDraft) to the ProductTypes endpoint. 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`. ```java // 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); ``` ```ts // Create a ProductTypeDraft with the required fields (name and description) const createProductType = () => { return apiRoot .productTypes() .post( { // The ProductTypeDraft is the object within the body body: { name: 'The name of your ProductType', description: 'The description of your ProductType', }, }) .execute(); }; // Create the ProductType and output the ProductType ID createProductType() .then(({ body }) => { console.log(body.id); }) .catch(console.error); ``` ```php withName('The name of your ProductType') ->withDescription('The description of your ProductType') ->build(); // Post the ProductTypeDraft $productType = $apiRoot ->productTypes() ->post($newProductTypeDetails) ->execute(); // Output the ProductType ID $productTypeID = $productType->getId(); echo $productTypeID; ``` ```cs // The following import is required: // using commercetools.Sdk.Api.Models.ProductTypes; // Create a ProductTypeDraft with the required fields (name and description) var newProductTypeDetails = new ProductTypeDraft() { Name = "The name of your ProductType", Description = "The description of your ProductType" }; // Post the ProductTypeDraft var productType = projectApiRoot .ProductTypes() .Post(newProductTypeDetails) .ExecuteAsync() .Result; // Output the ProductType ID var productTypeID = productType.Id; Console.WriteLine(productTypeID); ``` `{productTypeID}` is a placeholder in the following examples. #### Create a Product To create a Product, post a [ProductDraft](https://docs.commercetools.com/urn?urn=ctp%3Aapi%3Atype%3AProductDraft) to the Products endpoint. 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`. ```java // 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); ``` ```ts // Create a Product with the required fields (name, productType, and slug) const createProduct = (productTypeID: string) => { return apiRoot .products() .post( { // The ProductDraft is the object within the body body: { name: { en: 'English name for your Product', de: 'German name for your Product', }, productType: { typeId: 'product-type', id: productTypeID, }, slug: { en: 'human-readable-url-for-english-product', de: 'human-readable-url-for-german-product', }, }, }) .execute(); }; // Create the Product and output the Product ID createProduct('{productTypeID}') .then(({ body }) => { console.log(body.id); }) .catch(console.error); ``` ```php withName( LocalizedStringBuilder::of() ->put('en', 'English name for your Product') ->put('de', 'German name for your Product') ->build(), ) ->withSlug( LocalizedStringBuilder::of() ->put('en', 'human-readable-url-for-english-product') ->put('de', 'human-readable-url-for-german-product') ->build(), ) ->withProductType( (new ProductTypeResourceIdentifierBuilder()) ->withId('{productTypeID}') ->build(), ) ->build(); // Post the ProductDraft and get the new Product $product = $apiRoot->products()->post($newProductDetails)->execute(); // Output the Product ID $productID = $product->getId(); echo $productID; ``` ```cs // The following imports are required: // using commercetools.Sdk.Api.Models.Products; // using commercetools.Sdk.Api.Models.ProductTypes; // using commercetools.Sdk.Api.Models.Common; // Create a ProductDraft with the required fields (name, slug, and productType) var newProductDetails = new ProductDraft() { Name = new LocalizedString { { "en", "English name for your Product" }, { "de", "German name for your Product" } }, ProductType = new ProductTypeResourceIdentifier() { Id = "{productTypeID}" }, Slug = new LocalizedString { { "en", "human-readable-url-for-english-product" }, { "de", "human-readable-url-for-german-product" } } }; // Post the ProductDraft and get the new Product var product = projectApiRoot .Products() .Post(newProductDetails) .ExecuteAsync() .Result; // Output the Product ID var productID = product.Id; Console.WriteLine(productID); ``` `{productID}` is a placeholder in the following examples. #### Query your Product You can query the Product by including its `id` after the Product endpoint. This example code outputs the Product's `version`, but you can access every field within the Product. ```java // 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()); ``` ```ts // Query a Product by its ID const queryProduct = (productID: string) => { return apiRoot .products() .withId({ ID: productID }) .get() .execute(); }; // Query the Product and output the Product's version queryProduct('{productID}') .then(({ body }) => { console.log(body.version); }) .catch(console.error); ``` ```php products()->withId('{productID}')->get()->execute(); // Output the Product's version $productVersion = $queryProduct->getVersion(); echo $productVersion; ``` ```cs // Query a Product by its ID var queryProduct = projectApiRoot .Products() .WithId("{productID}") .Get() .ExecuteAsync() .Result; // Output the Product's version Console.WriteLine(queryProduct.Version); ``` #### 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. To update a Product, post a `ProductUpdate`, which contains the current version of the Product and an array/collection of update actions, to the specified Product. Adding a `key` to a Product requires the [Set Key](https://docs.commercetools.com/api/projects/products.md#set-product-key) update action. ```java // 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 increments every time the API applies an update action 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); ``` ```ts const addKeyToProduct = (productID: string) => { return apiRoot .products() .withId({ ID: productID }) .post({ // The ProductUpdate is the object within the body body: { // The version of a new Product is 1. This value increments every time the API applies an update action to the Product. If the specified version does not match the current version, the request returns an error. version: 1, actions: [ { action: 'setKey', key: 'new-product-key', }, ], }, }) .execute(); }; // Add the key to the Product and output the updated Product's key addKeyToProduct('{productID}') .then(({ body }) => { console.log(body.key); }) .catch(console.error); ``` ```php add( (new ProductSetKeyActionBuilder())->withKey('new-product-key')->build(), ); // Create the ProductUpdate with the current version of the Product and the actions $productUpdate = (new ProductUpdateBuilder()) // The version of a new Product is 1. This value increments every time the API applies an update action to the Product. If the specified `withVersion` value does not match the current version, the request returns an error. ->withVersion(1) ->withActions($updateCollection) ->build(); // Post the ProductUpdate and return the updated Product $productToUpdate = $apiRoot ->products() ->withId('{productID}') ->post($productUpdate) ->execute(); // Output the updated Product's key $updatedProductKey = $productToUpdate->getKey(); echo $updatedProductKey; ``` ```cs // The following import is required: // using commercetools.Sdk.Api.Models.Products; // Create an list of update actions and add the setKey action var updateActions = new List { new ProductSetKeyAction() { Key="new-product-key" } }; // Create the ProductUpdate with the current version of the Product and the update actions var productUpdate = new ProductUpdate() { // The version of a new Product is 1. This value increments every time the API applies an update action to the Product. If the specified version does not match the current version, the request returns an error. Version = 1, Actions = updateActions }; // Post the ProductUpdate and return the updated Product var productToUpdate = projectApiRoot .Products() .WithId("{productID}") .Post(productUpdate) .ExecuteAsync() .Result; // Output the updated Product's key var updatedProductKey = productToUpdate.Key; Console.WriteLine(updatedProductKey); ``` #### Return a Product by its Key You can now query the Product by including its key after the Products endpoint. This example code outputs the Product's current English name. ```java 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); ``` ```ts const returnProductByKey = (productKey: string) => { return apiRoot .products() .withKey({ key: productKey }) .get() .execute(); }; // Output the Product's current English name returnProductByKey('new-product-key') .then(({ body }) => { console.log(body.masterData.current.name["en"]); }) .catch(console.error); ``` ```php products() ->withKey('{productKey}') ->get() ->execute(); // Output the Product's current English name $productName = $findProductByKey->getMasterData()->getCurrent()->getName(); echo $productName['en']; ``` ```cs // Get a Product by its Key var findProductByKey = projectApiRoot .Products() .WithKey("{productKey}") .Get() .ExecuteAsync() .Result; // Output the Product's current English name var productName = findProductByKey.MasterData.Current.Name["en"]; Console.WriteLine(productName); ``` ## Import API The following SDK code examples demonstrate how to perform basic import tasks. This includes creating an [Import Container](https://docs.commercetools.com/api/import-export/import-container.md), creating a [CategoryImportRequest](https://docs.commercetools.com/urn?urn=ctp%3Aimport%3Atype%3ACategoryImportRequest), querying [Import Operations](https://docs.commercetools.com/api/import-export/import-operation.md), and getting an [Import Summary](https://docs.commercetools.com/urn?urn=ctp%3Aimport%3Atype%3AImportSummary) with commercetools SDKs. You can adapt and build upon these code examples to help integrate commercetools into your code base. ### Create an Import Container To create an Import Container, post an [ImportContainerDraft](https://docs.commercetools.com/api/import-export/import-container.md#importcontainerdraft) to the Import Containers endpoint. ImportContainerDrafts have one required field: `key`. You can also specify the optional `resourceType` field to restrict what can be imported using this Import Container. This example sets `resourceType` to `category`, which means only CategoryImportRequests can be imported using this Import Container. After posting the ImportContainerDraft, the Import API returns an [ImportContainer](https://docs.commercetools.com/api/import-export/import-container.md#importcontainer) object. This contains the new Import Container and its details. ```java // Create the ImportContainerDraft ImportContainerDraft importContainerDraft = ImportContainerDraftBuilder.of() .key("sdk-example-import-container") .resourceType(ImportResourceType.CATEGORY) .build(); // Example call to create an ImportContainer ImportContainer createImportContainer = importApiRoot .importContainers() .post(importContainerDraft) .executeBlocking() .getBody(); // Output the response to the console System.out.println(createImportContainer); ``` ```ts // Create the ImportContainerDraft const importContainerDraft: ImportContainerDraft = { key: 'sdk-example-import-container', resourceType: 'category', // Remove to make the ImportContainer generic }; // Example call to create an ImportContainer async function createImportContainer(body: ImportContainerDraft) { const response = await importApiRoot .importContainers() .post({ body }) .execute(); return response.body; } // Create an ImportContainer and output the result to the log await createImportContainer(importContainerDraft) .then(console.log) .catch(console.error); ``` ```cs // Create the ImportContainerDraft var importContainerDraft = new ImportContainerDraft { Key = "sdk-example-import-container", ResourceType = IImportResourceType.Category }; // Example call to create an ImportContainer var importContainer = await importApiRoot .ImportContainers() .Post(importContainerDraft) .ExecuteAsync(); // Output the response to the console Console.WriteLine(importContainer.Key); ``` ### Import a Category To import a Category, you must create a [CategoryImport](https://docs.commercetools.com/urn?urn=ctp%3Aimport%3Atype%3ACategoryImport), and then include it in a [CategoryImportRequest](https://docs.commercetools.com/urn?urn=ctp%3Aimport%3Atype%3ACategoryImportRequest). ```java // Create a CategoryImport CategoryImport categoryImport = CategoryImport.builder() .key("sdk-example-category-import") .name(LocalizedString.builder().addValue("en", "SDK Example Category Import").build()) .slug(LocalizedString.builder().addValue("en", "sdk-example-category-import").build()) .build(); // Create a CategoryImportRequest CategoryImportRequest categoryImportRequest = CategoryImportRequest.builder() .resources(List.of(categoryImport)) .build(); // Example call to import Categories ImportResponse createCategoryImport = importApiRoot .categories() .importContainers() .withImportContainerKeyValue("sdk-example-import-container") .post(categoryImportRequest) .executeBlocking() .getBody(); // Output the response to the console System.out.println(createCategoryImport); ``` ```ts // Create a CategoryImport const categoryImport: CategoryImport = { key: 'sdk-example-category-import', name: { en: 'SDK Example Category Import', }, slug: { en: 'sdk-example-category-import', }, }; // Create a CategoryImportRequest const categoryImportRequest: CategoryImportRequest = { type: 'category', resources: [categoryImport], // Include up to 20 categoryImports in this array }; // Example call to import Categories async function createCategoryImport( importContainerKey: string, body: CategoryImportRequest ) { const response = await importApiRoot .categories() .importContainers() .withImportContainerKeyValue({ importContainerKey }) .post({ body }) .execute(); return response.body; } // Import the Category and output the result to the log await createCategoryImport( 'sdk-example-import-container', categoryImportRequest ) .then(console.log) .catch(console.error); ``` ```cs // Create a CategoryImport var categoryImport = new CategoryImport { Key = "sdk-example-category-import", Name = new LocalizedString { { "en", "SDK Example Category Import" }, }, Slug = new LocalizedString { { "en", "sdk-example-category-import" }, } }; // Create a CategoryImportRequest var categoryImportRequest = new CategoryImportRequest { Resources = new List { categoryImport } }; // Example call to import Categories var createCategoryImport = await importApiRoot .Categories() .ImportContainers() .WithImportContainerKeyValue("sdk-example-import-container") .Post(categoryImportRequest) .ExecuteAsync(); // Output the response to the console Console.WriteLine(createCategoryImport.OperationStatus[0].OperationId); ``` ### Query the import process #### Query Import Operations in the Import Container The following code examples demonstrate how to query Import Operations in the Import Container you created earlier. For more information, see [Query ImportOperations in ImportContainer](https://docs.commercetools.com/api/import-export/import-operation.md#query-importoperations-in-importcontainer). ```java // Example call to query Import Operations ImportOperationPagedResponse queryImportOperations = importApiRoot .importContainers() .withImportContainerKeyValue("sdk-example-import-container") .importOperations() .get() .executeBlocking() .getBody(); // Output the response to the console System.out.println(queryImportOperations); ``` ```ts // Example call to query Import Operations async function queryImportOperations(importContainerKey: string) { const response = await importApiRoot .importContainers() .withImportContainerKeyValue({ importContainerKey }) .importOperations() .get() .execute(); return response.body; } // Query Import Operations for an Import Container and output the result to the log await queryImportOperations('sdk-example-import-container') .then(console.log) .catch(console.error); ``` ```cs // Example call to query Import Operations var queryImportOperations = await importApiRoot .ImportContainers() .WithImportContainerKeyValue("sdk-example-import-container") .ImportOperations() .Get() .ExecuteAsync(); // Output the response to the console Console.WriteLine(queryImportOperations.Results[0].Id); ``` #### Get an Import Summary For more information, see [ImportSummary](https://docs.commercetools.com/urn?urn=ctp%3Aimport%3Atype%3AImportSummary). ```java // Example call to get an Import Summary for an Import Container ImportSummary getImportSummary = importApiRoot .importContainers() .withImportContainerKeyValue("sdk-example-import-container") .importSummaries() .get() .executeBlocking() .getBody(); // Output the response to the console System.out.println(getImportSummary); ``` ```ts // Example call to get an Import Summary for an Import Container async function getImportSummary(importContainerKey: string) { const response = await importApiRoot .importContainers() .withImportContainerKeyValue({ importContainerKey }) .importSummaries() .get() .execute(); return response.body; } // Get an ImportSummary for an Import Container and output the result to the log await getImportSummary('sdk-example-import-container') .then(console.log) .catch(console.error); ``` ```cs // Example call to get an Import Summary for an Import Container var getImportSummary = await importApiRoot .ImportContainers() .WithImportContainerKeyValue("sdk-example-import-container") .ImportSummaries() .Get() .ExecuteAsync(); // Output the response to the console Console.WriteLine(getImportSummary.States.Processing); ``` ## Checkout API The following SDK code examples demonstrate how to create a [Transaction](https://docs.commercetools.com/checkout/transactions-api.md#create-transaction) and [Manage Payments](https://docs.commercetools.com/checkout/payment-intents-api.md#manage-payment-by-id) with the [Checkout API](https://docs.commercetools.com/checkout/). You can adapt and build upon these code examples to help integrate Checkout into your code base. ### Create a Transaction To create a Transaction, post a [TransactionDraft](https://docs.commercetools.com/urn?urn=ctp%3Acheckout%3Atype%3ATransactionDraft) to the Transactions endpoint. Ensure you use TransactionDraft from the Checkout SDK package and not TransactionDraft from the HTTP API package. ```java // Create and post a TransactionDraft to generate a Transaction Transaction transaction = checkoutApiRoot.with() .transactions() .post(TransactionDraft.builder() .key("a-transaction-key") .application(a -> a.key("your-application-key")) .cart(CartResourceIdentifierBuilder.of().key("your-cart-key").build()) .plusTransactionItems(t -> t.amount(a -> a.centAmount(1000).currencyCode("EUR")) .paymentIntegration(p -> p.key("your-payment-integration-key"))) .build() ) .executeBlocking() .getBody(); // Output the created Transaction System.out.println(transaction); ``` ```ts // Create the TransactionDraft const transactionDraft: TransactionDraft = { key: 'a-transaction-key', application: { typeId: 'application', key: 'your-application-key' }, cart: { typeId: 'cart', key: 'your-cart-key' }, transactionItems: [ { paymentIntegration: { typeId: 'payment-integration', key: 'your-payment-integration-key', }, amount: { currencyCode: 'EUR', centAmount: 1000 }, }, ], }; // Example call to create a Transaction async function createTransaction(body: TransactionDraft) { const response = await checkoutApiRoot .transactions() .post({ body }) .execute(); return response.body; } // Create a Transaction and output the result to the log await createTransaction(transactionDraft) .then(console.log) .catch(console.error); ``` ```cs // Create and post a TransactionDraft to generate a Transaction var transaction = await checkoutApiRoot .Transactions() .Post(new TransactionDraft() { Key = "a-transaction-key", Application = new ApplicationResourceIdentifier() { Key = "your-application-key" }, Cart = new CartResourceIdentifier() { Key = "your-cart-key" }, TransactionItems = new List() { new TransactionItemDraft() { Amount = new Amount() { CentAmount = 1000, CurrencyCode = "EUR" }, PaymentIntegration = new PaymentIntegrationResourceIdentifier() { Key = "your-payment-integration-key" } } } }).ExecuteAsync(); // Output the id of the created Transaction Console.WriteLine($"Transaction ID: {transaction.Id}"); ``` ## Related pages - [Section overview page](https://docs.commercetools.com/dev-tooling.md) - [Next page: SDK demo applications](https://docs.commercetools.com/dev-tooling/sdk-example-applications.md)