First Flask Application (Hello World)
This is the smallest useful Flask app.
Create app.py
Section titled “Create app.py”from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Hello, Flask!"What’s happening?
Section titled “What’s happening?”app = Flask(__name__)creates the Flask application object.__name__helps Flask know where to find templates/static files later.
@app.route("/")registers a route.- When a request hits
/, Flask callshome().
- When a request hits
- Returning a string becomes an HTTP response body.
Run it (two common ways)
Section titled “Run it (two common ways)”Option A: flask run (recommended)
Section titled “Option A: flask run (recommended)”Set the Flask app entry point:
export FLASK_APP=app
flask runOption B: python app.py
Section titled “Option B: python app.py”You’ll see this pattern in many tutorials:
if __name__ == "__main__":
app.run(debug=True)This is valid, but for this tutorial track we’ll mainly use flask run because it matches production patterns better.
Common beginner error
Section titled “Common beginner error”If you see “Working outside of application context” later, it’s usually because something that expects app is being used without a request/app context.
Don’t worry about it now—just remember Flask has context concepts.
Visualize it
Section titled “Visualize it”Here’s how a single request flows through the WSGI server and your Flask app before a response comes back.
flowchart LR B["Browser"] --> W["WSGI server"] W --> F["Flask app"] F --> M["Matched view function"] M --> R["Response"] R --> B
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – Create a Flask App
Section titled “Exercise 1 – Create a Flask App”Exercise 2 – Dynamic Route
Section titled “Exercise 2 – Dynamic Route”Exercise 3 – Return JSON
Section titled “Exercise 3 – Return JSON”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading