First Flask Application (Hello World)
This is the smallest useful Flask app.
Create app.pyapp.py
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Hello, Flask!"from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Hello, Flask!"Whatβs happening?
app = Flask(__name__)app = Flask(__name__)creates the Flask application object.__name____name__helps Flask know where to find templates/static files later.
@app.route("/")@app.route("/")registers a route.- When a request hits
//, Flask callshome()home().
- When a request hits
- Returning a string becomes an HTTP response body.
Run it (two common ways)
Option A: flask runflask run (recommended)
Set the Flask app entry point:
export FLASK_APP=app
flask runexport FLASK_APP=app
flask runOption B: python app.pypython app.py
Youβll see this pattern in many tutorials:
if __name__ == "__main__":
app.run(debug=True)if __name__ == "__main__":
app.run(debug=True)This is valid, but for this tutorial track weβll mainly use flask runflask run because it matches production patterns better.
Common beginner error
If you see βWorking outside of application contextβ later, itβs usually because something that expects appapp is being used without a request/app context.
Donβt worry about it nowβjust remember Flask has context concepts.
π§ͺ Try It Yourself
Exercise 1 β Create a Flask App
Exercise 2 β Dynamic Route
Exercise 3 β Return JSON
If this helped you, consider buying me a coffee β
Buy me a coffeeWas this page helpful?
Let us know how we did
