Your first Flask web server
Flask is the minimal Python web framework — one file, three lines, and you have a server.
Anatomy
Flask(__name__)— the app object.__name__tells Flask where to find templates/static.@app.get("/path")/@app.post(...)— bind a URL to a Python function.<int:user_id>in the path — typed URL param, passed as function arg.request.get_json()— parse incoming JSON body.jsonify(...)— return a JSON response with correct Content-Type.
Run it
pip install flask
python app.py
Then hit http://localhost:5000/ in your browser.
debug=True
Auto-reloads on file change + prints tracebacks in the browser. Never leave it on in production — it exposes a Python REPL to anyone hitting the error page.
Where Flask fits
- Micro-services, internal tools, MVPs, prototypes.
- Not batteries-included — no built-in ORM, no admin panel. That's a feature; you pick your own stack.
- Grown-up alternative: FastAPI (next lesson) if you want async + auto-docs + type hints as validation.
Try it
- Add a
/healthroute that returns{"ok": True}. - Add
/users(plural) that returns a list of 3 fake users.
3 graded exercises
Write the code, click Check. We’ll tell you exactly what to fix.
- Exercise 1
Create a Flask app with a
GET /route that returns the string"Hello, PyRun". Then useapp.test_client()to call the route and print the response body. - Exercise 2
Add a
GET /users/<int:user_id>route that returnsjsonify({"id": user_id, "name": f"User {user_id}"}). Call/users/42with the test client and print thenamefield from the JSON response. - Exercise 3
Add a
POST /echoroute that reads the JSON body viarequest.get_json()and returnsjsonify({"you_sent": body}). POST{"hello": "world"}and print the value ofyou_sentfrom the response.