Can anyone Provide a sample code to assign Product Category on via GraphQL Api

Can anyone Provide a sample code to assign Product Category on via GraphQL Api

jchuku
Visitor
1 0 0

I have spent my entire day trying to figure this out even with all the documentation on it and I can seem to hack it!
Please if anyone can provide a sample it would mean a lot! You'd think shopify will have an actual use case template for novice by now instead of deprecating everything that works just fine

Reply 1 (1)

DaisyVo
Shopify Partner
3794 412 499

Hi @jchuku 

I totally get your frustration—Shopify’s documentation can be overwhelming, especially when things keep changing. Assigning a product to a category via GraphQL isn’t as straightforward as it should be, but I’ve got you covered with a working example.

Assigning a Product to a Category via GraphQL API

Since Shopify has moved to the new "Collection" system and deprecated some old methods, you’ll need to use the productUpdate mutation and link the product to a collection (which acts as a category). Here’s a sample GraphQL request:

Step 1: Get the Collection ID (Category ID)

Before assigning a product, you need the ID of the collection where you want to place the product.

 

{

  collections(first: 10) {

    edges {

      node {

        id

        title

      }

    }

  }

}

 

This will return the list of collections (categories) with their IDs.

Step 2: Assign the Product to the Collection

Now, you need to use the collectionAddProducts mutation to add the product to the category.

 

mutation {

  collectionAddProducts(

    id: "gid://shopify/Collection/1234567890"  # Replace with your collection ID

    productIds: ["gid://shopify/Product/9876543210"]  # Replace with your product ID

  ) {

    collection {

      id

      title

    }

    userErrors {

      field

      message

    }

  }

}

 

Alternative: Assign Product Type or Tags (If Needed)

If you’re just trying to categorize products, another approach is to update the product type or tags:

 

mutation {

  productUpdate(

    input: {

      id: "gid://shopify/Product/9876543210"

      productType: "T-Shirts"  # Assigns a product category

      tags: ["Men", "Casual"]  # Adds tags for filtering

    }

  ) {

    product {

      id

      productType

      tags

    }

    userErrors {

      field

      message

    }

  }

}

 

Final Thoughts

Shopify really should provide better beginner-friendly templates for these basic tasks, instead of just updating APIs and deprecating stuff. But for now, this should get you going!

Let me know if you run into any issues—I’m happy to help.

If you need any other assistance, I am willing to help.
Best regards,
Daisy.

Please let us know if our reply is helpful by giving it a Like or marking it as a Solution!

Avada SEO & Image Optimizer - The #1 SEO solution