0

I'm developing a Flask API. I want to create an API route that with accept JSON parameters and based on that json to do a search in database. My code looks like this:

@mod_api.route('/test', methods=['POST'])
def test():
    query_params = json.loads(request.data)
    json_resp = mongo.db.mydb.find(query_params)
    return Response(response=json_util.dumps(json_resp), status=200, mimetype='application/json')

Now when I run the api i go to my route: This example looks like this:

http://0.0.0.0:5002/api/test

I don't know exactly how to send a json parameter. If i do like this:

http://0.0.0.0:5002/api/test?{'var1':'123', 'var2':'456'}

I get an error ValueError("No JSON object could be decoded")

How to send this json parameter?

3
  • 1
    JSON means data in request body, not parameters in url. Commented Jan 7, 2016 at 12:49
  • @furas thank you for your answer? Can you explain it more please? Commented Jan 7, 2016 at 12:52
  • first print request.data to see what you get. maybe you should use test?args="{'var1':'123', 'var2':'456'}" or test?var1=123&var2=456 to get correct values in request.data. Commented Jan 7, 2016 at 13:04

2 Answers 2

1

You likely aren't supplying JSON data. With your browser at http://0.0.0.0:5002, use XHR in the browser console to test out your API.

var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
xmlhttp.open("POST", "/api/test");
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({'var1':'123', 'var2':'456'}));

You can see the request/response in the Network tab, and the Flask process will show the request happening as well.

Sign up to request clarification or add additional context in comments.

Comments

0

First, I want to point out that usually we use request.get_json() to get the json data, request.data contains the incoming request data that flask can't handle.

Test your app with curl should be easy, send the json data this way:

$ curl -H "Content-Type: application/json" -X POST -d '{"var1":"123", "var2":"456"}' http://localhost:5000/api/test

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.