Search code examples
pythonapirequestrestful-authentication

Python Request Token from REST API


Im struggling with this Dokumentation here:

  • Send your credential base64 encoded to the authentication server.
  • Get a response including an UUID for authentication.
  • Use the UUID to authenticate REST requests.

It shows this request as an example:

**Header**

“`json

{

‘Content-Type’: ‘application/x-www-form-urlencoded’,

‘authorization’: ‘Basic <base64 encoded username:password>’

 }

 “`

 **Body**

 “`json

 {

 ‘grant_type’: ‘client_credentials’

 }

 “`

How do I turn with into a requests.post() ?


Solution

  • you have to build dictionaries and post them with requests :

    import requests
    import base64
    import json
    
    username = "user"
    password = "password"
    url = 'https://myurl.com'
    
    headers = {}
    headers['Content-Type'] = 'application/x-www-form-urlencoded'
    headers['authorization'] = 'Basic ' + base64.b64encode(bytes(username + ':' + password, 'utf-8')).decode('utf-8')
    
    body = {}
    body['grant_type'] = 'client_credentials'
    
    r = requests.post(url, data=json.dumps(body), headers=json.dumps(headers))