1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] Understanding the difference between these two python requests POST calls (data vs....

Discussão em 'Python' iniciado por Stack, Outubro 8, 2024.

  1. Stack

    Stack Membro Participativo

    This is a toy, non-reproducible example as I can't share the original. I think it's answerable, and might help others. From other SO posts like this and this, my understanding is that given some dictionary d of params, these are equivalent:

    requests.post(url, data=json.dumps(d))
    requests.post(url, json=d)


    The parameters for a token endpoint were defined in documentation like so:

    • url: {{base_url}}/token
    • parameters
      • grant_type={{password}}
      • username={{username}}
      • password={{password}}
      • scope={"account":"{{account}}", "tenant":"{{tenant}}"}

    I started with this, with variables loaded from a .env file:

    resp = requests.post(f'{base_url}/token',
    json={'grant_type': 'password', 'username': uname, 'password': pwd,
    'scope': {'account': account, 'tenant': tenant}})
    resp.text
    # '{"error":"unsupported_grant_type"}'


    I tried changing to the data argument, and got a more sane error:

    resp = requests.post(f'{base_url}/token',
    data={'grant_type': 'password', 'username': uname, 'password': pwd,
    'scope': {'account': account, 'tenant': tenant}})
    resp.text
    # '{"error":"invalid_grant","error_description":"{\\"ErrorMessage\\":\\"Error trying to Login - User [username] Account [] Unexpected character encountered while parsing value: a.


    I tried a few other things like forcing quotes around args (e.g. {'account': f"{account}"}) without success, and ultimately succeeded with this "hybrid" method:

    resp = requests.post(f'{base_url}/token',
    data={'grant_type': 'password', 'username': uname, 'password': pwd,
    'scope': json.dumps({'account': account, 'tenant': tenant})})


    My questions:

    • is this nuance "real" vs. the straightforward reading of the linked questions? Namely, it seemed like one either uses data=json.dumps(d) or json=d, but I have not found an answer mixing the two (and wrapping the entire data arg in json.dumps() breaks my working final version)
    • as a relative noob in APIs/network things, would this be discernible to me from the documentation arguments listed above, or was trial and error the only way to discover this?
    • given my final solution was there a better/more correct way to pass these params?

    Continue reading...

Compartilhe esta Página