How to bulk update Stock & Price of Shopify items via API

How to bulk update Stock & Price of Shopify items via API

Introduction to Shopify

Shopify is one of the leading e-commerce platforms that allows businesses to set up, operate, and manage their online stores. With its user-friendly interface, customizable themes, and wide range of integrations, Shopify makes it easy for entrepreneurs and businesses to create a professional online store with minimal technical expertise. It offers powerful tools for product management, order processing, marketing, and analytics, helping businesses scale efficiently. Whether you’re selling a few items or running a large-scale enterprise, Shopify is a robust solution for e-commerce.

Importance of Bulk Updating Stock & Price via API

In the fast-paced world of e-commerce, managing inventory and product pricing efficiently is crucial for staying competitive. For businesses that are integrating Shopify with an Enterprise Resource Planning (ERP) system, bulk updates become even more essential. An ERP typically handles a large volume of data, including stock levels and pricing, across multiple channels. Without bulk updating capabilities, manually syncing stock and price changes between an ERP and Shopify can be time-consuming, prone to errors, and lead to delays in reflecting real-time data on the storefront.

By using Shopify’s API to perform bulk updates, businesses can automate and streamline the process of syncing product stock and prices between their ERP system and their Shopify store. This ensures that product data remains consistent, accurate, and up-to-date across all platforms, reducing the risk of overselling, stockouts, or pricing discrepancies. Bulk updates not only save time but also improve operational efficiency, making it easier for businesses to manage their products at scale, especially as inventory grows.

So let’s see how we can execute a bulk update.

Let’s breakdown to simpler steps for easy understanding

  1. Get API Keys

    Obtain your Shopify API credentials (API key and access token) by creating a private app in the Shopify Admin panel.

  2. Fetch All Products with Pagination

Use the Shopify GET /admin/api/2023-04/products.json API to fetch all product data, implementing pagination to handle large datasets.

Sample curl

 curl --location 'https://yourdomain.myshopify.com/admin/api/2023-04/products/9637789827376.json' \
--header 'X-Shopify-Access-Token: key' \
--header 'Content-Type: application/json'

and the response will be

 {
    "product": {
        "id": 9637789222222222227376,
        "title": "2 pin power cable",
        "body_html": "hello there ",
        "vendor": "abc qatar",
        "product_type": "",
        "created_at": "2024-10-28T03:29:31-04:00",
        "handle": "2-pin-power-cable",
        "updated_at": "2024-11-12T15:29:56-05:00",
        "published_at": "2024-11-12T02:48:30-05:00",
        "template_suffix": null,
        "published_scope": "global",
        "tags": "",
        "status": "active",
        "admin_graphql_api_id": "gid://shopify/Product/454545",
        "variants": [
            {
                "id": 45656456456456,
                "product_id": 45645645645645645,
                "title": "Default Title",
                "price": "20.00",
                "position": 1,
                "inventory_policy": "deny",
                "compare_at_price": null,
                "option1": "Default Title",
                "option2": null,
                "option3": null,
                "created_at": "2024-10-28T03:29:31-04:00",
                "updated_at": "2024-10-29T01:31:21-04:00",
                "taxable": true,
                "barcode": null,
                "fulfillment_service": "manual",
                "grams": 0,
                "inventory_management": null,
                "requires_shipping": true,
                "sku": "1001",
                "weight": 0.0,
                "weight_unit": "kg",
                "inventory_item_id": 456456456456,
                "inventory_quantity": 0,
                "old_inventory_quantity": 0,
                "admin_graphql_api_id": "gid://shopify/ProductVariant/4564564564565",
                "image_id": null
            }
        ],
        "options": [
            {
                "id": 45654645,
                "product_id": 5645645645645645,
                "name": "Title",
                "position": 1,
                "values": [
                    "Default Title"
                ]
            }
        ],
        "images": [
            {
                "id": 45645654564564,
                "alt": null,
                "position": 1,
                "product_id": 4565654645645645,
                "created_at": "2024-10-28T03:29:31-04:00",
                "updated_at": "2024-10-28T03:29:31-04:00",
                "admin_graphql_api_id": "gid://shopify/ProductImage/45645645645645",
                "width": 600,
                "height": 600,
                "src": "https://cdn.shopify.com/s/files/1/54645654/8496/7728/files/2pinpowerc4564564645645.jpg?v=456456546",
                "variant_ids": []
            }
        ],
        "image": {
            "id": 4697544723354645626256,
            "alt": null,
            "position": 1,
            "product_id": 963778546569827376,
            "created_at": "2024-10-28T03:29:31-04:00",
            "updated_at": "2024-10-28T03:29:31-04:00",
            "admin_graphql_api_id": "gid://shopify/ProductImage/5464564564",
            "width": 600,
            "height": 600,
            "src": "https://cdn.shopify.com/s/files/1/5645645/8496/7728/files/554645645-1.jpg?v=1730100571",
            "variant_ids": []
        }
    }
} 

1.Create a Data Table

Construct a table to store SKUproduct_id, and inventory_item_id for each product to help with stock and price updates.

2.Fetch Inventory Item ID

Use the GET /admin/api/2023-04/products/{product_id}.json API to retrieve the inventory_item_id for each product variant.

