Adam
Adam

Reputation: 2031

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?

Upvotes: 3

Views: 11697

Answers (2)

LazyCoder
LazyCoder

Reputation: 1265

The reason it is failing is because the views in Flask require a hashable return type. You can always convert your return values to hashable types viz string, dict, tuple etc and then transform from the result.

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

Upvotes: 3

Shirish Goyal
Shirish Goyal

Reputation: 510

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 ?

Upvotes: 3

Related Questions