pythonauthenticationrequestpasswords

Base64 Authentication Python


I'm following an API and I need to use a Base64 authentication of my User Id and password.

'User ID and Password need to both be concatenated and then Base64 encoded'

it then shows the example

'userid:password'

It then proceeds to say:

'Provide the encoded value in an "Authorization Header"'

'for example: Authorization: BASIC {Base64-encoded value}'

How do I write this into a Python API request?

z = requests.post(url, data=zdata )

Solution

  • You can encode the data and make the request by doing the following:

    import requests, base64
    
    usrPass = "userid:password"
    b64Val = base64.b64encode(usrPass)
    r=requests.post(api_URL, 
                    headers={"Authorization": "Basic %s" % b64Val},
                    data=payload)
    

    I'm not sure if you've to add the "BASIC" word in the Authorization field or not. If you provide the API link, It'd be more clear.