### Example URL for Querying Customers Source: https://docs.commercetools.com/api/getting-started/manage-resources This GET request example demonstrates how to retrieve all customer data from your project. An Authorization header is required. ```http GET https://api.{region}.commercetools.com/{projectKey}/customers ``` -------------------------------- ### Prefix Search Example Source: https://docs.commercetools.com/api/search-query-language Use a prefix query to find resources where a specified field starts with a given value. This example searches for resources with a 'name' field starting with 'car'. ```json { "query": { "prefix": { "field": "name", "language": "en", "value": "car" } } } ``` -------------------------------- ### Product Discount Predicate Example Source: https://docs.commercetools.com/api/predicates/predicate-operators This example demonstrates a simple predicate for a Product Discount, comparing the 'sku' field to a specific value. ```plaintext sku = "AB-123" ``` -------------------------------- ### Category Order Hints Example Source: https://docs.commercetools.com/api/projects/products Provides an example of the JSON structure for category order hints. These hints control the display order of products within categories. ```json { "1d20faef-e8e1-44f4-b1b9-3a25b68fd266": "0.1234", "ed9556d2-203f-4c80-840d-79305f341ba8": "0.5678" } ``` -------------------------------- ### Product Attribute Input String Example Source: https://docs.commercetools.com/api/graphql Example of a simple string value for the 'value' field on ProductAttributeInput. ```json "\"yellow\"" ``` -------------------------------- ### Product Selection Import Request Example Source: https://docs.commercetools.com/api/import-export/type Example JSON payload for creating a product selection with individual product and variant assignments. ```json { "type" : "product-selection", "resources" : [ { "key" : "selection-001", "name" : { "en" : "Featured Products", "de" : "Empfohlene Produkte" }, "mode" : "Individual", "assignments" : [ { "product" : { "key" : "product-123", "typeId" : "product" }, "variantSelection" : { "type" : "includeOnly", "skus" : [ "SKU-1", "SKU-2" ] } } ] } ] } ``` -------------------------------- ### Example Search Request Source: https://docs.commercetools.com/api/search-query-language This example demonstrates a search request to find resources matching a specific English name and sort them by name in descending order, with a limit of 20 results. ```json { "query": { "exact": { "field": "name", "language": "en", "value": "laptop stand" } }, "sort": [ { "field": "name", "language": "en", "order": "desc" } ], "limit": 20, "offset": 0 } ``` -------------------------------- ### Example Project API Response Source: https://docs.commercetools.com/api/getting-started/make-first-api-call This is an example of the JSON response you can expect when retrieving Project settings. It includes details like project key, name, countries, currencies, and languages. ```json { "key": "{projectKey}", "name": "{projectName}", "countries": ["GB", "DE", "US"], "currencies": ["EUR", "GBP", "USD"], "languages": ["en-GB", "de-DE", "en-US"], "createdAt": "2023-10-23T12:48:51.728Z", "trialUntil": "2023-12", "messages": { "enabled": false, "deleteDaysAfterCreation": 15 }, "carts": { "deleteDaysAfterLastModification": 90, "allowAddingUnpublishedProducts": false, "countryTaxRateFallbackEnabled": false, "cartDiscountCache": { "enabled": false }, "loadParsedDiscountsEnabled": false }, "shoppingLists": { "deleteDaysAfterLastModification": 360 }, "version": 9, "searchIndexing": { "products": { "status": "Activated", "lastModifiedAt": "2023-10-23T12:50:19.191Z", "lastModifiedBy": { "isPlatformClient": true } }, "orders": { "status": "Activated", "lastModifiedAt": "2023-10-23T12:49:11.387Z", "lastModifiedBy": { "isPlatformClient": true } } } } ``` -------------------------------- ### Client Credentials Flow cURL Example Source: https://docs.commercetools.com/api/authorization Example using cURL to request an access token with client credentials. Ensure your client ID and secret are correctly formatted. ```bash $curl https://{auth_host}/oauth/token -X POST --basic --user "{clientId}:{clientSecret}" -d "grant_type=client_credentials&scope=manage_project:{projectKey}" ``` -------------------------------- ### SearchQuery Example Source: https://docs.commercetools.com/api/search-query-language An example of a SearchQuery demonstrating a compound 'and' expression to find Products with 'banana' in their English name and a Product Variant with a specific attribute value. ```APIDOC ## SearchQuery Example ### Description This example demonstrates how to construct a SearchQuery using a compound `and` expression. It searches for Products that have 'banana' in their English name and a Product Variant with the text Attribute `someattribute` equal to '12'. ### Query Structure ```json { "query": { "and": [ { "fullText": { "field": "name", "language": "en", "value": "banana" } }, { "filter": [ { "exact": { "field": "variants.attributes.someattribute", "fieldType": "text", "value": "12" } } ] } ] } } ``` ``` -------------------------------- ### Product Attribute Input Example Source: https://docs.commercetools.com/api/graphql Example of a JSON string for the 'value' field on ProductAttributeInput, representing a monetary value. ```json "{\"type\": \"centPrecision\", \"currencyCode\": \"USD\", \"centAmount\": 1000, \"fractionDigits\": 2}" ``` -------------------------------- ### Password Flow for Global Customers cURL Example Source: https://docs.commercetools.com/api/authorization Example using cURL for the password flow for global customers. This includes the grant type, username, password, and scope. ```bash $curl https://{auth_host}/oauth/{projectKey}/customers/token -X POST --basic --user "{clientId}:{clientSecret}" -d "grant_type=password&username=alice@example.com&password=secret&scope=view_published_products:{projectKey} manage_my_orders:{projectKey} manage_my_profile:{projectKey}" ``` -------------------------------- ### Predicate Examples for Shipping Methods Source: https://docs.commercetools.com/api/shipping-delivery-overview These examples demonstrate various conditions that can be used in shipping method predicates to match carts based on line items, customer groups, cart contents, and stores. ```json // matches a cart when at least one Line Item has the Custom Field attribute "eligible_for_express_shipping" set to TRUE lineItemExists(attributes.eligible_for_express_shipping = true) ``` ```json // matches a cart for all customer group except one customerGroup.id != "f6a19a23-14e3-40d0-aee2-3e612fcb1bc7" ``` ```json // matches a cart when at least one Line Item has the Custom Field attribute "bulky" set to TRUE and when at least one Line Item has the Custom Field attribute "weightInKilograms" set to a value greater than 10 lineItemExists(attributes.bulky = true) and lineItemExists(attributes.weightInKilograms > 10) ``` ```json // matches a cart with Store key "sweden-store" store.key = "sweden-store" ``` -------------------------------- ### cURL Example for API Endpoint Source: https://docs.commercetools.com/api/getting-started/use-api-reference Use this cURL example to test an API endpoint. Replace placeholders like {projectKey}, {id}, and {BEARER_TOKEN} with actual values. Obtain the token from the OAuth token endpoint. ```bash curl -X GET https://api.commercetools.com/{projectKey}/products/{id} \ -H "Authorization: Bearer {BEARER_TOKEN}" ``` -------------------------------- ### CartDiscountPatternTarget Example Source: https://docs.commercetools.com/api/projects/cartDiscounts This target uses pattern matching to select units for a discount. It defines trigger and target patterns, maximum occurrences, and selection mode. The example specifies a discount on bundles of jeans and shirts. ```json { "type": "pattern", "pattern": { "triggerPattern": [], "targetPattern": [ { "type": "CountOnLineItemUnits", "predicate": "categories.key=\"Jeans\"", "minCount": 2, "maxCount": 2 }, { "type": "CountOnLineItemUnits", "predicate": "categories.key=\"Shirt\"", "minCount": 1, "maxCount": 1 } ], "maxOccurrence": 3, "selectionMode": "Cheapest" }, "value": { "type": "absolute", "applicationMode": "EvenDistribution", "money": [ { "type": "centPrecision", "currencyCode": "USD", "centAmount": 10000, "fractionDigits": 2 } ] } } ``` -------------------------------- ### Example Request for Anonymous Token Source: https://docs.commercetools.com/api/authorization A cURL example demonstrating how to request an access token for an anonymous session. It includes specifying the grant type, scopes, and an optional `anonymous_id`. ```bash $curl https://{auth_host}/oauth/{projectKey}/anonymous/token -X POST --basic --user "{clientId}:{clientSecret}" -d "grant_type=client_credentials&scope=view_published_products:{projectKey} manage_my_orders:{projectKey} manage_my_profile:{projectKey}&anonymous_id={uniqueId}" ``` -------------------------------- ### Example response for category child count and ancestors reference Source: https://docs.commercetools.com/api/graphql Example JSON response showing the count of child categories and the IDs of ancestors, demonstrating optimized reference fetching. ```json { "data": { "category": { "childCount": 3, "ancestorsRef": [ { "id": "1fbfdc4b-b6c7-4f06-9db4-cbd4179f2a17" } ] } } } ``` -------------------------------- ### Get Product Discount by Key Source: https://docs.commercetools.com/api/projects/productDiscounts Retrieves a Product Discount by its unique key. ```APIDOC ## Get ProductDiscount by Key ### Description Retrieves a Product Discount by its unique key. ### Method GET ### Endpoint /product-discounts/key={key} ``` -------------------------------- ### Get Cart in Store by ID - HTTP Example Source: https://docs.commercetools.com/api/projects/stores Example of an HTTP GET request to retrieve a cart within a specific store. Ensure your API client has the necessary scopes, such as `manage_orders:{projectKey}:{storeKey}`. ```http GET /{projectKey}/in-store/key={storeKey}/carts/{id} ``` -------------------------------- ### Encoding Predicate with cURL Source: https://docs.commercetools.com/api/predicates/query Example using cURL to send a GET request with a URL-encoded query predicate. The `-G` parameter is necessary to ensure the method is GET when using `--data-urlencode`. ```bash $curl -sH "Authorization: Bearer ACCESS_TOKEN" -G --data-urlencode "masterData(staged(name(en="Super Product") and slug(en="super-product")))" https://api.{region}.commercetools.com/PROJECT_KEY/products ``` -------------------------------- ### Exists Query Example for SetType Source: https://docs.commercetools.com/api/projects/order-search An example demonstrating an 'exists' query on a SetType of DateType custom field. ```APIDOC ## Exists Query Example for SetType ### Description Illustrates how to perform an 'exists' query on a custom field that is a SetType of DateType. ### Example Query Searching for orders where the `custom.myDateField` (which is a SetType of DateType) contains the value `2021-05-10`: ```json { "query": { "exists": { "field": "custom.myDateField", "value": "2021-05-10", "customType": "SetType.DateType" } } } ``` ``` -------------------------------- ### Fetch Product Data for Matching Products Source: https://docs.commercetools.com/api/graphql This example shows how to retrieve detailed product data, including master variant information and pricing, for products found by the `productsSearch` query. ```APIDOC ## productsSearch (Fetch Product Data) ### Description Retrieves product data for matching products, including master variant details, pricing for specific currencies and countries, and attributes. ### Query ```graphql { productsSearch( query: {fullText: {field: "name", value: "Skirt", language: "en"}} ) { results { product { masterData{ current{ masterVariant{ sku images{ url } price ( currency: "USD" country: "US" ) { value { centAmount } } attributesRaw(includeNames: "designer"){ name value } } } } } } offset limit total } } ``` ### Parameters - **query** (SearchQuery) - Required - The search query expression, here using `fullText` to find products named 'Skirt'. ### Response #### Success Response (200) - **results** (Array) - A list of product search results, each containing detailed product information. - **product** (Product) - The detailed product data. - **masterData** (ProductMasterData) - **current** (ProductCatalogData) - **masterVariant** (ProductVariant) - **sku** (String) - **images** (Array) - **price** (Money) - Price for the specified currency and country. - **attributesRaw** (Array) - Raw attributes, filtered by name. - **offset** (Int) - The offset used for pagination. - **limit** (Int) - The limit used for pagination. - **total** (Int) - The total number of matching products. #### Response Example ```json { "results": [ { "product": { "masterData": { "current": { "masterVariant": { "sku": "SKU123", "images": [{"url": "http://example.com/image.jpg"}], "price": {"value": {"centAmount": 5000}}, "attributesRaw": [{"name": "designer", "value": "DesignerName"}] } } } } } ], "offset": 0, "limit": 10, "total": 5 } ``` ``` -------------------------------- ### Complete query for Customers with parameters and values to return Source: https://docs.commercetools.com/api/graphql A comprehensive example showing how to query multiple customers with parameters and specify the exact fields to be returned. ```APIDOC ## Complete query for Customers with parameters and values to return ```graphql title="Complete query for Customers with parameters and values to return" query ReturnCustomers { # Return up to five Customers named "John", ordered by their surname (ascending), and not including the first result customers( where: "firstName=\"John\"" sort: "lastName asc" limit: 5 offset: 1 ) { # Display the offset, count, and total offset count total results { # Return the Customer's ID, version, email, and name. id version email firstName lastName } } } ``` ``` -------------------------------- ### Custom Object Draft Example Source: https://docs.commercetools.com/api/graphql Example of a JSON string for the 'value' field on CustomObjectDraft, including various data types. ```json "{ \"stringField\": \"myVal\", \"numberField\": 123, \"boolField\": false, \"nestedObject\": { \"nestedObjectKey\": \"anotherValue\" }, \"dateField\": \"2018-10-12T14:00:00.000Z\" }" ``` -------------------------------- ### Custom Field Input Array Example Source: https://docs.commercetools.com/api/graphql Example of a JSON string representing an array of strings for the 'value' field on CustomFieldInput. ```json "[\"This is a string\", \"This is another string\"]" ``` -------------------------------- ### Upload Image by Product Key Source: https://docs.commercetools.com/api/projects/product-tailoring This example demonstrates how to upload an image to tailor a specific ProductVariant within a Product and Store using cURL. ```APIDOC ## POST /in-store/{storeKey}/products/{productID}/product-tailoring/images ### Description Uploads a binary image file to a given ProductVariantTailoring. The system converts the original image to several sizes retrievable from the CDN. ### Method POST ### Endpoint `https://api.{region}.commercetools.com/{projectKey}/in-store/{storeKey}/products/{productID}/product-tailoring/images?variant={variantId}&filename={filename}` ### Parameters #### Query Parameters - **variant** (number) - Required - The ID of the ProductVariant to tailor. - **filename** (string) - Optional - The name of the file to be uploaded. #### Request Headers - **Content-Type**: `image/jpeg` (or other supported image formats like PNG, GIF) - **Authorization**: `Bearer {token}` ### Request Example ```bash curl -X POST \ -H "Content-Type: image/jpeg" \ -H "Authorization: Bearer {token}" \ --upload-file "detail.jpg" \ "https://api.{region}.commercetools.com/{projectKey}/in-store/{storeKey}/products/{productID}/product-tailoring/images?variant=2&filename=detail.jpg" ``` ### Response #### Success Response (200 OK) Returned when all sizes of the image have been successfully uploaded to the CDN. #### Success Response (202 Accepted) Returned when the `small` size of the image has been successfully uploaded to the CDN, but the upload of the other sizes is still ongoing. #### Error Response (400 Bad Request) Returned with code `InvalidInput` and message `Unsupported image data. Not able to identify the color model of your image.` if the image is not in sRGB color space. ``` -------------------------------- ### Example response for category children and ancestors Source: https://docs.commercetools.com/api/graphql Example JSON response showing the IDs of a category's children and its ancestors. ```json { "data": { "category": { "children": [ { "id": "7900ab4b-c01c-4e73-8f10-557b84de55f5" }, { "id": "93aa3372-310f-4fa7-8ab2-986036382e4f" }, { "id": "0938dbd3-766e-48c2-b86b-31a3a3d820da" } ], "ancestors": [ { "id": "1fbfdc4b-b6c7-4f06-9db4-cbd4179f2a17" } ] } } } ``` -------------------------------- ### Complete query for creating a new resource Source: https://docs.commercetools.com/api/graphql This query demonstrates how to create a new resource by providing a draft with required fields and specifying the values to return upon creation. ```graphql mutation CreateDiscountCode { # The action for creating a Discount Code createDiscountCode( # The DiscountCodeDraft and its required fields draft: { code: "SAVE25" isActive: true cartDiscounts: { typeId: "cart-discount", id: "{cartDiscountID}" } } ) { # The values to return code isActive } } ``` -------------------------------- ### Custom Field Input Object Example Source: https://docs.commercetools.com/api/graphql Example of a JSON string representing an object for the 'value' field on CustomFieldInput, referencing a product. ```json "{\"id\": \"b911b62d-353a-4388-93ee-8d488d9af962\", \"typeId\": \"product\"}" ``` -------------------------------- ### Request Product with Expanded Product Type and Tax Category Source: https://docs.commercetools.com/api/general-concepts This GET request expands both the 'productType' and 'taxCategory' references for a specific product. Ensure you replace placeholders like '', '', and '' with your actual values. ```bash GET https://api.{region}.commercetools.com//products/?expand=productType&expand=taxCategory ``` -------------------------------- ### Read Resources (GET) Source: https://docs.commercetools.com/api/getting-started/manage-resources Use the HTTP GET method to retrieve a collection of resources. This is typically used for listing or querying resources. ```http GET https://api.{region}.commercetools.com/{projectKey}/{resources} ``` -------------------------------- ### Querying Products with Multiple Predicates (URL Encoded) Source: https://docs.commercetools.com/api/predicates/query Example of constructing a URL-encoded query predicate for Products, combining slug and name conditions. ```bash # decoded predicate masterData(current(slug(en="peter-42") and name(en="Peter"))) # URL-encoded predicate masterData%28current%28slug%28en%3D%22peter-42%22%29%20and%20name%28en%3D%22Peter%22%29%29%29 ``` -------------------------------- ### Example Custom Object with Array of Review References Source: https://docs.commercetools.com/api/graphql This JSON illustrates a Custom Object containing an array of references to Review resources. ```json { "id": "687e312c-600a-4544-af21-ca1f6313bfde", "version": 7, ... "container": "containerForReferences", "key": "listOfReferences", "value": { "reviewReferences": [ { "id": "6e46a6fc-bdee-4159-a07d-ce7b8f6f130f", "typeId": "review" }, { "id": "e8f32564-7963-4c8a-906e-cdc675aba9e8", "typeId": "review" }, { "id": "9902febb-6208-4322-9d7a-d622ec3e4f4f", "typeId": "review" } ] } } ``` -------------------------------- ### Create Store Source: https://docs.commercetools.com/api/projects/stores Creates a new store with the provided details. ```APIDOC ## Create Store ### Description Creates a new store. ### Method POST ### Endpoint /stores ### Request Body - **body** (StoreDraft) - Required - The draft object to create the store. ``` -------------------------------- ### Get VariantProjection Source: https://docs.commercetools.com/api/projects/variant-projections Retrieves a Variant Projection. By default, it returns the current (published) representation. Use the `staged=true` query parameter to get the staged (draft) representation. ```APIDOC ## Get VariantProjection ### Description Retrieves a Variant Projection. By default, it returns the current (published) representation. Use the `staged=true` query parameter to get the staged (draft) representation. ### Method GET ### Endpoint `/variants` ### Query Parameters - **staged** (boolean) - Optional - If `true`, returns the staged (draft) representation. Defaults to `false` (current, published). - **localeProjection** (string) - Optional - Filters localized fields to specific locales. Can be specified multiple times. - **priceCurrency** (string) - Optional - Filters prices based on currency. - **priceCountry** (string) - Optional - Filters prices based on country. - **priceCustomerGroup** (string) - Optional - Filters prices based on customer group. - **priceChannel** (string) - Optional - Filters prices based on channel. - **filter[attributes]** (string) - Optional - Filters attributes. Use `attributeName` to include or `-attributeName` to exclude. ### Response #### Success Response (200) - **VariantProjectionPagedQueryResponse** (object) - A paged response containing Variant Projections. ``` -------------------------------- ### Query Customers with parameters Source: https://docs.commercetools.com/api/graphql Demonstrates how to add query parameters such as `where`, `sort`, `limit`, and `offset` to a customer query. ```APIDOC ## Query Customers with parameters Query parameters must be enclosed in `()` next to the endpoint: ```graphql title="Query Customers with parameters" query ReturnCustomers { # Return up to five Customers named "John", ordered by their surname (ascending), and not including the first result customers(where: "firstName=\"John\"", sort: "lastName asc", limit: 5, offset: 1) { } } ``` ``` -------------------------------- ### cURL Request for Project Settings Source: https://docs.commercetools.com/api/getting-started/make-first-api-call This cURL command demonstrates how to make a GET request to fetch Project settings, including the necessary Authorization header. ```curl curl https://api.{region}.commercetools.com/{projectKey}/ -X GET -H "Authorization: Bearer ${BEARER_TOKEN}" ``` -------------------------------- ### Combine Product Update Actions Source: https://docs.commercetools.com/api/general-concepts This example demonstrates how to combine multiple update actions, such as setting a title and text, in a single request to update a product. Ensure update actions are ordered correctly and consider the transactional nature of the request. ```json { "id": "a136fd9e-bc29-4d05-813f-350b248aefd8", "version": 1, "actions": [ { "action": "setTitle", "title": "My title" }, { "action": "setText", "text": "My text" } ] } ``` -------------------------------- ### Making API Calls with cURL Source: https://docs.commercetools.com/api/getting-started/use-api-reference Each endpoint contains an example request in cURL syntax that you can use to test the endpoint. The example shows the required parameters and the expected JSON response. Note that the cURL command contains placeholders for path variables like {projectKey} or {id} that you must replace with actual values. You must also replace {BEARER_TOKEN} with a valid token, which you can obtain via the OAuth token endpoint. ```APIDOC ## cURL examples Each endpoint contains an example request in `cURL` syntax that you can use to test the endpoint. The example shows the required parameters and the expected JSON response. Note that the cURL command contains placeholders for path variables like `{projectKey}` or `{id}` that you must replace with actual values. You must also replace `{BEARER_TOKEN}` with a valid token, which you can obtain via the [OAuth token endpoint](https://docs.commercetools.com/api/authorization.md#request-an-access-token-using-the-internal-oauth-20-service). ``` -------------------------------- ### Product Variant Patch Request Example Source: https://docs.commercetools.com/api/import-export/type Example JSON payload for updating product variants, including boolean, null, localized text, and localized text set attributes. ```json { "type" : "product-variant-patch", "patches" : [ { "productVariant" : { "typeId" : "product-variant", "key" : "red-t-shirt" }, "attributes" : { "attribute-to-update" : { "type" : "boolean", "value" : true }, "name-of-attribute-to-delete" : null, "name-of-localized-attribute-to-update" : { "type" : "ltext", "value" : { "en" : "Existing field", "es" : null, "de" : "Updating field" } }, "name-of-localized-attribute-set-to-update" : { "type" : "ltext-set", "value" : [ { "en" : "Existing field", "es" : null, "de" : "Updating field", "br" : "New field" }, { "en" : "Another Existing field", "es" : null, "de" : "Another Updating field", "br" : "Another New field" } ] } }, "staged" : false } ] } ``` -------------------------------- ### Create a Cart in a specific Store Source: https://docs.commercetools.com/api/graphql This example demonstrates how to create a cart within a specific Store using the `storeKey` argument in the `createCart` mutation. ```APIDOC ## Create a Cart in a Store ### Description Creates a new cart within the context of a specified Store. ### GraphQL Operation ```graphql mutation { createCart(draft: { currency: "USD" }, storeKey: "luxury-brand") { id } } ``` ### Parameters #### Mutation Arguments - **draft** (CartDraftInput!) - Required - The draft object containing the initial data for the cart. - **currency** (String!) - Required - The currency for the cart. - **storeKey** (String) - Optional - The key of the Store in which to create the cart. ### Response #### Success Response (200) - **createCart** - Object - The created cart. - **id** - String - The ID of the newly created cart. ### Authorization - Project-wide scopes (e.g., `manage_orders:project-key`). - Store-based scopes (e.g., `manage_orders:project-key:luxury-brand`). ``` -------------------------------- ### Example SearchQuery for Products Source: https://docs.commercetools.com/api/search-query-language Searches for products with 'banana' in their English name and a variant attribute 'someattribute' equal to '12'. ```json { "query": { "and": [ { "fullText": { "field": "name", "language": "en", "value": "banana" } }, { "filter": [ { "exact": { "field": "variants.attributes.someattribute", "fieldType": "text", "value": "12" } } ] } ] } } ``` -------------------------------- ### Example Error Message - Incompatible Nesting Levels Source: https://docs.commercetools.com/api/projects/product-search This bash snippet shows an example error message from the API, detailing incompatible expression nesting levels that failed query validation. ```bash Expressions nesting level are incompatible: expr1= [ and( exact("variants.prices.currencyCode", ...), exact("variants.prices.channel", ...) ) ], expr2=[ or( and( fullText("variants.parentProduct.name", ...), exact("variants.parentProduct.productType", ...) ), exact("variants.prices.country", ...) ) ] ``` -------------------------------- ### Term Facet Example Source: https://docs.commercetools.com/api/projects/products-search This example demonstrates how to request term facets for the `colors` and `size` attributes using the `facet` query parameter. This helps in obtaining counts for all occurring values of these attributes. ```APIDOC ## GET /{projectKey}/product-projections/search?facet=variants.attributes.colors&facet=variants.attributes.size:"m" ### Description Requests term facets for the `colors` and `size` attributes. The `size` attribute is filtered to only include products with size "m". ### Method GET ### Endpoint `/{projectKey}/product-projections/search` ### Query Parameters - **facet** (string) - Required - Specifies the facet expression. Can be repeated to request multiple facets. - `variants.attributes.colors`: Facets by all occurring values of the `colors` attribute. - `variants.attributes.size:"m"`: Facets by all occurring values of the `size` attribute, filtered for the value "m". ### Response #### Success Response (200) - **facets** (object) - Contains the calculated facet counts for the requested attributes. ``` -------------------------------- ### Example response for checking resource existence Source: https://docs.commercetools.com/api/graphql A typical JSON response indicating whether a resource exists. 'true' means at least one resource matches the query, 'false' means none do. ```json { "data": { "customers": { "exists": true } } } ``` -------------------------------- ### Query GraphQL API with C# SDK Source: https://docs.commercetools.com/api/graphql An example of querying the GraphQL API using the C# SDK. This code snippet shows how to construct a GraphQL request with query, operation name, and variables to retrieve product details. ```csharp var graphQLQuery = new GraphQLRequest(){ Query = "query getProductByKey($productKey: String!) { product(key: $productKey) { id version }}", OperationName = "getProductByKey", Variables = new GraphQLVariablesMap() { { "productKey", "a-product-key" } } }; var graphQLCall = await projectApiRoot .Graphql() .Post(graphQLQuery) .ExecuteAsync(); // Output the response Console.WriteLine(graphQLCall.Data.ToString()); ``` -------------------------------- ### Product Projection Search with GET Source: https://docs.commercetools.com/api/projects/products-search Retrieves product projections matching full-text search or filter criteria using a GET request. This method is suitable for simpler queries due to URL length limitations. ```APIDOC ## GET /product-projections/search ### Description Use Product Projection Search to retrieve Product Projections matching full-text search, or filter criteria, and to let the API calculate facets about product information. Perform API calls either with GET or with POST. ### Method GET ### Endpoint https://api.{region}.commercetools.com/{projectKey}/product-projections/search ### Parameters #### Path Parameters - **region** (string) - Required - Region in which the Project is hosted. - **projectKey** (string) - Required - `key` of the Project. #### Query Parameters - **markMatchingVariants** (boolean) - Optional - Set to `true` to mark matching variants in the search result. Default: `false` - **text.** (string) - Optional - The text to analyze and search for. The parameter must include the language in form of a Locale. The content to search in, that means the full-text search, is only performed in the localized Product content of the specified language. The parameter can be passed multiple times. - **fuzzy** (boolean) - Optional - Set to `true` to apply fuzzy search on the `text` to analyze. Default: `false` - **fuzzyLevel** (int) - Optional - Set this parameter to overwrite the default fuzzy level. Only applicable if `fuzzy` is `true`. Minimum: `0`, Maximum: `2` - **filter.query** (string) - Optional - Applies a filter to the query results before facets are calculated. This parameter has an impact on facet counts. The parameter can be passed multiple times. - **filter** (string) - Optional - Applies a filter to the query results after facets are calculated. This parameter does not have an impact on facet counts. Use this parameter in combination with the `facet` and `filter.facets` parameters for multi-select faceting. The parameter can be passed multiple times. - **facet** (string) - Optional - Requests calculation of facets. The parameter can be passed multiple times. - **filter.facets** (string) - Optional - Applies a filter to the calculated facet results, not to the Products returned with the query results. Use this parameter in combination with the `facet` and `filter` parameters for multi-select faceting. The parameter can be passed multiple times. - **sort** (string) - Optional - Controls sorting of results. Use this parameter multiple times to sort by multiple fields. ### Request Example (No example provided in source) ### Response #### Success Response (200) (No specific fields documented in source) #### Response Example (No example provided in source) ``` -------------------------------- ### Create Product Selections using Import API Source: https://docs.commercetools.com/api/import-export/type Use this endpoint to create an Import Request for Product Selections. Requires 'manage_product_selections' and 'view_product_selections' scopes. ```bash curl https://import.{region}.commercetools.com/{projectKey}/product-selections/import-containers/{importContainerKey} -i \ --header "Authorization: Bearer ${BEARER_TOKEN}" \ --header 'Content-Type: application/json' \ --data-binary @- << DATA { "type" : "product-selection", "resources" : [ { "key" : "selection-001", "name" : { "en" : "Featured Products", "de" : "Empfohlene Produkte" }, "mode" : "Individual", "assignments" : [ { "product" : { "key" : "product-123", "typeId" : "product" }, "variantSelection" : { "type" : "includeOnly", "skus" : [ "SKU-1", "SKU-2" ] } } ] } ] } DATA ``` -------------------------------- ### Product Projection Search with Term Facets for Attributes Source: https://docs.commercetools.com/api/projects/product-projection-search This example demonstrates how to request term facets for custom attributes like 'colors' and 'size' in product projections. It shows how to specify attribute names in the facet query parameter. ```bash GET /{projectKey}/product-projections/search?facet%3Dvariants.attributes.colors%26facet%3Dvariants.attributes.size%3A%22m%22 ``` -------------------------------- ### Distinct Facet Example Source: https://docs.commercetools.com/api/projects/product-search This example demonstrates how to configure a distinct facet in a ProductSearchRequest to count occurrences of distinct values for an attribute, such as product sizes. The response provides buckets with keys representing the distinct values and their corresponding counts. ```APIDOC ## Distinct Facet Configuration ### Description Configures a distinct facet to count occurrences of distinct values for a specified attribute. ### Request Body Example ```json { "facets": [ { "distinct": { "name": "sizes", "field": "variants.attributes.size", "fieldType": "number", "limit": 50 } } ] } ``` ### Response Example (Success - 200) ```json { "facets": [ { "name": "sizes", "buckets": [ { "key": "43", "count": 112 }, { "key": "44", "count": 63 }, { "key": "45", "count": 34 } ] } ] } ``` ``` -------------------------------- ### Get State by Key Source: https://docs.commercetools.com/api/projects/states Retrieves a state by its key. ```APIDOC ## Get State by Key ### Description Retrieves a state by its key. ### Method GET ### Endpoint /states/key={key} ### Parameters #### Path Parameters - **key** (string) - Required - The key of the state. #### Query Parameters None specified. ``` -------------------------------- ### Query GraphQL API with Java SDK Source: https://docs.commercetools.com/api/graphql This Java SDK example demonstrates querying the GraphQL API. It utilizes type-safe GraphQL support provided by the SDK's GraphQL module. The query fetches a product by its key. ```java GraphQLRequest graphQLQuery = GraphQLRequestBuilder.of() .query("query getProductByKey($productKey: String!) { product(key: $productKey) { id version }}") .operationName("getProductByKey") .variables(GraphQLVariablesMapBuilder.of() .addValue("productKey", "a-product-key") .build()) .build(); GraphQLResponse graphQLCall = apiRoot .graphql() .post(graphQLQuery) .executeBlocking() .getBody(); System.out.println(graphQLCall.getData()); ``` -------------------------------- ### Get ImportOperation Source: https://docs.commercetools.com/api/import-export/overview View the status of a specific ImportOperation. ```APIDOC ## Get ImportOperation ### Description View the status of a specific ImportOperation. ### Method GET ### Endpoint /import/operations/{importOperationId} ### Parameters #### Path Parameters - **importOperationId** (string) - Required - The ID of the ImportOperation to retrieve. ### Response #### Success Response (200) - **id** (string) - The ID of the ImportOperation. - **status** (string) - The current status of the ImportOperation. ```