0
0
Flaskframework~5 mins

Accessing JSON data in Flask

Choose your learning style9 modes available
Introduction

We use JSON data to send and receive information in web apps. Accessing JSON data lets your Flask app read this information easily.

When your Flask app receives data from a web form or API in JSON format.
When you want to read user input sent as JSON in a POST request.
When your app needs to process data sent from JavaScript running in the browser.
When building APIs that accept JSON data from clients.
When you want to extract specific values from JSON to use in your app logic.
Syntax
Flask
from flask import request

json_data = request.get_json()
value = json_data['key']

request.get_json() reads the JSON data sent in the request body.

You can access values by their keys like a Python dictionary.

Examples
This example reads a JSON object with a 'name' key and returns a greeting.
Flask
from flask import Flask, request

app = Flask(__name__)

@app.route('/data', methods=['POST'])
def data():
    json_data = request.get_json()
    name = json_data['name']
    return f"Hello, {name}!"
Uses get to safely access 'age' key with a default value.
Flask
from flask import Flask, request

app = Flask(__name__)

@app.route('/info', methods=['POST'])
def info():
    json_data = request.get_json()
    age = json_data.get('age', 'unknown')
    return f"Age is {age}."
Sample Program

This Flask app has a POST endpoint '/user' that reads JSON data with 'username' and 'email'. It returns a JSON response confirming the data received.

Flask
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/user', methods=['POST'])
def user():
    json_data = request.get_json()
    username = json_data.get('username', 'Guest')
    email = json_data.get('email', 'No email provided')
    response = {
        'message': f'User {username} with email {email} received.',
        'status': 'success'
    }
    return jsonify(response)

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

Always check if request.get_json() returns None if no JSON was sent.

Use jsonify() to send JSON responses properly with correct headers.

Make sure the client sets the Content-Type header to application/json when sending JSON.

Summary

Use request.get_json() to access JSON data sent to Flask routes.

Access JSON keys like a Python dictionary to get values.

Always handle missing keys safely to avoid errors.