3

When the flask-jwt-extended token has expired, a HTTP request will result in this JSON response

{
  "msg": "Token has expired"
}

My application has a fixed error response format:

{
    "message": "Project name 'Test 8' already exist.",
    "error": {
        "resource": "Project",
        "field": "project_name",
        "code": "already_exists",
        "stack_trace": "(psycopg2.IntegrityError) duplicate key value violates unique constraint \"project_name_idx\"\nDETAIL:  Key (project_name)=(Test 8) already exists.\n [SQL: 'INSERT INTO project (project_name, project_root, deadline_id) VALUES (%(project_name)s, %(project_root)s, %(deadline_id)s) RETURNING project.project_id'] [parameters: {'project_name': 'Test 8', 'project_root': 'P:\\\\Test8', 'deadline_id': 2}]"
    }
}

How do I customize flask-jwt-extended error response?

Hanxue
  • 12,243
  • 18
  • 88
  • 130

2 Answers2

1

If you want to provide being able to change the standard JSON error response that is returned by Flask JWT so that you can send back your own standard error message format you would have to use JWTManager loader functions. Specifically the expired_token_loader

# Using the expired_token_loader decorator, we will now call
# this function whenever an expired but otherwise valid access
# token attempts to access an endpoint
@jwt.expired_token_loader
def my_expired_token_callback():
    return jsonify({
        'status': 401,
        'sub_status': 42,
        'msg': 'The token has expired'
    }), 401

Doing this may end up being tedious having to use all the loader functions for all the different ways in validating a token though.

You could considered writing your own generic utility function that returns the value portion of any response object text attribute and then put that into your fixed error message format that needs to be returned.

Example:

def extract_response_text(the_response):
    return the_response.json().get('msg')

Also I forgot to mention you could take the above example and use the @app.after_request decorator. This would allow you to configure all your apps endpoints to use this method before returning the response. In which you could alter or create your specific JSON response payload.