#🔒 How to read json post request in Flask ?

6 messages · Page 1 of 1 (latest)

wide pilot
#

I need to read the following request:
curl -X POST http://localhost:8080/cat
-d "{"name": "Tihon", "color": "red & white", "tail_length": 15, "whiskers_length": 12}"

how can i make it using flask ?
I tried:

from flask import Flask, request, jsonify

app = Flask(name)

@app.route('/cat', methods=['POST'])
def json_example():
request_data = request.get_json()
name = request_data.get('name')
color = request_data.get('color')
tail_length = request_data.get('tail_length')
whiskers_length = request_data.get('whiskers_length')

response_data = {
    'name': name,
    'color': color,
    'tail_length': tail_length,
    'whiskers_length': whiskers_length
}

return jsonify(response_data), 200

if name == 'main':
app.run(host='0.0.0.0', port=8080, debug=True)

but it returns an error 415. Also i tried with form.get() but it returns null

from flask import Flask, request, jsonify

app = Flask(name)

@app.route('/cat', methods=['POST'])
def add_cat():
# Получаем JSON-данные из тела запроса
name = request.form.get('name')
color = request.form.get('color')
tail_length = request.form.get('tail_length')
whiskers_length = request.form.get('whiskers_length')

return jsonify({'name': name, 'color': color, 'tail_length': tail_length,
                'whiskers_length': whiskers_length}), 200

if name == 'main':
app.run(host='0.0.0.0', port=8080)

granite finchBOT
#

@wide pilot

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

azure marsh
#

415 means unsupported media type

#

have you tried it with curl argument -H "Content-Type: application/json"

granite finchBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.