简体   繁体   中英

Get Specific Data form request.post response in Python

I am using sendgrid api to send email to users and then check the status,

res = requests.post(url)
print type(res)

and it prints type as <class 'requests.models.Response'>

on the Postman API client I am getting this:

{
"message": "error",
"errors": [
"JSON in x-smtpapi could not be parsed"
]
}

I want to fetch only the message value from response. I have written the following piece of code but doesn't work:

for keys in res.json():
    print str(res[keys]['message'])

You don't need to loop; just access the 'message' key on the dictionary returned by the response.json() method:

print res.json()['message']

It may be easier to follow what is going on by storing the result of the response.json() call in a separate variable:

json_result = res.json()
print json_result['message']

The reason Postman API returns an error message is because your POST didn't actually contain any data; you probably want to send some JSON to the API:

data = some_python_structure
res = requests.post(url, json=data)

When you use the json argument, the requests library will encode it to JSON for you, and set the correct content type header.

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