如何将含嵌套XML的Curl请求转为Python Requests POST请求?
Got it, let's walk through converting that curl command into a working Python Requests POST request. The tricky parts here are the nested XML request body and the Basic Auth header, but we'll break it down so it's straightforward.
Step 1: Prep the Basics
First, make sure you've got the requests library installed (run pip install requests if you haven't already). Then we'll define the core components: the API URL, authentication details, headers, and the XML payload.
Step 2: Handle Authentication
The curl command uses Basic Auth, which Requests simplifies a lot. Instead of manually encoding your username and password into a Base64 string, you can just pass a tuple of (username, password) to the auth parameter—Requests handles the encoding automatically. If you prefer to use the pre-encoded header from the curl command, you can add it directly to the headers dict, but using the auth parameter is cleaner and less error-prone.
Step 3: Craft the XML Request Body
Since the request body is XML (not JSON), we'll pass the raw XML string directly to the data parameter (not json!). Using triple quotes (''') lets us preserve the XML structure exactly as it appears in the curl command, which helps avoid formatting issues the API might reject.
Full Working Code
import requests # Target Bluesnap sandbox endpoint url = "https://sandbox.bluesnap.com/services/2/tools/param-encryption" # Replace with your actual Bluesnap username and password auth_credentials = ("your_username", "your_password") # Nested XML payload - keep the structure and xmlns attribute intact xml_payload = '''<param-encryption xmlns="http://ws.plimus.com"> <parameters> <parameter> <param-key>amount</param-key> <param-value>125.00</param-value> </parameter> </parameters> </param-encryption>''' # Required request headers request_headers = { "Content-Type": "application/xml" } # Send the POST request response = requests.post( url=url, auth=auth_credentials, headers=request_headers, data=xml_payload ) # Optional: Check response to debug or confirm success print("Response Status Code:", response.status_code) print("Response Content:", response.text)
Alternative: Manual Authorization Header
If you want to use the exact Base64 string from the curl command instead of the auth parameter, modify the headers like this and omit the auth argument in the post call:
request_headers = { "Content-Type": "application/xml", "Authorization": "Basic dXNlcm5hbWU6cGFzc3dvcmQ=" # Your pre-encoded credentials }
Key Notes
- Use
datainstead ofjsonfor XML payloads—Requests will send the raw text as-is with the correctContent-Typeheader. - Don't remove the
xmlnsattribute in the XML root element; the API relies on it to parse the request correctly. - Always check the response status code (e.g., 200 = success, 401 = auth failure, 400 = malformed request) to debug issues quickly.
内容的提问来源于stack exchange,提问作者Alec Davies

