javacommercetools

How to get category by name?


I recently work with commerce tools platform and I have such a question.

I have this query:

CompletionStage<List<Category>> stage = QueryExecutionUtils.queryAll(client, CategoryQuery.of().byName(Locale.ENGLISH, "cat1"));
        final CompletableFuture<List<Category>> result = stage.toCompletableFuture();
        return result.get().get(0);

Is there a way to return just a Category instead of List.get(0) and how it can be done?


Solution

  • Thanks for submitting this question. There is no unique constraint for the name field on categories. For this reason we cannot guarantee that the API will only return one result. With the name query you will get paged results and will have to pull the first entry from the list. Both key and id are both unique so you could query for either of those and get just the unique category. You can view the representation of categories in the docs here. https://docs.commercetools.com/http-api-projects-categories#category

    Hope this helps!