Welcome back to CodeYourCraft! Today, we're diving into Flask, a powerful Python web framework, and learning how to work with JSON data using the request.get_json() method. This lesson is designed for beginners and intermediates, so let's get started! 🚀
JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write and easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - Draft.
JSON is often used when data is sent between the server (Flask app) and the client (usually a web browser). It allows us to send complex data structures like objects and arrays.
First, let's create a new Flask app if you haven't already.
from flask import Flask, request, jsonify
app = Flask(__name__)Flask's request object has a method called get_json() which can be used to parse JSON data from the request body. Let's see an example:
@app.route('/parse_json', methods=['POST'])
def parse_json():
data = request.get_json()
return jsonify(data)In this example, we have created a route /parse_json that only accepts POST requests. When a POST request is made to this route with JSON data in the body, Flask will automatically parse it for us, and we can access the parsed data using request.get_json().
Let's see a practical example where we'll send a JSON object from a POST request and parse it in our Flask app.
{
"name": "John Doe",
"age": 30,
"hobbies": ["reading", "coding", "music"]
}@app.route('/parse_json', methods=['POST'])
def parse_json():
data = request.get_json()
# Accessing the parsed JSON data
name = data['name']
age = data['age']
hobbies = data['hobbies']
# Printing the parsed JSON data
print(name, age, hobbies)
return jsonify(data)What method of the Flask `request` object can be used to parse JSON data from the request body?
That's all for today! In the next lesson, we'll dive deeper into working with JSON data in Flask, including handling JSON errors and more advanced topics. Until then, keep coding and learning! 🌟
Remember, practice makes perfect. Try out the example on your own and experiment with different JSON objects and structures. Happy coding! 🎉