简体   繁体   中英

Translating curl to Python requests (post)

I have a curl request in the following format

body=$(cat << EOF
{
  "order": {
    "units": "100",
    "instrument": "EUR_USD",
    "timeInForce": "FOK",
    "type": "MARKET",
    "positionFill": "DEFAULT"
  }
}
EOF
)

curl \
  -X POST \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer <AUTHENTICATION TOKEN>" \
  -d "$body" \
  "https://api-fxtrade.oanda.com/v3/accounts/<ACCOUNT>/orders"

I hope to have your help translating this into requests.post format.

This is what I have currently, and it doesnt seem to work:

order_data = {
"order": {
"units": "100",
"instrument": "EUR_USD",
"timeInForce": "FOK",
"type": "MARKET",
"positionFill": "DEFAULT"
},
'Authorization': 'Bearer '+<AUTHENTICATION TOKEN>
}

requests.post('https://api-fxpractice.oanda.com/v3/accounts/<ACCOUNT>/orders', data = order_data)

I have replaced ACCOUNT and AUTHENTICATION TOKEN with actual strings.

The part I am confused with is the body=$() line. Not too sure how to fit that into the requests format.

Hope to have your help. Thank you.

Authorization should be passed as header, Content-Type must be 'application/json' and payload must be json encoded.

As of Requests version 2.4.2 and onwards, you can alternatively use 'json' parameter in the call which makes it simpler.

The final payload should be as follows:

order_data = {
"order": {
"units": "100",
"instrument": "EUR_USD",
"timeInForce": "FOK",
"type": "MARKET",
"positionFill": "DEFAULT"
}
}
headers = 'Authorization': 'Bearer <AUTHENTICATION TOKEN>'

requests.post('https://api-fxpractice.oanda.com/v3/accounts/<ACCOUNT>/orders', headers=headers, json=order_data)

Using the json parameter in the request will change the Content-Type in the header to application/json .

Docs here: http://docs.python-requests.org/en/master/user/quickstart/#more-complicated-post-requests

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM