How to Easily Create a Product via GraphQL

Ardee Aram

GraphQL

Our objective in this exercise is to be able to create a product in Shopify using GraphQL.

In my previous post, I showed you how to retrieve Shopify data via GraphQL. This time, I’ll show you how to add data (more specifically, a product) via GraphQL.

You can click here to view reference code used for this exercise.

To get the most out of this, I suggest you quickly setup your own Shopify app on your development environment. Run, test, play around, and even destroy the code. You will appreciate this guide more, and you will learn faster.

As that good old Chinese proverb says (now a cornerstone of my life), “I hear, I forget. I see, I remember, I do, I understand.”

I hear, I forget.
I see, I remember.
I do, I understand.
- Chinese Proverb.

Let’s get started, shall we?

Creating a new product

1.) Build your GraphQL mutation query

All of our GraphQL statements, whether query or mutation, will be plain old strings, which then be placed inside a gql tagged template function (Line 3). The gql function converts our string query into a syntax tree object that the Apollo GraphQL client readily understands.

2.) Create a function that will execute your mutation

Once our mutation query is all set and ready, we use the useMutation hook to create a function that will be executed at will, and several variables that act as references to return data and metadata.

3.) Invoke your function and capture results

After all that preparation, this is where the magic actually happens. We chose an event when we want the query to be executed, then we pull the trigger. In this example, we choose a button click (i.e, form submission) as our event trigger.

What we are looking at is a form with the following Polaris components:

We also observe the following:

If the reference application is run correctly, you should see something like this:

Graphql Admin API Mutation Example

And we’re done! :)

Next up, let’s see how we can sell our Shopify app masterpiece at the Shopify app store.