使用Python Requests调用Shopify API PUT更新图片遇400错误求助
解决Shopify API更新图片Alt文本的400错误
问题描述
执行以下代码尝试更新Shopify产品图片的Alt文本时,始终收到400错误:
import requests import json import re # Define your Shopify store's API key and password API_KEY = 'xxxxxxxxxxxxxxxxxx' PASSWORD = 'xxxxxxxxxxxxxx' API_TOKEN = 'xxxx_xxxxxxxxxcd7' SHOPIFY_DOMAIN = 'https://www.xxxx.xxx/' headers = { 'X-Shopify-Access-Token': API_TOKEN, 'Content-Type': 'application/json', } # Define the endpoint URL endpoint = 'https://www.xxxxx/admin/api/2024-04/products/9190309691717/images/53245809295685.json' # Define the new alt text new_alt_text = "#title-#seren.earth-#variantSKU" # Prepare the request body body = { 'image': { "product_id": 9190309691717, "id": 53245809295685, # Include the image ID, "alt": 'variantSKU', } } # Send the PUT request response = requests.put(endpoint, headers=headers, json=body) print(response.status_code) print(response.content) # Check the response status if response.status_code == 200: print(f"Alt text updated successfully for image 9190309691717") else: print(f"Failed to update alt text for image 9190309691717. Response: {response.text}")
错误返回内容:
400 b'{"errors":{"image":"Required parameter missing or invalid"}}' Failed to update alt text for image 9190309691717. Response: {"errors":{"image":"Required parameter missing or invalid"}}
错误原因及修正方案
核心问题
Shopify的**更新图片API(PUT请求)**不需要在请求体中传递product_id和id——这两个参数已经通过URL路径/products/{product_id}/images/{image_id}.json明确指定,额外传递会导致API判定参数无效。同时代码中定义了new_alt_text但未实际使用,属于逻辑冗余。
修正后的代码
import requests # 配置Shopify信息 API_TOKEN = 'xxxx_xxxxxxxxxcd7' # 替换为店铺实际域名 endpoint = 'https://www.xxxx.xxx/admin/api/2024-04/products/9190309691717/images/53245809295685.json' headers = { 'X-Shopify-Access-Token': API_TOKEN, 'Content-Type': 'application/json', } # 定义新的Alt文本 new_alt_text = "#title-#seren.earth-#variantSKU" # 精简请求体,仅传递需要更新的alt字段 body = { 'image': { "alt": new_alt_text } } # 发送请求 response = requests.put(endpoint, headers=headers, json=body) print(response.status_code) print(response.content) # 检查结果 if response.status_code == 200: print(f"图片9190309691717的Alt文本更新成功") else: print(f"图片9190309691717的Alt文本更新失败。响应内容: {response.text}")
额外注意事项
- 确保
endpoint中的域名是店铺的实际域名(如your-store.myshopify.com或自定义域名),路径中的API版本(2024-04)需要与店铺支持的版本匹配。 - 确认
X-Shopify-Access-Token拥有write_products权限,否则会返回权限错误。
内容的提问来源于stack exchange,提问作者RamAlx
相关产品推荐
相关产品推荐

