4

I am having a lot of trouble passing a URL parameter using request.args.get.

My code is the following:

from flask import Flask, request
app= Flask(__name__)

@app.route('/post?id=post_id', methods=["GET"])
def show_post():
    post_id=1232
    return request.args.get('post_id')

if __name__=="__main__":
     app.run(host='0.0.0.0')

After saving, I always type python filename.py in the command line, see Running on http://0.0.0.0:5000/ (Press CTRL+C to quit) as the return on the command line, and then type in the url (http://ip_addres:5000/post?id=1232) in chrome to see if it will return 1232, but it won't do it! Please help.

SAS
  • 77
  • 1
  • 2
  • 6

2 Answers2

11

You should leave the query parameters out of the route as they aren't part of it.

@app.route('/post', methods=['GET'])
def show_post():
    post_id = request.args.get('id')
    return post_id

request.args is a dictionary containing all of the query parameters passed in the URL.

bdjett
  • 514
  • 5
  • 9
  • What would the URL be then, please? Thank you so much! – SAS Jul 22 '16 at 06:32
  • The URL would still be `http://:5000/post?id=1232`. `id` is a query parameter that will appear in the `request.args` dictionary with the value `1232`. Note I edited the above answer to correct the name of the parameter. – bdjett Jul 22 '16 at 06:33
  • 1
    so basically, the request.args.get('id') automatically inserts the param inside the url? – SAS Jul 22 '16 at 06:39
  • No, not at all. You enter the URL `http://127.0.0.1:5000/post?id=1232`. Flask will cut off the query string, which is `?id=1232` and match on the actual path, which is `/post`. That path gets routed to the `show_post` function. `request.args` is a dictionary containing all of the query parameters that were passed along with the URL, which in this case is the key `id` and the value `1232`. `request.args` here will be a dictionary that looks like this: `{"id": "1232"}`. – bdjett Jul 22 '16 at 06:42
  • @SAS please see my answer also – Raja Simon Jul 22 '16 at 06:44
6

request.args is what you are looking for.

@app.route('/post', methods=["GET"])
def show_post()
    post_id = request.args.get('id')

request.args is get all the GET parameters and construct Multidict like this MultiDict([('id', '1232'),]) so using get you can get the id

Raja Simon
  • 10,126
  • 5
  • 43
  • 74
  • Thank you so much! What would the URL be then, please? – SAS Jul 22 '16 at 06:32
  • Okay, cool!:D Thank you so much! Your answer was equally helpful! Now I not only can use the code that y'all offered, but also understand what it is doing:) – SAS Jul 22 '16 at 06:51