Vishal Addnectar
Vishal Addnectar

Reputation: 1

USPS Shipping Options API v3 - "The request body is invalid or malformed" Error (400)

I'm trying to use the USPS Shipping Options API v3 with Python's requests library to retrieve shipping rates. I successfully obtain an OAuth token, but when I call get_usps_rate to get quotes, I receive a 400 error with the message:

"The request body is invalid or malformed."

def get_usps_rate(access_token, origin_zip, destination_zip, weight, length, height, width, mail_class):
url = f"{BASE_URL}/shipments/v3/options/search"
headers = {
    "Authorization": f"Bearer {access_token}",
    "Content-Type": "application/json"
}

payload = {
    "pricingOptions": [
        {
            "priceType": "RETAIL"
        }
    ],
    "originZIPCode": origin_zip,
    "destinationZIPCode": destination_zip,
    "packageDescription": {
        "weight": weight,
        "length": length,
        "height": height,
        "width": width,
        "mailClass": mail_class
    }
}

response = requests.post(url, headers=headers, json=payload)
if response.status_code == 200:
    return response.json()
else:
    print(f"Request payload: {payload}")
    print(response.status_code)
    print(response.text)
    raise Exception(f"Error fetching USPS rate: {response.json()}")

I have reviewed the USPS Shipping Options API documentation for common errors and data format requirements.(https://developer.usps.com/shippingoptionsv3)

I've tried simplifying the request by removing optional fields, but still receive the same error.

Upvotes: 0

Views: 112

Answers (0)

Related Questions