Web Routes in Python
Web routes connect URLs to Python functions and define how a web application responds to client requests.
What are Web Routes?
A web route is a URL pattern that tells a web application which function should execute when a client requests that URL.
For example, a website can have separate routes for the home page, about page, courses page, and contact page.
Simple Definition
A web route maps a URL to a Python function or API endpoint.
Web Routing Flow
1. Client
Browser or application sends a request.
2. URL
Request contains a URL and HTTP method.
3. Python Route
Matching route executes a Python function and returns a response.
Basic Flask Route
Flask uses the route decorator to connect a URL with a Python function.
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Welcome to the Home Page"
if __name__ == "__main__":
app.run(debug=True)
When the browser requests /, Flask executes the home() function.
Creating Multiple Routes
A Flask application can define multiple routes for different pages.
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Home Page"
@app.route("/about")
def about():
return "About Page"
@app.route("/courses")
def courses():
return "Courses Page"
@app.route("/contact")
def contact():
return "Contact Page"
if __name__ == "__main__":
app.run(debug=True)
Understanding Routes
| URL | Function | Purpose |
|---|---|---|
| / | home() | Displays the home page |
| /about | about() | Displays the about page |
| /courses | courses() | Displays the courses page |
| /contact | contact() | Displays the contact page |
Routes and HTTP Methods
A route can be associated with one or more HTTP methods. The most common methods are GET and POST.
GET
GET is commonly used to retrieve information from the server.
@app.route("/courses", methods=["GET"])
def get_courses():
return "Course List"
POST
POST is commonly used to send data to the server.
@app.route("/courses", methods=["POST"])
def create_course():
return "Course Created"
Dynamic Routes
A dynamic route allows a value to be included in the URL. This is useful when the application needs to work with different records.
from flask import Flask
app = Flask(__name__)
@app.route("/student/<name>")
def student(name):
return "Student: " + name
if __name__ == "__main__":
app.run(debug=True)
Example URL:
/student/Rahul
The value Rahul is passed to the name parameter.
Integer Route Parameters
Flask can also define routes that expect an integer value.
from flask import Flask
app = Flask(__name__)
@app.route("/student/<int:id>")
def student(id):
return "Student ID: " + str(id)
if __name__ == "__main__":
app.run(debug=True)
Example:
/student/101
Query Parameters
Query parameters are sent after a question mark in a URL. Flask can read them using the request object.
from flask import Flask, request
app = Flask(__name__)
@app.route("/search")
def search():
name = request.args.get("name")
return "Search: " + str(name)
if __name__ == "__main__":
app.run(debug=True)
Example URL:
/search?name=Python
Example: CIIT Course Routes 📩🤓
A training institute website can use different routes for different resources.
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Welcome to CIIT Training Institute"
@app.route("/courses")
def courses():
return "Python | .NET | Java"
@app.route("/course/<name>")
def course(name):
return "Selected Course: " + name
@app.route("/contact")
def contact():
return "Contact CIIT Training Institute"
if __name__ == "__main__":
app.run(debug=True)
Common Route Parameter Types
| Type | Example | Meaning |
|---|---|---|
| string | <name> | Text value |
| int | <int:id> | Integer value |
| float | <float:price> | Decimal value |
| path | <path:file> | Value can contain slashes |
Organizing Routes
Small Flask applications can keep routes in one file. Larger applications should organize routes into separate modules or blueprints.
Example Structure
project/
│
├── app.py
├── routes/
│ ├── home.py
│ ├── courses.py
│ └── students.py
└── templates/
Important Routing Concepts
Static Route
A fixed URL such as /about.
Dynamic Route
A URL containing a variable value.
HTTP Method
Defines how the client interacts with a resource.
Path Parameter
A value included directly in the URL path.
Query Parameter
A value passed after the question mark.
Response
Data returned by the route to the client.
Best Practices
- Use clear and meaningful URL names.
- Use appropriate HTTP methods.
- Keep route functions simple.
- Use dynamic routes when working with specific records.
- Validate route parameters before using them.
- Organize routes when the project becomes large.
Common Mistakes
- Using an incorrect URL path.
- Using the wrong HTTP method.
- Forgetting to define a route.
- Using invalid route parameter syntax.
- Not validating dynamic values.
- Keeping too many routes in one large file.
Practice Exercise
Create a Flask application with the following routes:
- / → Display a welcome message.
- /students → Display a student list.
- /student/<id> → Display a student ID.
- /courses → Display available courses.
- /course/<name> → Display the selected course.
Test every route using a browser.
Summary
Web routes connect URLs with Python functions and define how a web application responds to client requests. Flask uses routes to process browser requests, and a single application can contain multiple routes. Routes can use different HTTP methods, while dynamic routes allow values to be included in URLs. Query parameters can be used to pass additional data, and proper route organization helps keep web applications easier to maintain.