Use the GraphQL Explorer and the SDK

Learn which tools are required to send GraphQL queries and mutations in commercetools.

Ask about this Page
Copy for LLM
View as Markdown

After completing this page, you should be able to:

  • Explain how to navigate the GraphQL Explorer interface.

  • Describe how to send a GraphQL request using one of the commercetools SDKs.

  • Explain how to validate a GraphQL operation before executing it against a Project.

On this page, we will look in more detail at sending GraphQL requests. We'll explore two options: one using the GraphQL Explorer in the Merchant Center, and the other using the SDK.

GraphQL Explorer

The GraphQL Explorer is a built-in IDE in the Merchant Center for running GraphQL queries and mutations against your Project. To access it, go to Settings > Developer settings and click the GraphQL Explorer tab.
The GraphQL Explorer provides a query editor with autocomplete, a results window, and a Documentation Explorer for browsing the schema. Additional features include query prettification and history. For a full walkthrough of the interface, see GraphQL Explorer in the Merchant Center documentation.

Use the SDKs

How can we begin to use GraphQL in our code? Just like our commercetools SDKs provide help in using the REST APIs, they also provide help in using GraphQL. For additional SDK examples, including TypeScript, Java, and .NET, see Using an SDK in the GraphQL API reference.
See our examples below for creating the Customer query using sort and where parameters that we explored earlier.

TypeScript

Java

C#


import { apiRoot } from '../impl/apiClient.js';

const query = `
query {
 customers(where: "firstName=\\"Martha\\"", sort: "id asc" ) {
   results {
     firstName
     lastName
     email
   }
 }
}
`;

async function customerFetch() {
  try {
    const response = await apiRoot
      .graphql()
      .post({ body: { query } })
      .execute();

    console.log('Success', JSON.stringify(response.body, null, 2));
  } catch (error) {
    console.log(JSON.stringify(error, null, 2));
  }
}

customerFetch();

The commercetools Java SDK has a module that provides GraphQL support. It generates a type-safe query and projection builder. Results can be mapped to the correct response type.


String query = "{ customers(sort: [\"id asc\"], where: \"firstName=\\\"Martha\\\"\") { total results { firstName lastName email } } }";

GraphQLResponse response = client
  .graphql()
  .post(GraphQLRequest.builder().query(query).build())
  .executeBlocking()
  .getBody();

Map<String, Object> data = response.getData();
Map<String, Object> customersData = (Map<String, Object>) data.get("customers");
List<Map<String, Object>> results = (List<Map<String, Object>>) customersData.get("results");

logger.info("Total Customers: " + customersData.get("total"));
logger.info("First" + "\t" + "Last" + "\t" + "Email");
logger.info("-----" + "\t" + "----" + "\t" + "-----");
results.forEach(result ->
  logger.info(
    result.get("firstName") +
    "\t" +
    result.get("lastName") +
    "\t" +
    result.get("email")
  )
);
client.close();

The Composable Commerce .NET SDK also provides GraphQL support. This example sends the operation as a raw query string and reads the results from the JSON response.


using System.Text.Json;

var query = @"
query {
  customers(where: ""firstName=\""Martha\"""", sort: ""id asc"" ) {
    results {
      firstName
      lastName
      email
    }
  }
}
";

var response = await projectApiRoot
  .Graphql()
  .Post(new GraphQLRequest { Query = query })
  .ExecuteAsync();

var data = (JsonElement)response.Data;
var results = data
  .GetProperty("customers")
  .GetProperty("results");

logger.LogInformation("First" + "\t" + "Last" + "\t" + "Email");
logger.LogInformation("-----" + "\t" + "----" + "\t" + "-----");
foreach (var result in results.EnumerateArray())
{
  logger.LogInformation(
    result.GetProperty("firstName").GetString() +
    "\t" +
    result.GetProperty("lastName").GetString() +
    "\t" +
    result.GetProperty("email").GetString()
  );
}

Which outputs the following (modified to remove some logger info):

{
  "data": {
    "customers": {
      "results": [
        {
          "firstName": "Martha",
          "lastName": "Jones",
          "email": "martha@example.uk"
        },
        {
          "firstName": "Martha",
          "lastName": "Schmidt",
          "email": "martha@example.de"
        },
        {
          "firstName": "Martha",
          "lastName": "Robinson",
          "email": "martha@example.com"
        }
      ]
    }
  }
}

Check a query before you run it

A GraphQL operation can be syntactically valid while still referring to a field, argument, or mutation that does not exist in the commercetools schema. Check the operation before you execute it so that schema mistakes are separate from authentication, Project configuration, and data errors.

If you use the AI plugin, ask your coding agent to run commercetools-graphql-validate with the complete query or mutation. The tool checks the operation against the public commercetools GraphQL schema and reports issues such as unknown fields, incorrect argument types, and missing required fields.

Validation is read-only. It does not execute the operation, inspect data in your Project, or validate Project-specific configuration. After validation succeeds, use either the GraphQL Explorer or an SDK to run the operation.

For the tool arguments and response format, see Knowledge MCP.

Key Takeaways

  • The GraphQL Explorer and SDKs execute operations against your Project.
  • GraphQL validation checks an operation against the public schema without executing it.
  • A valid operation can still fail because of authorization, Project configuration, or data.

Test your knowledge