Your First Flask Application
Introduction
A Flask app can be a dozen lines: create the app object, register a route, return a response. This chapter builds Hello Flask, runs it with flask run, tries GET and POST, and returns JSON with jsonify—patterns you will reuse in every project.
Prerequisites
- Flask Environment and Installation
- Virtual environment activated with Flask installed
Minimal Application
Create app.py:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
return "Hello, Flask!"
if __name__ == "__main__":
app.run(debug=True)Code explanation:
__name__helps Flask locate resources next to this moduleif __name__ == "__main__"runs the dev server only when you execute the file directly
Run With flask CLI
Set app module (if not already):
export FLASK_APP=app
export FLASK_DEBUG=1Start server:
flask runOutput similar to:
* Running on http://127.0.0.1:5000Change port:
flask run --port 8080Bind all interfaces (careful on public networks):
flask run --host 0.0.0.0 --port 5000Test in Browser or curl
curl http://127.0.0.1:5000/Expected: Hello, Flask!
Debug Mode
FLASK_DEBUG=1 or app.run(debug=True) enables:
- Auto reload on code changes
- Interactive debugger in browser on errors
Warning
Debug Mode Is Not for Production
The debugger allows code execution on errors—never expose it on the public internet.
Production uses Gunicorn with debug off—see deployment chapter.
Multiple Routes
Code explanation:
- Returning
(body, status)tuple sets HTTP status code explicitly
HTTP Methods
GET shows form; POST reads request.form.
JSON Response
from flask import Flask, jsonify
app = Flask(__name__)
@app.route("/api/time")
def api_time():
return jsonify({"message": "Use server time in real apps"})Or return a dict directly (Flask 3 serializes to JSON):
@app.route("/api/ping")
def ping():
return {"status": "ok"}Test:
curl -s http://127.0.0.1:5000/api/pingRun With python app.py
Alternative to flask run:
python app.pyUses app.run(debug=True) inside if __name__. Pick one style per project for consistency.
Practice Checklist
- Home route returns text
-
curlsucceeds on port 5000 - JSON route returns valid JSON
- You know how to stop server (Ctrl+C)
FAQ
Address already in use?
Another process on port 5000—flask run --port 5001 or kill the old process.
404 on /hello?
Check URL spelling and that server restarted after edits.
Changes not showing?
Ensure debug reload is on or restart manually.
flask: command not found?
Activate venv; pip install Flask.
Template HTML in return string?
Works for tiny demos—use Jinja2 templates in the Jinja2 chapter.