Python · Module 11 · Lesson 21 min read

Building APIs with Flask

Flask: a small, flexible web framework

You map URLs to Python functions with decorators, and return JSON with jsonify (or just return a dict).

Key pieces

  • @app.get("/users") / @app.post("/users") define routes for each HTTP method.
  • /users/<int:user_id> captures part of the URL as an argument.
  • request.get_json() reads the JSON body; request.args reads the query string.
  • Return (data, status_code) to set the status, e.g. 201 for created and 404 for not found.

Validate input

Never trust what the client sends. Check required fields and types, and return 400 with a helpful message.

Running

flask --app app run --debug starts a development server on http://127.0.0.1:5000.

⚠️ Debug mode and the built-in server are for development only. In production use a WSGI server like gunicorn.

💡 FastAPI is a popular modern alternative: it validates data with type hints and generates API docs automatically.

💻 Starts a web server, so run it on a computer.

Example

Python
from flask import Flask, jsonify, request

app = Flask(__name__)
users = {1: {"id": 1, "name": "Ana"}}

@app.get("/users")
def list_users():
    return jsonify(list(users.values()))

@app.get("/users/<int:user_id>")
def get_user(user_id):
    user = users.get(user_id)
    if user is None:
        return {"error": "User not found"}, 404
    return user

@app.post("/users")
def create_user():
    data = request.get_json(silent=True) or {}
    name = str(data.get("name", "")).strip()
    if not name:
        return {"error": "'name' is required"}, 400
    new_id = max(users, default=0) + 1
    users[new_id] = {"id": new_id, "name": name}
    return users[new_id], 201

if __name__ == "__main__":
    app.run(debug=True)

# Try it:  curl -X POST -H "Content-Type: application/json" \
#            -d '{"name": "Ben"}' http://127.0.0.1:5000/users