Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask REST API Error: The view function did not return a valid response

In a Flask REST API route in Python, the return type is a list

@app.route('/ent', methods=['POST'])
def ent():
    """Get entities for displaCy ENT visualizer."""
    json = request.get_json()
    nlp = MODELS[json['model']]
    doc = nlp(json['text'])
    return [
        {"start": ent.start_char, "end": ent.end_char, "label": ent.label_}
        for ent in doc.ents
    ]

This errors with:

TypeError: The view function did not return a valid response. The return type must be a string, dict, tuple, Response instance, or WSGI callable, but it was a list.

How can I get the API route on /ent to return a JSON array correctly?

like image 539
Adam Avatar asked Jan 19 '26 12:01

Adam


1 Answers

You can always convert the list into dict as needed by Flask as shown below

return { "data": [
        {"start": ent.start_char, "end": ent.end_char, "label": ent.label_}
        for ent in doc.ents
    ]}

Also have you seen Flask REST API responding with a JSONArray ?

like image 160
Shirish Goyal Avatar answered Jan 21 '26 01:01

Shirish Goyal



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!