0
0
Flaskframework~30 mins

Request validation in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Request Validation in Flask
📖 Scenario: You are building a simple web application using Flask. Users will submit their name and age through a form. You want to make sure the data received is valid before processing it.
🎯 Goal: Build a Flask app that validates incoming request data for name and age. The app should check that name is a non-empty string and age is a positive integer.
📋 What You'll Learn
Create a Flask app with a route to accept POST requests
Extract name and age from the request JSON
Add validation to check name is not empty and age is a positive integer
Return a JSON response indicating success or error
💡 Why This Matters
🌍 Real World
Validating user input is essential in web apps to prevent errors and security issues. This project shows how to check data before using it.
💼 Career
Backend developers often write request validation to ensure APIs receive correct data. This skill is fundamental for building reliable web services.
Progress0 / 4 steps
1
Set up Flask app and route
Import Flask and request from flask. Create a Flask app called app. Define a route /submit that accepts POST requests and a function submit() that returns a JSON response with {"message": "Ready"}.
Flask
Need a hint?

Use Flask(__name__) to create the app. Use @app.route decorator with methods=['POST']. Return JSON using jsonify.

2
Extract data from request JSON
Inside the submit() function, get the JSON data from the request using request.get_json() and store it in a variable called data. Then extract name and age from data.
Flask
Need a hint?

Use request.get_json() to get JSON data. Use data.get('name') and data.get('age') to extract values.

3
Add validation for name and age
Add validation inside submit() to check if name is a non-empty string and age is an integer greater than 0. If validation fails, return JSON with {"error": "Invalid input"} and status code 400.
Flask
Need a hint?

Use isinstance() to check types. Use name.strip() to check for empty strings. Return JSON error with status 400 if invalid.

4
Return success message with validated data
If validation passes, return a JSON response with {"message": "Data received", "name": name, "age": age}.
Flask
Need a hint?

Return JSON with keys message, name, and age using jsonify.