我正在尝试创建一个简单的 Python 脚本来通过新的 FedEx REST API 上传 PDF 文档。
下面是我的最小代码示例,可用于通过在脚本旁边放置文件
file.pdf
并更新为您自己的 FedEx REST API 生产凭据来复制问题。
在运行代码时,我收到以下错误消息。任何意见表示赞赏:
{
"customerTransactionId": "ETD-Pre-Shipment-Upload_test1",
"errors": {
"code": "1001",
"message": "Invalid request: invalid input : Incoming Request"
}
}
我的代码如下:
# minimal class for upload docs test
class FedexLabelHelper:
def __init__(self, fedex_cred):
self.fedex_cred = fedex_cred
self.access_token = ""
return
# function for retrieving access_token
def get_access_token(self):
import json, requests
url = self.fedex_cred["url_prefix"] + "/oauth/token"
payload = {
"grant_type": "client_credentials",
"client_id": self.fedex_cred["key"],
"client_secret": self.fedex_cred["password"],
}
headers = {"Content-Type": "application/x-www-form-urlencoded"}
response = requests.request("POST", url, data=payload, headers=headers)
access_token = json.loads(response.text)["access_token"]
self.access_token = access_token
# function for uploading PDF document
def upload_pdf_document_fedex_script(self):
import requests, binascii
fileName = "file.pdf"
file_content = open(fileName, "rb").read()
file_content_b64 = binascii.b2a_base64(file_content)
file_content_b64.decode("cp1250")
url = self.fedex_cred["doc_url_prefix"] + "/documents/v1/etds/upload"
payload = {
"document": {
"workflowName": "ETDPreshipment",
"carrierCode": "FDXE",
"name": fileName,
"contentType": "application/pdf",
},
"meta": {
"shipDocumentType": "COMMERCIAL_INVOICE",
"originCountryCode": "DK",
"destinationCountryCode": "BE",
},
}
files = [
(
"attachment",
(fileName, "file_content_b64", "application/pdf"),
)
]
headers = {
"Authorization": f"Bearer {self.access_token}",
"x-customer-transaction-id": "ETD-Pre-Shipment-Upload_test1",
"Cookie": "XYZ",
}
response = requests.post(url, headers=headers, data=payload, files=files)
print(response.text)
# -----------------------
# setup minimal test of the FedEx Upload Documents REST API
fedex_cred = {
"production": {
"url_prefix": "https://apis.fedex.com",
"doc_url_prefix": "https://documentapi.prod.fedex.com",
"key": "XYZ",
"password": "XYZ",
"freight_account_number": "XYZ",
},
}
flh = FedexLabelHelper(fedex_cred["production"])
flh.get_access_token()
flh.upload_pdf_document_fedex_script()