使用Python调用Fetchapp API创建产品时POST请求返回404的原因
Let's break down the issues in your code and fix them one by one:
1. Incorrect API Domain & Protocol
First, the API documentation specifies the host as app.fetchapp.com, not www.fetchapp.com. Additionally, you should use HTTPS instead of HTTP—most modern APIs require secure connections, and using HTTP might lead to redirects or unexpected 404 errors.
2. Missing Required Content-Type Header
The API explicitly requires setting Content-Type: application/xml in your request headers. Your current code only sets Accept: application/xml, which tells the server you accept XML responses, but doesn't specify that you're sending XML data (the server needs this to parse your payload correctly).
3. Wrong Request Data Format
You're sending form-encoded data via a Python dictionary, but the API expects an XML payload matching the structure shown in the docs. The way you tried to specify the price attribute ('price type="float"') won't work with form data—this attribute needs to be part of the XML element structure, not a dictionary key.
Fixed Code Example
Here's the corrected implementation that addresses all these issues:
import requests from requests.auth import HTTPBasicAuth import xml.etree.ElementTree as ET # Build the XML payload matching the API's required structure root = ET.Element("product") sku = ET.SubElement(root, "sku") sku.text = "CJ0001" name = ET.SubElement(root, "name") name.text = "Carrot Juice" price = ET.SubElement(root, "price", type="float") price.text = "1.00" # Add file IDs if you have them (omit this section if not needed) files = ET.SubElement(root, "files", type="array") file_id1 = ET.SubElement(files, "id") file_id1.text = "4443443" file_id2 = ET.SubElement(files, "id") file_id2.text = "4443444" # Convert the XML element to a properly formatted string xml_payload = ET.tostring(root, encoding="UTF-8", xml_declaration=True) # Correct API URL (HTTPS + proper domain) url = 'https://app.fetchapp.com/api/v2/products/create.xml' # Headers with required Content-Type headers = { "Accept": "application/xml", "Content-Type": "application/xml" } # Basic auth as specified in the docs auth = HTTPBasicAuth('demokey', 'demotoken') # Send POST request with XML payload r = requests.post(url, auth=auth, headers=headers, data=xml_payload, verify=True) print(r.status_code) print(r.text)
Additional Notes
- Replace
demokeyanddemotokenwith your actual Fetchapp API credentials. - If you don't have file IDs to associate with the product, you can remove the entire
<files>section from the XML payload. - If you still encounter issues, try testing alternative endpoints listed in the docs (like
/api/v2/productsor/api/v2/products/create) with the same XML payload—sometimes APIs have multiple valid paths for the same action.
内容的提问来源于stack exchange,提问作者ben olsen

