Introduction
Routes are an essential part of a Flask web application. They define how your application responds to different URLs. In this guide, we'll walk you through the process of creating your first Flask route. By the end, you'll understand how to build a basic route and return a response.
Step 1: Create a Flask Application
Before you can define a route, you need a Flask application. Here's a simple Flask application that you can use as a starting point:
from flask import Flask
app = Flask(__name)
Make sure to install Flask if you haven't already by running pip install Flask
.
Step 2: Define a Route
To define a route, you can use the @app.route()
decorator. This decorator tells Flask which URL should trigger your function. Here's an example:
@app.route('/')
def hello():
return "Hello, Flask!"
In this example, we define a route that responds to the root URL (/
) and returns the string "Hello, Flask!" when you visit that URL in your browser.
Step 3: Running Your Application
To run your Flask application, you can add the following code at the end of your script:
if __name__ == '__main__':
app.run()
Now, you can run your application with the command python your_app.py
, and you should be able to access your route at http://localhost:5000
.
Conclusion
Congratulations! You've successfully built your first Flask route. Routes are the building blocks of a Flask application, and you can create more complex routes as your project evolves. Continue exploring Flask's capabilities and features to build powerful web applications.