Python Flask Routes: Handling Requests and JSON Responses
Build Flask routes that handle HTTP requests and return JSON, with request parsing, status codes, error handling, validation, and production tips.

In Flask, a route maps a URL to a Python function, and the function's return value becomes the HTTP response. For a JSON API, the simplest pattern is to return a Python dictionary; Flask serializes it as JSON. The explicit alternative is flask.jsonify().
from flask import Flask, jsonify
app = Flask(__name__)
@app.route("/health")
def health():
return {"status": "ok"}Since Flask 1.1, returning a dict from a view function automatically serializes it to JSON with the correct Content-Type: application/json header. The jsonify() function does the same thing explicitly and also accepts keyword arguments:
@app.route("/health")
def health():
return jsonify(status="ok")Both approaches produce the same wire format. The difference is mainly readability: jsonify() makes the intent explicit and is convenient when the response is built from keyword arguments. If the response already exists as a dict variable, returning the variable directly is shorter.
Reading Request Data in Flask Routes
The request object gives you access to what the client sent. The request data you will usually read in a JSON API is query parameters or a JSON request body.
from flask import request
@app.route("/users")
def list_users():
page = request.args.get("page", default=1, type=int)
limit = request.args.get("limit", default=20, type=int)
return {"page": page, "limit": limit, "users": []}request.args is a MultiDict containing URL query parameters. The get() method with type=int converts the value and falls back to the default if the value is missing or cannot be parsed.
For a JSON request body, use request.get_json():
@app.route("/users", methods=["POST"])
def create_user():
data = request.get_json()
if not isinstance(data, dict):
return {"error": "Request body must be a JSON object"}, 400
return {"id": 123, "name": data.get("name")}, 201request.get_json() returns None when the body is empty or the Content-Type header is not application/json. The isinstance check matters because a valid JSON body can also be an array or a scalar. Calling it with silent=True suppresses the 400 error that Flask raises on malformed JSON, which lets you handle the failure yourself instead of returning Flask's default HTML error page.
Choosing the Right HTTP Method for a Route
A route can accept one or more HTTP methods. The methods parameter on @app.route() controls which verbs the route responds to. The declared methods for a route default to GET.
@app.route("/items/<int:item_id>", methods=["GET", "PUT", "DELETE"])
def handle_item(item_id):
if request.method == "GET":
return {"id": item_id, "name": "example"}
if request.method == "PUT":
data = request.get_json()
return {"id": item_id, "updated": data.get("name")}
if request.method == "DELETE":
return {"deleted": item_id}, 204When a route accepts multiple methods, you typically branch on request.method inside the function. For larger APIs, flask.views.MethodView provides a class-based structure where each HTTP method maps to a method on the class; that is cleaner when a single resource has many operations.
Setting Status Codes, Headers, and Content-Type
Returning a tuple of (body, status) is the shortest way to set a status code. The body can be a dict, a string, or a response object.
@app.route("/items/<int:item_id>")
def get_item(item_id):
if item_id > 100:
return {"error": "Item not found"}, 404
return {"id": item_id, "name": "example"}For more control, build a Response object explicitly:
from flask import Response
import json
@app.route("/items/<int:item_id>")
def get_item(item_id):
payload = {"id": item_id, "name": "example"}
return Response(
json.dumps(payload),
status=200,
mimetype="application/json"
)Flask sets Content-Type: application/json automatically when you return a dict or use jsonify(). The Accept header from the client is not used to negotiate the response format by default. If you need content negotiation, you must implement it yourself:
@app.route("/items")
def items():
if request.accept_mimetypes.best == "text/html":
return "<ul><li>example</li></ul>"
return {"items": ["example"]}For most JSON APIs, checking Accept is unnecessary because the client already knows the API returns JSON. But if the same route serves both browsers and API clients, explicit negotiation prevents the wrong content type from reaching the client.
Serializing Python Objects That Are Not JSON-Serializable
Python dicts with string keys and JSON-compatible values serialize without issue. But datetime objects, Decimal values, and custom class instances do not, because Flask's default JSON serializer does not know how to convert them.
from datetime import datetime
@app.route("/now")
def now():
return {"timestamp": datetime.now().isoformat()}Converting the value before returning it is the simplest fix. If you need the same conversion across many routes, you can centralize it through Flask's JSON configuration. The interface depends on the Flask version: Flask 2.2 deprecated app.json_encoder, and Flask 2.3 removed it; newer releases use the app.json provider configuration. Check the JSON customization guide for your Flask version before implementing a custom serializer.
Handling Errors and Returning JSON Instead of HTML
By default, Flask returns an HTML error page for unhandled exceptions and for HTTP errors raised with abort(). If your API clients expect JSON, register error handlers that return JSON.
@app.errorhandler(404)
def not_found(error):
return {"error": "Resource not found"}, 404
@app.errorhandler(500)
def internal_error(error):
return {"error": "Internal server error"}, 500The error handler receives the exception object as an argument. For HTTPException subclasses, you can read the original status code and description from the exception if you want to echo them in the response body.
from werkzeug.exceptions import HTTPException
@app.errorhandler(HTTPException)
def handle_http_exception(error):
return {"error": error.description}, error.codeThis single handler covers all HTTP errors, including 400, 401, 403, 404, and 405. Registering it alongside the 500 handler keeps your API responses consistent even when something fails.
Production Considerations for JSON Routes
By default, the Flask development server is single-threaded and not designed for production traffic. When you deploy a Flask app that serves JSON responses, serve it with a production WSGI server such as Gunicorn or uWSGI, usually behind a reverse proxy.
JSON serialization is fast for small payloads, but large response bodies increase memory usage and latency. If a route returns a large collection, consider pagination. If the data source can be generated incrementally, a streaming response can reduce latency, but it adds complexity and is not needed for most JSON APIs.
CORS is another concern. If your Flask API is called from a browser on a different origin, the browser blocks the response unless the server sends the appropriate CORS headers. The flask-cors extension handles this cleanly:
from flask_cors import CORS
CORS(app)Without CORS headers, a frontend at http://localhost:3000 will not be able to read a response from a Flask API at http://localhost:5000, even though the request reaches the server. The browser enforces this restriction after the response is received.
Validating Request Data Before Returning JSON
A route that accepts JSON input should validate the data before using it. request.get_json() returns whatever the client sent, including unexpected fields or wrong types. A minimal validation check keeps the route safe:
@app.route("/users", methods=["POST"])
def create_user():
data = request.get_json(silent=True)
if not isinstance(data, dict):
return {"error": "Request body must be a JSON object"}, 400
if "name" not in data:
return {"error": "Field 'name' is required"}, 400
if not isinstance(data["name"], str):
return {"error": "Field 'name' must be a string"}, 400
return {"id": 123, "name": data["name"]}, 201For complex schemas, a validation library such as Marshmallow or Pydantic reduces boilerplate. But for a small API, the inline checks above are often sufficient and keep the route readable.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.