Home » Blogs » How to Use Input Variables in Shopify Functions

How to Use Input Variables in Shopify Functions?

What is the Shopify Function?

Shopify recently introduced Shopify Function which enables developers to build customized solutions for the stores. By using Shopify Function developers can create and deploy serverless solutions by which there is no dependency on server and provides smooth functionality.

Why Use Input Variables in Shopify Functions?

As we are aware of input and output files in shopify functions which plays a vital role in function.

For input we use run.graphql file and for output we use run file.

We can use the run.graphql file to provide inputs for the function which uses an input query.

Example:

run.graphql

Input.json

input-json-variables-functions

In input query we can pass variables which allows developers to use merchant configured values in the function.

Example:  hasTags, hasAnyTags, isAnyCollection etc, we can provide input variables to these.

Requirement:

  • Knowledge of metafields and APIS.
  • Created a Shopify Function.

Implementation:

Let’s find out whether the product added to the cart has any tags associated with it.

Step 1: Write and input query

run.graphql file.

Here we’re using the input variable for the product to check if it has provided tags.

Step 2: Configure Metafields and APIs

Incorporate metafields namespaces and keys into the extensions.toml file. These metafields store input variable values, ensuring consistency across Shopify Function executions.

Note: You can use any namespace and key but make sure you’re using the same  for  metafields.

Specify which metafields contain input variables value.

Step 3: Run API for Function

Execute the necessary APIs to implement Shopify Functions. This involves running the function’s API, such as discountAutomaticAppCreate, to apply discounts based on input variables like product tags.

Mutation:

Variables:

Here we’re creating a discount. In this example we’re using the Product discount function. As you can see we have saved tags data to function metafields. We can set value using the metafield on the mutation on your function owner.

Step 4: Add Products to Cart

To add products with specific tags to the cart, use Shopify’s cart management APIs.

We have added two products, one of which has tags assigned, as shown below.

Output:

As you can see the tags we pass through input variables, also we can see functions executed and provided product tags and their status whether the product has tags or not.

Conclusion

This is the very basic implementation of input variables in functions for the understanding. But one can use it more powerfully. By using input variables we can make more dynamic solutions and applications and can make more use of shopify functions.

Leave A Comment