How to pass an authorization header in Python?
I'm developing a API that I need to pass credentials of a user to be able to access an external service, my question is, what is the best way to obtain these credentials?
I thought about getting them from the header like this: import http.client, urllib.request
HttpClient = http.HTTPSConnection("api.website.com")
Header =. Request = urllib.Request("") urllib.HTTPBasicAuthHandler().addpassword( httpClient, password="mypassword" )
Response = httpClient.request(request, headers=header) print(response.read().decode())
The problem is that in order to print the response, it's needed to be in string format. But I want to be able to print it without the extra step.
Could you please help me with that? Or maybe could you suggest any other method? I also tried to use requests like this: import requests. Import base64. Requests.post("", headers='.format(credentials)} auth=(user, pwd)). Print(base64.b64decode(response.text))
But the result is the same. Thank you so much! Here is one option. Instead of your header value, you can have headers key, then you don't need to call .read() on the response object.HTTPSConnection("api.com")
Header = ".format(credentials)
How to set basic authentication in HTTP header in Python?
First, if you don't want to use a library, use this. It's much simpler and easier to use. If you are using a library, it will probably already have this code built in.
Import requests. Headers =. R = requests.get(' headers=headers) In requests 2.7.6 or newer, it will automatically add the Authorization header to the request. So no need to do anything.
You can use the urllib2 module for this: >>> import urllib2. >>> headers=. >>> response = urllib2.urlopen("", headers=headers) >>> response.read() .
Python 3000 - Welcome
.Welcome to python 3000
. Hi,. .
Here's a little something I prepared for you.
Related Answers
What is the basic format of Authorization header?
I am trying to write my own authorization header....
What are the methods of Web proxy authentication?
A proxy is a program that allows a computer running it to...
How to get basic auth from username and password in Python?
I'm creating REST APIs with angular. I have a login and...