How to obtain a single resource through its ID from a URL?

Question:

I have an URL such as: http://example.com/page/page_id

I want to know how to get the page_id part from url in the route. I am hoping I could devise some method such as:

@route('/page/page_id')
   def page(page_id):
       pageid = page_id
Asked By: ashutosh

||

Answers:

You should use the following syntax:

@app.route('/page/<int:page_id>')
def page(page_id):
    # Do something with page_id
    pass
Answered By: Andreas Argelius

It’s pretty straightforward – pass the path parameter in between angle brackets, but be sure to pass that name to your method.

@app.route('/page/<page_id>')
def page(page_id):
    pageid = page_id
    # You might want to return some sort of response...
Answered By: Makoto

You can specify the ID as integer :

@app.route('/page/<int:page_id>')
def page(page_id):
    # Replace with your custom code or render_template method
    return f"<h1>{page_id}</h1>"

or if you are using alpha_num ID:

@app.route('/page/<username>')
def page(username):
    # Replace with your custom code or render_template method
    return f"<h1>Welcome back {username}!</h1>"

It’s also possible to not specify any argument in the function and still access to URL parameters :

# for given URL such as domain.com/page?id=123

@app.route('/page')
def page():
    page_id = request.args.get("id") # 123

    # Replace with your custom code or render_template method
    return f"<h1>{page_id}</h1>"

However this specific case is mostly used when you have FORM with one or multiple parameters (example: you have a query :

domain.com/page?cars_category=audi&year=2015&color=red

@app.route('/page')
def page():
    category = request.args.get("cars_category") # audi
    year = request.args.get("year") # 2015
    color = request.args.get("color") # red

    # Replace with your custom code or render_template method
    pass

Good luck! 🙂

Answered By: Kevin Sabbe
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.