3.Enable Inventory Tracking (if needed)

Ensure that inventory tracking is enabled using the PUT /admin/api/2023-04/inventory_items/{inventory_item_id}.json API, setting inventory_management to “shopify”.

alternatively you can use admin panel bulk update feature to set inventory tracking on.

6. Update Stock & Price

Use the PUT /admin/api/2023-04/variants/{variant_id}.json API to update the inventory_quantity and price for each product variant.

7. Handle API Limits and Delays

Implement API rate-limiting and delay logic (e.g., 1 call per second) to avoid timeouts and ensure smooth updates.

Problem

Shopify doesn’t have any API to update stock and price of product together.

Solution

So what I did is to create an API and from inside that i called both stock update and price update Shopify APIs

 [Route("api/v2/ERP/ShopifyStockPriceUpdate")]
        [HttpPost]
        public async Task ShopifyStockPriceUpdate([FromBody] List sp)
        {
            HttpResponseMessage response = new HttpResponseMessage();
            ResponseModel ResModel = new ResponseModel();
            try
            {
                string baseUrl = Common.ShopifyERPUrl;
                string accessToken = Common.shopifyKey;
                string locationId = Common.shopifyLocationId;

                object JsonData = Newtonsoft.Json.JsonConvert.SerializeObject(sp);
                var dateOfPOST = Common.GetCurrentDateTime();

                //loop items and call shopify api
                using (HttpClient httpClient = new HttpClient())
                {
                    httpClient.DefaultRequestHeaders.Add("X-Shopify-Access-Token", accessToken);

                    foreach (var item in sp)
                    {
                      
                        if (!item.ProductId.HasValue || item.ProductId.Value <= 0) { throw new Exception($"Invalid productId for ERPRefNo: {item.ERPRefNo}"); } //price if (item.UnitPrice >=0)
                        {
                            var priceUpdatePayload = new
                            {
                                product = new
                                {
                                    id = (long)item.ProductId,
                                    variants = new[]
                                    {
                                new
                                {
                                    product_id = (long)item.ProductId, 
                                    price =item.UnitPrice.ToString("F2")
                                }
                            }
                                }
                            };

                            var priceUpdateResponse = await httpClient.PutAsync(
                                $"{baseUrl}/2023-04/products/{item.ProductId.Value}.json",
                                new StringContent(JsonConvert.SerializeObject(priceUpdatePayload), Encoding.UTF8, "application/json")
                            );

                            if (!priceUpdateResponse.IsSuccessStatusCode)
                            {
                                throw new Exception($"Failed to update price for ERPRefNo: {item.ERPRefNo}. API Response: {await priceUpdateResponse.Content.ReadAsStringAsync()}");
                            }
                        }

                      //Update Stock
                        if (item.Stock.HasValue)
                        {
                            var stockUpdatePayload = new
                            {
                                location_id =locationId, 
                                inventory_item_id = (long)item.InventoryProductId, 
                                available = (int)item.Stock.Value
                            };

                            var stockUpdateResponse = await httpClient.PostAsync(
                                $"{baseUrl}/2023-04/inventory_levels/set.json",
                                new StringContent(JsonConvert.SerializeObject(stockUpdatePayload), Encoding.UTF8, "application/json")
                            );

                            if (!stockUpdateResponse.IsSuccessStatusCode)
                            {
                                throw new Exception($"Failed to update stock for ERPRefNo: {item.ERPRefNo}. API Response: {await stockUpdateResponse.Content.ReadAsStringAsync()}");
                            }
                        }
                    }
                }

                // Success response
                ResModel.Message = "Price and Stock updated successfully for all items.";
                ResModel.Data = "";
                response = Request.CreateResponse(HttpStatusCode.OK, ResModel);
                 
            }
            catch (Exception e)
            {
                string message = string.Format(e.Message.ToString());
                ResModel.Message = message;
                ResModel.Data = "";
                response = Request.CreateResponse(HttpStatusCode.BadRequest, ResModel);

            }
            return response;
        } 

This api can be called from postman for testing. For example

 curl --location 'http://yourdomain/api/v2/ERP/Shp_StockPriceUpdate' \
--header 'Content-Type: application/json' \
--data '[
{
"ERPRefNo": "4549292138337", //this is the sku
"UnitPrice": 349.00,
"SpecialPrice": 0.00,
"Stock": 2,
"productId":"9637974835504",
"InventoryProductId":"51257747702064"
}
]' 

Conclusion

In conclusion, bulk updating stock and prices in Shopify via API is an essential task for businesses that need to sync their inventory and pricing with an external system, like an ERP. By following the steps outlined above, merchants can automate the process of fetching product data, enabling inventory tracking, and updating quantities and prices, all while maintaining data accuracy and efficiency. This streamlined approach not only saves time but also ensures that inventory levels and pricing are always up-to-date across all sales channels, helping businesses manage their operations more effectively.


Interoons aim at providing electronically intelligent and comprehensive range of digital marketing solutions that exceed customer expectations. We implement revolutionary digital marketing ideas to achieve a common as well as the aggregate growth of the organization. Long-term customer relations and extended support are maintained.

Leave a Reply

Your email address will not be published. Required fields are marked *