Flask Hello World
Welcome to your first step in Flask web development! In this tutorial, we'll create the simplest possible Flask application - a "Hello World" program. This foundational exercise will help you understand the basic structure of Flask applications and set you up for building more complex web applications in the future.
What is Flask?
Flask is a lightweight web framework written in Python. It's designed to make getting started quick and easy, with the ability to scale up to complex applications. Unlike some other web frameworks, Flask aims to keep the core simple but extensible.
Prerequisites
Before you begin, make sure you have:
- Python installed on your system (version 3.6 or higher recommended)
- Basic understanding of Python programming
- A code editor or IDE of your choice
Setting Up Your Environment
First, let's install Flask using pip, Python's package installer:
pip install flask
After installation, you can verify that Flask was installed correctly by checking its version:
python -c "import flask; print(flask.__version__)"
This should output the version of Flask that was installed, such as 2.0.1
or similar.
Creating Your First Flask Application
Let's create our "Hello World" application step by step:
Step 1: Create a new file
Create a new file named app.py
or hello.py
in your working directory.
Step 2: Write the Flask application code
Add the following code to your file:
from flask import Flask
# Create a Flask application instance
app = Flask(__name__)
# Define a route and its handler function
@app.route('/')
def hello_world():
return 'Hello, World!'
# Run the application if this file is executed directly
if __name__ == '__main__':
app.run(debug=True)
Step 3: Understanding the code
Let's break down what each part does:
from flask import Flask
: Imports the Flask class from the flask package.app = Flask(__name__)
: Creates an instance of the Flask class. The__name__
variable is a special Python variable that gets the name of the current module.@app.route('/')
: A decorator that tells Flask what URL should trigger our function. In this case, it's the root URL '/'.def hello_world():
: The function that will be executed when the route is accessed.return 'Hello, World!'
: The content that will be sent to the browser.if __name__ == '__main__':
: Makes sure the app runs only when executed directly (not when imported).app.run(debug=True)
: Starts the development server with debug mode enabled.
Step 4: Run the application
To run your Flask application, open a terminal, navigate to the directory containing your Python file, and execute:
python app.py
# or if you named it hello.py:
python hello.py
You should see output similar to:
* Serving Flask app 'app' (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: XXX-XXX-XXX
Step 5: Access your application
Open a web browser and navigate to http://127.0.0.1:5000/ or http://localhost:5000/.
You should see "Hello, World!" displayed in your browser!
Adding More Routes
Let's enhance our application by adding another route:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
@app.route('/about')
def about():
return 'This is a simple Flask application!'
if __name__ == '__main__':
app.run(debug=True)
Now, if you navigate to http://localhost:5000/about, you'll see "This is a simple Flask application!" displayed.
Dynamic Routes with Parameters
You can also create dynamic routes that accept parameters:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
@app.route('/user/<username>')
def show_user_profile(username):
return f'Hello, {username}!'
if __name__ == '__main__':
app.run(debug=True)
If you navigate to http://localhost:5000/user/John, you'll see "Hello, John!" displayed.
Returning HTML Content
So far, we've only returned plain text. Let's return some HTML:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return '''
<!DOCTYPE html>
<html>
<head>
<title>Flask Hello World</title>
</head>
<body>
<h1>Hello, World!</h1>
<p>Welcome to my first Flask application.</p>
</body>
</html>
'''
if __name__ == '__main__':
app.run(debug=True)
Now when you visit http://localhost:5000/, you'll see a formatted HTML page with a heading and paragraph.
Real-World Application: A Simple API Endpoint
Flask is commonly used to create APIs. Here's a simple example that returns JSON data:
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/api/greeting/<name>')
def api_greeting(name):
return jsonify({
'message': f'Hello, {name}!',
'status': 'success'
})
if __name__ == '__main__':
app.run(debug=True)
If you navigate to http://localhost:5000/api/greeting/John, you'll see a JSON response like:
{
"message": "Hello, John!",
"status": "success"
}
This is the foundation of how RESTful APIs are built with Flask.
Debug Mode
You might have noticed we included debug=True
when running our application. This is useful during development for a few reasons:
- The server will reload automatically when you make code changes
- If an exception occurs, an interactive debugger will appear in the browser
- More detailed error messages are provided
Note: Never use debug mode in production environments, as it can expose sensitive information and allow code execution.
Summary
Congratulations! You've created your first Flask application and learned:
- How to install Flask and set up a basic application
- The structure of a simple Flask app
- How to define routes and handler functions
- Creating dynamic routes with parameters
- Returning different types of content (text, HTML, JSON)
- The purpose of debug mode
This "Hello World" example serves as the foundation for all Flask applications. From here, you can expand to include templates, database connections, user authentication, and much more.
Additional Resources
To continue your learning journey with Flask:
Exercises
To practice what you've learned:
- Create a Flask application with at least three different routes
- Add a route that accepts multiple parameters (e.g.,
/user/<username>/post/<post_id>
) - Create an API endpoint that returns a list of items as JSON
- Modify the "Hello World" application to display the current date and time
- Create a route that simulates a simple calculator (e.g.,
/calculate/add/5/3
returns8
)
Happy coding with Flask!
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)