ashutosh
ashutosh

Reputation: 1232

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

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

Upvotes: 35

Views: 43758

Answers (3)

Kevin Sabbe
Kevin Sabbe

Reputation: 1452

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! :)

Upvotes: 8

Andreas Argelius
Andreas Argelius

Reputation: 3614

You should use the following syntax:

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

Upvotes: 16

Makoto
Makoto

Reputation: 106440

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...

Upvotes: 57

Related Questions