Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flask-jwt-extended: customizing error message

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?

like image 785
Hanxue Avatar asked Jul 19 '26 18:07

Hanxue


2 Answers

Examples of this are documented here: http://flask-jwt-extended.readthedocs.io/en/latest/changing_default_behavior.html

The API docs are here: http://flask-jwt-extended.readthedocs.io/en/latest/api.html#module-flask_jwt_extended

like image 108
vimalloc Avatar answered Jul 21 '26 08:07

vimalloc


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.

like image 20
Andrew Spear Avatar answered Jul 21 '26 06:07

Andrew Spear



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!