I have developed an API in Flask and using basic authentication token. When I testing this API with curl then bearer token accepted and API is working. But when using in python requests it is showing 401 error.
Python code used for Flask API:
@app.route('/api/resource')
@auth.login_required
def get_resource():
return
jsonify({'data': 'Hello, %s!' % g.user.username.title()})
Testing with curl is working fine: >
curl -u eyJhbGciOiJIUzI1NsdfCI6MTUzMDc5MDIzNCwiZXhwIjoxNT
MwNzkwODM0fQ.eyJpZCsf.jKiafmv-qrvAxVo7UKQuohS2vkF-9scpuqsKRuw:sp -i -X GET
http://127.0.0.1:5000/api/resource
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 32
Server: Werkzeug/0.14.1 Python/3.6.4
Date: Thu, 05 Jul 2018 11:33:22 GMT
{ "data": "Hello, FlaskAPI!"}
Python code to consume API:
import requests
url = "http://127.0.0.1:5000/api/resource"
headers = {
'Content-Type': "application/json",
'Authorization': "Bearer eyJhbGciOiJIUzI1NiIsImlhsfsdfsdzNCwiZXhwIjoxNTMwNzksdfsdsdRF.eyJpZCI6MX0.YhZvjKiafmv-qrvAxVo7UKQuohS2vkF-9scpuqsKRuw"
}
response = requests.request("GET", url, headers=headers)
print(response.text)
It shows error: Unauthorized Access 401
How to use Bearer token used in curl from Python or postman?
Thanks in advance!
If you want us to use Bearer tokens take a look at Miguel Grinberg's Application Programming Interfaces and scroll down to the "Tokens in the User Model". However, the whole thing deserves a read.
Another article is Real Pythons's Token-Based Authentication with Flask.
Both of these will help with understanding and implementation of bearer tokens.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With