pythonpython-requestspostmanput

PUT request via Postman works, but via Python requests not


When I send PUT request via Postman everything is ok, but when I copy code from Postman to Python I get this:

{"code": 50035, "errors": {"_errors": [{"code": "CONTENT_TYPE_INVALID", "message": "Expected "Content-Type" header to be one of {'application/json'}."}]}, "message": "Invalid Form Body"}

The code:

url = "https://discord.com/api/v9/guilds/860859559908474900/premium/subscriptions"

payload={'user_premium_guild_subscription_slot_ids': '853228009795223572'}
files=[

]
headers = {
  'authorization': 'here token',
  'Cookie': '__dcfduid=c5cbabf10a8344558c8c4b90a6e306e2'
}

response = requests.request("PUT", url, headers=headers, data=payload, files=files)

print(response.text)

if I add 'content-type' : 'application/json' to headers, I get this:

{"message": "400: Bad Request", "code": 0}


Solution

  • Either use json= instead of data= or add the Content-Type header with value application/json as the server tells you.

    Also check the Authorization header, mostly there's a prefix which mentions what auth to use e.g.:

    Authorization: Basic base64-encoded(user:pass)
    Authorization: Bearer token
    Authorization: Token token
    

    and make sure the files parameter is actually allowed to be empty by the API and if not, try removing it.

    Then there's __dcfduid cookie you provide. Some cookies tend to be dynamic as in the value changes between requests. Try then establishing the session and do the login part within it:

    import requests as r
    ses = r.Session()
    resp = ses.post(<login to the API>)
    print(resp.text)
    ses.put(
        url="https://discord.com/api/v9/guilds/860859559908474900/premium/subscriptions",
        headers={
            'Authorization': 'here token',
            # cookies are in the ses object
        },
        json={
            'user_premium_guild_subscription_slot_ids': '853228009795223572'
        },
        # if required
        files=[...]
    )