Search code examples
jsonflaskrequestjwtrestful-authentication

Request to API Flask-Restful with JWT header and JSON data


I'm trying to do the following from python:

This work:

curl -i -H "Content-Type: application/json" -H "Accept: application/json" -X GET  -d "{\"Dato\":\"1\"}" http://localhost:5000/api/v1/recurso -H " Authorization: JWT ...p_GWs2XOAY" 

My resource:

class RecursoPrivado(Resource):

@jwt_required()
def get(self):
    json_data = request.get_json(force=True)
    #data  = json.loads(json_data)
    return json_data

api.add_resource(RecursoPrivado, '/recurso')

I tried this, but return Response [401]

url = 'http://localhost:5000/api/v1/recurso'
data={"Dato":"1"}
token="...p_GWs2XOAY" 
response=requests.get(url, data=data, headers={'Authorization':'JWT '+token})

Any ideas?


Solution

  • response = requests.get(url, data=data, headers={'Authorization': 'JWT '+token})
    

    should be this:

    response = requests.get(url, json=data, headers={'Authorization': 'JWT '+token})
    

    You're currently sending form-encoded data rather than JSON-encoded data.