KeepingItClassy
KeepingItClassy

Reputation: 171

Flask: Unicode error when trying to parse POST payload

I'm trying to build a Flask API endpoint that takes an image url from the JSON payload. I'm using flask.request.get_json() which has worked for me before:

@app.route("/caption", methods=["POST"])
def caption():
    image_url = flask.request.get_json().get('image_url')
    image_info = get_caption(image_url)
    return flask.jsonify(image_info)

However, when trying to post a URL to the endpoint with content type application/json I get an AttributeError: 'unicode' object has no attribute 'image_url'

I tried printing out the contents of flask.request.get_json() and I get

{u'image_url': u'https://images.pexels.com/photos/66997/pexels-photo-66997.jpeg'}

How can I get my payload as a dictionary instead of a unicode object?

Upvotes: 1

Views: 694

Answers (3)

KeepingItClassy
KeepingItClassy

Reputation: 171

I just realized that the error was in the way I handled image_url in my get_caption function. The error message led me to believe that the problem was with parsing the payload. I apologize for the misunderstanding. Thanks everyone who answered, you helped me find the bug.

Upvotes: 1

G. Bachman
G. Bachman

Reputation: 11

Seems like you're using python2 and you can print out the result so why not print out the type of the the dictionary-like object and find out its type.

Upvotes: 1

MatrixTXT
MatrixTXT

Reputation: 2502

Though I don't think flask.request.get_json() return you the dictionary you posted as @zwer mentioned. But if you really get that dictionary. Try to do this to achieve your aim.

import json
def caption():
    image_json = flask.request.get_json()
    image_url = json.loads(json.dumps(image_json)).get('image_url')

Upvotes: 1

Related Questions