You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用JSON payload通过PrestaShop API上传产品遇500错误,求可行方案

PrestaShop API使用JSON创建产品报错,如何用JSON上传产品?

我尝试通过PrestaShop API创建产品,使用JSON格式的payload时收到500错误,系统似乎不支持JSON payload。请问是否有办法使用JSON payload上传产品?

我在Postman中使用的代码结构如下:

url = {base_url} + api/products     
payload = json.dumps({ "product": { "name": "Sample Product", "price": "19.99", "description": "This is a sample product description.", "category": "1" } })  
headers = { 'Content-Type': 'application/json', 'Authorization': 'Basic ' + auth key }     
response = requests.request("POST", url, headers=headers, data=payload)

收到的500错误响应内容:


问题原因

PrestaShop原生Web服务默认仅支持XML格式的请求体,系统会自动尝试将请求内容解析为XML,你的JSON格式内容不符合XML规范,因此触发解析错误,返回500状态码。

解决方案

方案1:改用XML格式Payload(全版本支持)

按照PrestaShop要求构造XML请求体,示例代码:

import requests
import xml.etree.ElementTree as ET

url = "{base_url}/api/products"
auth_key = "你的认证密钥"

# 构建符合PrestaShop要求的XML结构
prestashop_root = ET.Element("prestashop")
product_node = ET.SubElement(prestashop_root, "product")

# 添加产品字段
name = ET.SubElement(product_node, "name")
name.text = "Sample Product"
price = ET.SubElement(product_node, "price")
price.text = "19.99"
description = ET.SubElement(product_node, "description")
description.text = "This is a sample product description."
# 注意:分类字段正确名称是id_category_default
id_category = ET.SubElement(product_node, "id_category_default")
id_category.text = "1"

# 转换为XML字符串
payload = ET.tostring(prestashop_root, encoding='utf8', method='xml')
headers = {
    'Content-Type': 'application/xml',
    'Authorization': 'Basic ' + auth_key
}

response = requests.post(url, headers=headers, data=payload)
print(response.text)

方案2:启用JSON支持(仅PrestaShop 1.7.7+版本可用)

从PrestaShop 1.7.7版本开始,Web服务新增JSON格式支持,需在请求头中添加Output-Format: JSON,同时修正字段名错误,示例代码:

import requests
import json

url = "{base_url}/api/products"
auth_key = "你的认证密钥"

# 修正字段名:category改为id_category_default
payload = {
    "product": {
        "name": "Sample Product",
        "price": "19.99",
        "description": "This is a sample product description.",
        "id_category_default": "1"
    }
}

headers = {
    'Content-Type': 'application/json',
    'Authorization': 'Basic ' + auth_key,
    'Output-Format': 'JSON'  # 启用JSON格式支持
}

# 使用requests的json参数自动处理序列化,无需手动dumps
response = requests.post(url, headers=headers, json=payload)
print(response.json())

注意事项

  • 确保字段名与PrestaShop API要求一致,比如原代码中的category需改为id_category_default,否则即使格式正确也会报错
  • 若你的PrestaShop版本低于1.7.7,只能使用XML方案

内容的提问来源于stack exchange,提问作者Siddharth Srivastava

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 08:52:50