Access Shopify Asset API from rails App

Access Shopify Asset API from rails App

Hey Fellas!!

This post is a part of shopify app development in rails. You may be aware that shopify let’s you access the assets of your shopify store which could be read and modified from your app. Shopify’s assets API lets you access the store theme and its liquid files. You can programatically add new liquid files and also modify the existing files.

I came across this requirement but didn’t find complete resource of its implementation, so I thought writing about it.

So without any delay let’s start.

I assume that you have basic knowledge of rails and shopify APIs. Also you have a running rails application and have created and setup an embedded app. You can follow thisĀ  awesome tutorial for creating your first pubic shopify app in rails. Do look into the video at the end of the post.

If you have gone through above link and video tutorial in it. I am sure you are now aware of shopify_app gem. So considering you have configured a rails application and have created your first embedded app, lets continue to learn how we can access the asset API on rails.

via GIPHY

To access the Assets of the store, store admin needs to grant your app the permission to read and modify it. These are called scopes.

You can modify the scopes of your application from /config/initializers/shopify_app.rb

You will find the code like below:

Note the line

This is what you need to set to read and modify assets. There are other scopes that you can add. For example: “read_orders, read_products” etc according to your requirement.

So after you set this. You need to fresh install the APP so that the store admin approves the app to access above permissions.Or you can do this installation steps after you come to an end of this post after you wrote the required code to access the API.

Now after the scopes has been configured, let’s see how we access the Asset API. Its really simple as you have already installed the shopify_app gem.

This will access the asset of live theme

That’s it you now have all the liquid files and assets on the @assets instance variable.

You can print it on your view file. with code below:

In above code you just printed out the key value pair. This will print the asset file name and value inside it.

Above line

gets all the theme files. What if you need to access only one particular file. This is easy too.Just do.

you can access its content by doing @theme.value

Now you can sucessfully read the asset file. Let’s extend this one step further and modify the content and save it.

Let’s take above code snippet and continue from there. We have

Voila!! You just modified the liquid file. You can verify the changes from your shopify admin too.

That’s it for this post. Hope it helps.

Cheers!!