Get product category graphql query

Hi everybody,

I’ve never used GraphQL (only REST) and I just found out that Product Category is not available in the REST API and it’s something that I need to be able to fetch based on a product id.

Can someone help me with what does the query look like to fetch a product category based on a product id and how to set a product category on a product given its id?

Overall I find it disconcerting that with an API offering like Shopify something is simply only available in GraphQL and not REST. I mean, when someone starts and makes a choice of what to use, this information won’t be available. Furthermore, as far as I understand proper practices, the goal of an API is to expose functionalities of a system. GraphQL simply allows you to have more granularity so you dont have to fetch the whole resource. But never I believe has the intention been that some stuff simply is not exposed in REST vs GraphQL. Seems like a poor practice to implement especially for a large company like Shopify.

1 Like

Hello @mmlacabra

To fetch a product category based on a product id, you can use the following GraphQL query:

query {
  product(id: "123456") {
    productCategory {
      id
      name
      handle
    }
  }
}

To set a product category on a product given its id, you can use the following GraphQL mutation:

mutation {
  updateProduct(id: "123456", productCategoryId: "789012") {
    product {
      productCategory {
        id
        name
        handle
      }
    }
  }
}

I understand your frustration with Shopify’s decision to only make Product Category available in GraphQL. It can be frustrating when you’re used to working with a particular API and then you find out that some functionality is only available in a different API.

However, I think it’s important to remember that GraphQL is a newer API and it’s still evolving. Shopify is likely still working on adding more functionality to the REST API, but in the meantime, GraphQL is a great option if you need access to features that aren’t available in the REST API.