Home > Software engineering >  Python urllib3 doesn't seem to be sending fields data
Python urllib3 doesn't seem to be sending fields data

Time:04-08

I am trying to utilise the authentication here: https://api.graphnethealth.com/system-auth using Python urllib3 and have the following

import urllib3
http = urllib3.PoolManager()
resp = http.request(
        "POST",
        "https://core.syhapp.com/hpca/oauth/token",
        headers={
            "Content-Type": "application/x-www-form-urlencoded"
        },
        fields={
            "grant_type": "client_credentials",
            "client_id": "YYYYYYYYY",
            "client_secret": "XXXXXXXXX"
        }
    )
print(resp.data)

I get an error saying that grant_type has not been sent.

b'{\r\n  "error": {\r\n    "code": "400",\r\n    "message": "Validation Errors",\r\n    "target": "/oauth/token",\r\n    "details": [\r\n      {\r\n        "message": "grant_type is required",\r\n        "target": "GrantType"\r\n      },\r\n      {\r\n        "message": "Value should be one of the following password,refresh_token,trusted_token,handover_token,client_credentials,pin",\r\n        "target": "GrantType"\r\n      }\r\n    ]\r\n  }\r\n}'

Any suggestions?

CodePudding user response:

You're telling it the data will be form-urlencoded, but that's not what request does by default. I believe you need:

resp = http.request(
        "POST",
        "https://core.syhapp.com/hpca/oauth/token",
        fields={
            "grant_type": "client_credentials",
            "client_id": "YYYYYYYYY",
            "client_secret": "XXXXXXXXX"
        },
        encode_multipart = False
    )

request replaces the Content-Type header, so there's no point in specifying it at all.

CodePudding user response:

This is because you have specified wrong Content-Type header value. The request body is a JSON, so try with Content-Type: application/json.

  • Related