简体   繁体   中英

Can you get a more comprehensive http response using python requests?

I tried calling an API using both python and nodejs but the format in which the response is in is quite different.

For nodejs, it returns the statuscode, headers, body, request etc. Eg (Only an example, not the actual response so you can ignore any syntax errors)

{
    "statusCode" : 200,
    "headers" : {
                    'xxxx' : 'xxxx"
                },
    "body" : {
                 "name" : "james",
                 "age" : 35
             },
    "request" {
                  "method" : "POST"
              }
}

For python, it only returns the response body. Eg (Only an example, not the actual response so you can ignore any syntax errors)

{
    'name' : james,
    'age' : 35
}

I am aware that i am able to get the headers etc using python request response object such as response.headers etc but is there a way that allows me to a similar response like nodejs. I know about response. dir but i need to forward this response so the format of response. dir is not accepted.

Thanks all!

You can compile your own response, similar to what you get from nodejs, something like

import json
import requests

url = 'http://date.jsontest.com/'

r = requests.get(url)

j = {
    "statusCode": r.status_code,
    "headers": dict(r.headers),
    "body": r.json(),
    "request": {
        "method": r.request.method
    }
}

print(json.dumps(j, indent=4))

Will produce:

{
    "statusCode": 200,
    "headers": {
        "Access-Control-Allow-Origin": "*",
        "Content-Type": "application/json",
        "X-Cloud-Trace-Context": "9b4e313aa5e6373ddc997dc963ee8f1b",
        "Date": "Thu, 23 Jun 2022 03:11:27 GMT",
        "Server": "Google Frontend",
        "Content-Length": "100"
    },
    "body": {
        "date": "06-23-2022",
        "milliseconds_since_epoch": 1655953887719,
        "time": "03:11:27 AM"
    },
    "request": {
        "method": "GET"
    }
}

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