Flask Working with JSON Receiving JSON from an HTTP Request

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

If the mimetype of the HTTP request is application/json, calling request.get_json() will return the parsed JSON data (otherwise it returns None)

from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/api/echo-json', methods=['GET', 'POST', 'DELETE', 'PUT'])                                                                                                    
def add():                                                                                                                              
    data = request.get_json()
    # ... do your business logic, and return some response
    # e.g. below we're just echo-ing back the received JSON data
    return jsonify(data)

Try it with curl

The parameter -H 'Content-Type: application/json' specifies that this is a JSON request:

 curl -X POST -H 'Content-Type: application/json' http://127.0.0.1:5000/api/echo-json -d '{"name": "Alice"}'               
{
  "name": "Alice"
}

To send requests using other HTTP methods, substitute curl -X POST with the desired method e.g. curl -X GET, curl -X PUT, etc.



Got any Flask Question?