Advanced level · Module 4: Building Web APIs with Flask · Lesson 2 of 5
Accepting and Validating Input
Accept JSON in POST and PUT requests, validate it and update the database.
In this lesson you will
- Parse JSON request bodies
- Return 400 with clear messages for invalid data
Key concepts
POST/PUTrequest.get_json()validationerror handler
The lesson
APIs that change data receive JSON in the request body: request.get_json(). Never trust it — clients can send missing fields, wrong types or negative quantities.
Validate every field and return 400 Bad Request with a clear message listing what is wrong. A successful creation returns 201 Created with the new item.
Reuse the validators you wrote at the Intermediate level, so the same rules apply whether data arrives from a CSV file or the API.
Step by step
- Add POST /products that reads the JSON body.
- Validate name, price and stock and collect all errors.
- Return 400 with the errors, or 201 with the new product.
- Test valid and invalid requests.
Validating input in a Flask API
Collect every validation problem and return a clear 400 response, or 201 with the new product.
from flask import Flask, jsonify, request app = Flask(__name__)products = [] @app.post("/products")def create_product(): data = request.get_json(silent=True) or {} errors = [] name = str(data.get("name", "")).strip() if not name: errors.append("name is required") price = data.get("price") if not isinstance(price, (int, float)) or price < 0: errors.append("price must be a number of 0 or more") if errors: return jsonify({"errors": errors}), 400 product = {"id": len(products) + 1, "name": name, "price": price} products.append(product) return jsonify(product), 201
Output
POST /products {"name": "", "price": -5}
→ 400 {"errors": ["name is required", "price must be a number of 0 or more"]}
POST /products {"name": "Exercise book", "price": 500}
→ 201 {"id": 1, "name": "Exercise book", "price": 500}How it works
get_json(silent=True) returns None instead of failing when the body is not valid JSON, so the code can report a clean error. Every rule adds to an errors list, so the client learns about all problems at once rather than one per request. Invalid requests get 400 Bad Request; a successful creation returns 201 Created with the new item.
Key concepts
request.get_jsonvalidation list400 vs 201jsonify
Where you would use it
Any API that accepts data from a mobile app, form or partner system.
Practice activity
Add POST /products and PUT /products/<id>/stock with validation for required fields and non-negative numbers.
Expected result: Endpoints that accept valid data and reject invalid data with clear 400 responses.
Check your understanding
-
What status code suits a request with a missing required field?
Show answer
400 Bad Request.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.