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

Minimal Application

Create app.py:

python
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 module
  • if __name__ == "__main__" runs the dev server only when you execute the file directly

Run With flask CLI

Set app module (if not already):

bash
export FLASK_APP=app
export FLASK_DEBUG=1

Start server:

bash
flask run

Output similar to:

text
 * Running on http://127.0.0.1:5000

Change port:

bash
flask run --port 8080

Bind all interfaces (careful on public networks):

bash
flask run --host 0.0.0.0 --port 5000

Test in Browser or curl

bash
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

python
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):

python
@app.route("/api/ping")
def ping():
    return {"status": "ok"}

Test:

bash
curl -s http://127.0.0.1:5000/api/ping

Run With python app.py

Alternative to flask run:

bash
python app.py

Uses app.run(debug=True) inside if __name__. Pick one style per project for consistency.

Practice Checklist

  • Home route returns text
  • curl succeeds 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.