'How to show product variant inventory quantity per location on Shopify product Page using Admin API?

I would like to show the product variant quantity on the product page like this:

Location 1: 5 in stock
Location 2: 2 in stock
Location 3: 63 in stock
Location 4: 5 in stock
and so on...

Is it possible to do this using the admin API from Shopify?

Thanks in advance.



Solution 1:[1]

It is not recommended to use the Shopify admin API directly in the store front as you could be exposing the API username and keys in your JS code.

You should use a backend service or something similar where your frontend will send a request to the backend. The backend will then fetch the records using the Shopify rest admin APIs and return the data back.

If you prefer to go the custom code route below are a few things for you to keep in mind

  1. Shopify has API rate limits. You most likely will be hitting these if you fetch every time a product page is loaded. Limits mentioned here
  2. As an option for the rate limits, you could query the backend every x mins, save them in the database and serve the inventory levels from the DB. Or you could try to cache your request for a certain time limit instead of saving in the DB.

If you just want to how much is available across all inventory locations, you can use the below liquid/JS code.

<script>
  var variantStock = {};

  {% for variant in product.variants %}
    variantStock[{{- variant.id -}}] = {{ variant.inventory_quantity }};
  {% endfor %}
  console.log(variantStock);
</script>

In the above code, you will have the available inventory quantity for each variant in the variantStock object. You can then write some extra code to display the stock levels when the user changes variants accordingly.

Check the liquid object document for variants here

Having said the above, another option is to use an app that will do the above for you. There are many apps in the Shopify app store that does exactly what you want.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ela Buwa