MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Dynamic URLs & Type Converters0%
Study Materials
FlaskProgress 0%
1.1What is Flask & WSGI Architecture1.2Virtual Environments & First Flask Application1.3Flask CLI & Environment Configuration
2.1Dynamic URLs & Type Converters2.2Handling HTTP Methods (GET, POST, PUT, DELETE)2.3The Flask Request Object & Data Parsing2.4Response Objects, make_response & Cookies2.5Reverse Routing with url_for, Aborts & Error Handlers
HomeTutorialsFlaskDynamic URLs & Type Converters
Handling HTTP Methods (GET, POST, PUT, DELETE)

Dynamic URLs & Type Converters

Beginner12 min read•Updated: 2026-09-16•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

Routing connects incoming client URLs to corresponding Python view functions. In real-world web applications, URLs are rarely completely static; they contain dynamic resource identifiers such as user IDs, article slugs, or UUIDs.


1. Declaring Dynamic URL Parameters

To define dynamic URL parameters, place a variable name inside angle brackets <variable_name> within @app.route():

1from flask import Flask
2 
3app = Flask(__name__)
4 
5@app.route("/user/<username>")
6def show_user_profile(username):
7 # 'username' is passed as a string argument to the function
8 return f"Displaying profile for user: {username}"

If a client requests /user/sumit, Flask extracts 'sumit' and passes it as the username argument to show_user_profile().


2. Built-in URL Type Converters

By default, URL segments are parsed as strings. Flask provides built-in type converters (<converter:variable_name>) to validate and typecast incoming parameters automatically:

ConverterTypeDescriptionExample
stringstrAccepts any text without slashes (default)<string:category>
intintAccepts positive integers only; typecasts to int<int:product_id>
floatfloatAccepts positive floating point numbers<float:discount_rate>
pathstrAccepts any text, including slashes<path:file_subpath>
uuiduuid.UUIDAccepts RFC 4122 UUID strings<uuid:order_id>

Practical Code Example:

1import uuid
2from flask import Flask, abort
3 
4app = Flask(__name__)
5 
6@app.route("/products/<int:product_id>")
7def get_product(product_id):
8 # product_id is already an integer
9 assert isinstance(product_id, int)
10 return {"product_id": product_id, "name": f"Product #{product_id}"}
11 
12@app.route("/orders/<uuid:order_id>")
13def get_order(order_id):
14 # order_id is a valid uuid.UUID instance
15 assert isinstance(order_id, uuid.UUID)
16 return {"order_id": str(order_id), "status": "Shipped"}
17 
18@app.route("/downloads/<path:file_path>")
19def download_file(file_path):
20 # file_path captures slashes: e.g. 'docs/2026/report.pdf'
21 return f"Streaming file located at: {file_path}"

If a client visits /products/abc (a non-integer), Flask's converter automatically rejects the request with an HTTP 404 Not Found without ever invoking get_product().


3. Unique URLs and Trailing Slash Redirection

Flask enforces canonical, unique URLs:

1@app.route("/projects/")
2def projects():
3 return "The projects page"
4 
5@app.route("/about")
6def about():
7 return "The about page"
  1. 1
    Canonical folder URL (/projects/): If a user visits /projects without a trailing slash, Flask automatically sends an HTTP 308 Permanent Redirect to /projects/.
  2. 2
    Canonical file URL (/about): If a user visits /about/ with a trailing slash, Flask returns an HTTP 404 Not Found.

This rule prevents duplicate content penalties in search engine optimization (SEO).


4. Custom Regex Converters

When built-in converters are insufficient, you can create custom converters by subclassing werkzeug.routing.BaseConverter:

1from werkzeug.routing import BaseConverter
2 
3class RegexConverter(BaseConverter):
4 def __init__(self, url_map, *items):
5 super().__init__(url_map)
6 self.regex = items[0]
7 
8# Register converter with the Flask app
9app.url_map.converters['regex'] = RegexConverter
10 
11# Use in routes: match only 4-digit years
12@app.route("/archive/<regex('[0-9]{4}'):year>")
13def archive_by_year(year):
14 return f"Viewing archives for year {year}"

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What is the default type converter if none is specified (e.g. @app.route('/user/<username>'))?
Question 2
Which built-in converter permits slashes (/) within the URL segment?
Question 3
What happens if a client requests /orders/hello for a route defined as @app.route('/orders/<int:order_id>')?
Question 4
Why does Flask redirect /projects to /projects/ when the route is defined with a trailing slash?
Question 5
How do you register a custom URL converter in Flask?
Next Lesson

Handling HTTP Methods (GET, POST, PUT, DELETE)

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Flask CLI & Environment ConfigurationHandling HTTP Methods (GET, POST, PUT, DELETE)

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master Flask with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext