How to Create Routes in Flask: A Complete Guide
Flask is a popular lightweight Python web framework that allows developers to quickly build web applications. One of the core concepts in Flask is routing—the process of mapping URLs to functions that handle the logic of your web app. In this tutorial, we will cover how to create routes in Flask, step-by-step, so even beginners can get started with building functional web applications.
Prerequisites
- Python installed on your machine (preferably Python 3.6+)
- Basic knowledge of Python programming
- Flask installed (you can install it via
pip install Flask) - A text editor or IDE (such as VS Code, PyCharm, or Sublime Text)
Step 1: Set Up Your Flask Application
First, create a Python file to hold your Flask app, for example, app.py. Start by importing Flask and creating an instance of the Flask app.
from flask import Flask
app = Flask(__name__)
Step 2: Define Your First Route
Routes in Flask are created using the @app.route() decorator. This decorator tells Flask what URL should trigger the execution of the associated function.
Here’s a simple example of creating a route for the homepage:
@app.route('/')
def home():
return 'Welcome to the Flask Homepage!'
Explanation:
@app.route('/')defines the route for your homepage (root URL).home()is the function that runs when someone visits/.- The function returns the string that will be displayed in the browser.
Step 3: Add More Routes with Different URLs
You can create multiple routes for different pages. For example, a route for /about might look like this:
@app.route('/about')
def about():
return 'About Page: Learn more about this Flask app.'
Here you define a function about() that handles the URL /about.
Step 4: Running Your Flask Application
To run your Flask app, add the following code at the bottom of your app.py file:
if __name__ == '__main__':
app.run(debug=True)
This will run the app in debug mode, which is helpful during development because it shows detailed error messages and reloads automatically.
Then run in your terminal:
python app.py
Open your browser and go to http://127.0.0.1:5000/ to see the homepage, or http://127.0.0.1:5000/about to visit the about page.
Step 5: Using Variables in Routes
Flask also supports dynamic routes with variables. This is useful when you want to pass parameters through the URL.
For example, creating a user profile page that displays the username:
@app.route('/user/<username>')
def show_user_profile(username):
return f'User: {username}'
Now, visiting /user/alice will display “User: alice”.
Step 6: Specifying Variable Types
You can also specify the type of the variable for more control, such as int for integers:
@app.route('/post/<int:post_id>')
def show_post(post_id):
return f'Post Number: {post_id}'
This ensures that post_id passed in the URL is treated as an integer, and the route will only match if the URL has an integer.
Troubleshooting Common Issues
- 404 Not Found: This usually means the route you are trying to access does not exist. Double-check your routes and URLs.
- Import Errors: Ensure Flask is installed. Run
pip install Flaskto install it. - Code Changes Not Reflecting: Make sure you run Flask in debug mode with
app.run(debug=True).
Summary Checklist
- Install Flask with
pip install Flask - Create your Flask app instance
- Define routes using
@app.route()decorator - Add functions to handle different URLs
- Use dynamic variables in routes for flexible URLs
- Run the app with debug mode for easy development
For beginners looking to install Flask before creating routes, check out our How to Install Flask guide for a smooth setup experience.
With these basics, you can start building small web apps and expand your Flask skills further. Happy coding!
