Shopify Python API Bulk Update

128 views Asked by At

I hope you are doing well. I am tring to make a bulk upload using Python Shopify API. But as there is not that much necessary example or I wasn't able to make a sucessful attempt of uploading a bulk update. I have done updating one by one but as our store is a big store sometimes it take about 2, 4 hours to update and working with dropshipping business you always want to remain upto dated as much possible.

import os
import json
import shopify

from dotenv import load_dotenv
load_dotenv()

shop_url = os.getenv("shop_url")
api_version = os.getenv("api_version")
access_token = os.getenv("access_token")     

# Initialize the Shopify session
session = shopify.Session(shop_url, api_version, access_token)
shopify.ShopifyResource.activate_session(session)

mutation = """
mutation ($inventoryItemAdjustments: [InventoryAdjustItemInput!]!, $locationId: ID!) {
  inventoryBulkAdjustQuantityAtLocation(inventoryItemAdjustments: $inventoryItemAdjustments, locationId: $locationId) {
    inventoryLevels {
        id
        available
    }
  }
}

"""

inputs = {
  "inventoryItemAdjustments": [
    {
      "inventoryItemId": "gid://shopify/InventoryItem/42884668031135",
      "availableDelta": 5
    },
    {
      "inventoryItemId": "gid://shopify/InventoryItem/42884724392095",
      "availableDelta": 10
    },
    {
      "inventoryItemId": "gid://shopify/InventoryItem/42884698865823",
      "availableDelta": 5
    }
  ],
  "locationId": "gid://shopify/Location/41639051323"
}

try:
    # Execute the GraphQL mutation and parse the response
    result = json.loads(shopify.GraphQL().execute(
        query=mutation,
        variables=inputs,
    ))

    # Check if the mutation was successful
    if isinstance(result, dict) and 'data' in result and 'inventoryBulkAdjustQuantityAtLocation' in result['data']:
        updated_inventory = result['data']['inventoryBulkAdjustQuantityAtLocation']['inventoryLevels']
        if updated_inventory:
            print(f'Successfully updated variants.')
            for item in updated_inventory:
                print(f'Inventory ID: {item["id"]}, New Quantity: {item["available"]}')
        else:
            print(f'Failed to update variants. No data available in the response.')
    else:
        print(f'Failed to update variants. Unexpected response format.')
        if isinstance(result, dict) and 'errors' in result:
            for error in result['errors']:
                print(f'Error Message: {error["message"]}')
except Exception as e:
    print(f'An error occurred: {str(e)}')


# Deactivate the Shopify session
shopify.ShopifyResource.clear_session()
`

Above is the piece of code I have tried. I want to have a csv file from where i will be reading data making a GraphQL command and make a bulk update. Main issue I am having in creating this GraphQL and then making a sucessful request. 

Any help regarding this would be appreciated. 
Thanks


`import os
import json
import shopify

from dotenv import load_dotenv
load_dotenv()

shop_url = os.getenv("shop_url")
api_version = os.getenv("api_version")
access_token = os.getenv("access_token")     

# Initialize the Shopify session
session = shopify.Session(shop_url, api_version, access_token)
shopify.ShopifyResource.activate_session(session)

mutation = """
mutation ($inventoryItemAdjustments: [InventoryAdjustItemInput!]!, $locationId: ID!) {
  inventoryBulkAdjustQuantityAtLocation(inventoryItemAdjustments: $inventoryItemAdjustments, locationId: $locationId) {
    inventoryLevels {
        id
        available
    }
  }
}

"""

inputs = {
  "inventoryItemAdjustments": [
    {
      "inventoryItemId": "gid://shopify/InventoryItem/42884668031135",
      "availableDelta": 5
    },
    {
      "inventoryItemId": "gid://shopify/InventoryItem/42884724392095",
      "availableDelta": 10
    },
    {
      "inventoryItemId": "gid://shopify/InventoryItem/42884698865823",
      "availableDelta": 5
    }
  ],
  "locationId": "gid://shopify/Location/41639051323"
}

try:
    # Execute the GraphQL mutation and parse the response
    result = json.loads(shopify.GraphQL().execute(
        query=mutation,
        variables=inputs,
    ))

    # Check if the mutation was successful
    if isinstance(result, dict) and 'data' in result and 'inventoryBulkAdjustQuantityAtLocation' in result['data']:
        updated_inventory = result['data']['inventoryBulkAdjustQuantityAtLocation']['inventoryLevels']
        if updated_inventory:
            print(f'Successfully updated variants.')
            for item in updated_inventory:
                print(f'Inventory ID: {item["id"]}, New Quantity: {item["available"]}')
        else:
            print(f'Failed to update variants. No data available in the response.')
    else:
        print(f'Failed to update variants. Unexpected response format.')
        if isinstance(result, dict) and 'errors' in result:
            for error in result['errors']:
                print(f'Error Message: {error["message"]}')
except Exception as e:
    print(f'An error occurred: {str(e)}')


# Deactivate the Shopify session
shopify.ShopifyResource.clear_session()

Want this to work, above peice of code didn't work for me.

0

There are 0 answers