简体   繁体   中英

Converting from curl to python request.post

I wish to convert my current curl command to python code to request for access token for an api.

curl -X POST -H "Content-Type:application/json" -d '{"grantType":"client_credentials"}' [Access Token URL] 

my attempt:

import requests

api_url_base = "https://api.example.com/api/"
headers ={'Content_Type':'application/json',
        'grandType': 'client_credentials'
        }

response = requests.post(headers=headers, "https://api.example.com/accesstokens")
if response.status_code == 200:
    print(json.loads(response.content.decode('utf-8')))
else:
    print(response.status_code)

Expected output: Should be in python.

You're mismatching posting headers and body data there, not to mention there's a typo with grandType .

Either way, posting JSON and parsing JSON responses is super easy with Requests:

response = requests.post(
    "https://api.example.com/accesstokens",
    json={"grantType": "client_credentials"},
)
response.raise_for_status()  # raise an exception for error statuses
data = response.json()
print(data)

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