Automating your Shopify tasks with Mechanic
Tags: shopify, mechanic, ecommerce
Published: 2021-03-12 02:39:13

Running an e-commerce store on Shopify is not only selling products through various sales channels and interacting with customers. 

A big part of the process involves manual and repetitive tasks, like creating products, managing inventory, or fulfilling orders. 

Enters [**Mechanic**](https://apps.shopify.com/mechanic), a Shopify App that allows merchants to automate tasks. It was written by Isaac Bowen, a person I admire a lot, and it has a very active community of developers. I have started working with Mechanic last year, but I was mostly modifying tasks already created by other developers in my team. 

In the past few weeks, I have been diving into the Mechanic documentation to understand how to build tasks in their entirety and on my own. There are a lot of new concepts I am encountering, mainly related to building GraphQL queries to get information about Shopify objects, as well as mutations to modify those Shopify objects.

In this article you will find some general information to get started with Mechanic. The app [documentation](https://docs.usemechanic.com/article/421-welcome) is really good, but I was very lost at the beginning so my notes might come in handy to other Shopify theme developers.

###Tasks and events

As a developer, I use Mechanic to write tasks, pieces of code that respond to events. There are many types of events available in Mechanic and they might be coming from Shopify, from incoming email, from webhooks, etc. You specify the event your task responds to in the "subscriptions" field of the Mechanic task.  When the event happens, it triggers the Mechanic task, which in turn will execute the actions defined in the code.

Here are some basic events available for Mechanic tasks, I'll explain each one in a couple of sentences. 

```
shopify/orders/create
mechanic/user/trigger
mechanic/scheduler/tuesday+9.hours
```

The first example `shopify/orders/create` triggers the Mechanic task each time a new order is created. It responds to a Shopify webhook and the event will have information about that specific order, which you can then use in your task. 

If you want to allow the user to trigger the task by clicking on a button, you should use the `mechanic/user/trigger` subscription. For example, I have used this event subscription, in addition to a scheduler event `mechanic/scheduler/daily` to run a bulk scan of all the products in my store every day at midnight and check that all their variants have a price. This way my client can rely on the scheduled task, but can manually run it whenever they need.
If you want to schedule a task for a specific time of the day, or a specific day of the week, you can play around with the `mechanic/scheduler` event - the last example `mechanic/scheduler/tuesday+9.hours` runs every Tuesday at 9am.

You can find a comprehensive list of the events available in Mechanic [here](https://docs.usemechanic.com/article/416-all-event-topics)

###Querying Shopify

Many of the tasks I have worked on required gathering data about a specific Shopify object and then, if the object met the specified criteria, perform an action on said object. 
Generally speaking, Mechanic offers three ways of fetching data from Shopify: 

- Liquid objects
- GraphQL
- GraphQL bulk operations

Liquid objects return data from Shopify's REST admin API, while GraphQL and GraphQL bulk operations return data from the Shopify GraphQL's API. The key difference between the two APIs regards the way data is fetched: GraphQL queries the endpoint knowing already what data to expect, while REST retrieves all data available for that specific object.

Which API is more appropriate to the task you are looking to build? In short, you should use Liquid objects when your Mechanic event is already returning an object with the data you need (for example in the case of `shopify/orders/create` already returns the order) or if you are querying a small amount of data (if you are querying `shop.customers` and you only have a few hundreds customers in your store).
On the other hand, you should use the GraphQL if you have a large amount of data to scan (GraphQL bulk operations if it's very large) and if you already know what information you want to retrieve for that specific object. 

Let me walk you through you a couple of examples. 

####Example: REST API
My task needs to tag a customer after he orders. In this case, my best option is to use Shopify's REST API and subscribe to the `shopify/orders/create` event topic. 

The task will run every time a new order is created in Shopify and it look for the customer id within the order. Then, I using Resourceful REST, the task will perform a "shopify" action and it will add the tag "ordered" to the customer. 

```
{% action "shopify" %}
  [
    "put",
    "/admin/customers/{{ order.customer.id }}.json",
    {
      "customer": {
        "tags": {{ order.customer.tags | add_tag: "ordered" | json }}
      }
    }
  ]
{% endaction %}
``` 

####Example: GraphQL bulk operations
My task needs to scan all products of the store and apply a tag if any of the product variants have a specific metafield.

In order to achieve this, I am going to use a ***bulk operation***, which sends Shopify a query that might return a large amount of data. As mentioned in the Mechanic documentation, "*when the query is complete, the Mechanic task is notified (with a "mechanic/shopify/bulk_operation" event), and the task then processes the query's results.*"

My task subscribes to the `mechanic/shopify/bulk_operation` as an additional event topic.

```
mechanic/user/trigger
mechanic/shopify/bulk_operation
mechanic/scheduler/daily+8.hours
```

Within my task, I have setup the script to watch for this event topic, using the bulkOperation variable to access the bulk operation's results.

I will go into more details of GraphQL and bulk operations in my next article, but here are some helpful links if you want to take a look at the documentation:
- [Shopify REST admin API reference](https://shopify.dev/docs/admin-api/rest/reference) 
- [GraphQL admin API reference](https://shopify.dev/docs/admin-api/graphql/reference)
- [Querying Shopify - Mechanic documentation](https://docs.usemechanic.com/article/358-querying-shopify#graphql-with-bulk-operations)