Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask Rest API - How to use Bearer API token in python requests

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!

like image 225
spy Avatar asked Jul 05 '18 13:07

spy


1 Answers

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.

like image 78
Frustrated Avatar answered Oct 16 '22 01:10

Frustrated