Insert asset files in shopify theme programatically using Asset API

Insert asset files in shopify theme programatically using Asset API

Are you a shopify app developer? Then you may have come accross the situation where you may need to add the asset file (like images or may be liquid files under snippets/sections/templates) programatically through shopify API. The scenario for this use case is that you may need to add a liquid file to the theme when a merchant installs your app in their shopify store. This short tutorial will guide you through the use of the shopify Asset API in rails and let you insert the asset files in shopify theme programatically.

This tutorial considers you have the understanding of Ruby on Rails platform and have knowledge on building basic shopify App. For quick tutorial on how you can develop shopify app in 5 minutes check out . To learn ruby on rails I would suggest you to read . Before beginning this quick tutorial please have a look into Shopify asset API . This list out the endpoints that shopify provides to allow the app to interact with shopify store assets.

Now let’s begin. If you have read my previous blog on how to modify the content of the liquid file you can see the detail implementation of Asset API in rails there.

The code snippet for adding the asset file is shown below

Code breakdown

Let me explain above code snippet line by line.

First line creates an object for Asset API.

second and third line sets the key and source of the file. Remember key should have the folder name under which the file should go. For example templates/sections/snippets/assets .

The source is the file which is being uploaded through API. It can be any Url that contains the file. For this instance I have uploaded a test liquid file on shopify files section and used that URL.

And the last line saves the file.

Note: This will save the file to the theme which is currently active.

That’s all for saving the asset file to shopify theme.

It’s easy isn’t it? Now you may think where should I add this code snippet. Actually it completely depends on the use case but mostly you add the files through API for once when the app get installed. So you should choose this to put under a method which is called once when the app gets installed. For example you can look into the controller which handles the recurring application charge. You can add this code snippet after the recurring application charge get saved. As shown below:

That’s it. Now you can insert the asset files in shopify theme programatically through  Shopify Asset API.