Multiple parameters in Flask approute
Asked Answered
I

8

81

How to write the flask app.route if I have multiple parameters in the URL call?

Here is my URL I am calling from AJax:

http://0.0.0.0:8888/createcm?summary=VVV&change=Feauure

I was trying to write my flask app.route like this:

@app.route('/test/<summary,change>', methods=['GET']

But this is not working. Can anyone suggest me how to mention the app.route?

Interior answered 3/3, 2013 at 5:16 Comment(0)
P
109

The other answers have the correct solution if you indeed want to use query params. Something like:

@app.route('/createcm')
def createcm():
   summary  = request.args.get('summary', None)
   change  = request.args.get('change', None)

A few notes. If you only need to support GET requests, no need to include the methods in your route decorator.

To explain the query params. Everything beyond the "?" in your example is called a query param. Flask will take those query params out of the URL and place them into an ImmutableDict. You can access it by request.args, either with the key, ie request.args['summary'] or with the get method I and some other commenters have mentioned. This gives you the added ability to give it a default value (such as None), in the event it is not present. This is common for query params since they are often optional.

Now there is another option which you seemingly were attempting to do in your example and that is to use a Path Param. This would look like:

@app.route('/createcm/<summary>/<change>')
def createcm(summary=None, change=None):
    ...

The url here would be: http://0.0.0.0:8888/createcm/VVV/Feauure

With VVV and Feauure being passed into your function as variables.

Photochromy answered 28/12, 2016 at 21:21 Comment(1)
if place <summary> in URL, can the default value be None? e.g. 0.0.0.0:8888/createcm//FeauureAmelioration
B
34

You can try this:

Curl request

curl -i "localhost:5000/api/foo?a=hello&b=world"  

flask server

from flask import Flask, request

app = Flask(__name__)


@app.route('/api/foo/', methods=['GET'])
def foo():
    bar = request.args.to_dict()
    print bar
    return 'success', 200

if __name__ == '__main__':   
    app.run(debug=True)

console output

{'a': u'hello', 'b': u'world'}

P.S. Don't omit double quotation(" ") with curl option, or it not work in Linux cuz "&"

Bremble answered 17/8, 2016 at 3:39 Comment(0)
C
28

Routes do not match a query string, which is passed to your method directly.

from flask import request

@app.route('/createcm', methods=['GET'])
def foo():
   print request.args.get('summary')
   print request.args.get('change')
Carbaugh answered 3/3, 2013 at 5:20 Comment(1)
It should be noted that the above comment is incorrect at the time of writing, as the answer as been edited.Placard
M
8
@app.route('/createcm', methods=['GET'])
def foo():
    print request.args.get('summary')
    print request.args.get('change')
Mors answered 20/1, 2014 at 5:20 Comment(0)
D
7

In your requesting url: http://0.0.0.0:8888/createcm?summary=VVV&change=Feauure, the endpoint is /createcm and ?summary=VVV&change=Feauure is args part of request. so you can try this:

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/createcm', methods=['get'])
def create_cm():
    summary = request.args.get('summary', None) # use default value repalce 'None'
    change = request.args.get('change', None)
    # do something, eg. return json response
    return jsonify({'summary': summary, 'change': change})


if __name__ == '__main__':
    app.run(debug=True)

httpie examples:

http get :5000/createcm summary==vvv change==bbb -v
GET /createcm?summary=vvv&change=bbb HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Host: localhost:5000
User-Agent: HTTPie/0.9.8



HTTP/1.0 200 OK
Content-Length: 43
Content-Type: application/json
Date: Wed, 28 Dec 2016 01:11:23 GMT
Server: Werkzeug/0.11.13 Python/3.6.0

{
    "change": "bbb",
    "summary": "vvv"
}
Dud answered 27/12, 2016 at 7:17 Comment(0)
T
6

You're mixing up URL parameters and the URL itself.

You can get access to the URL parameters with request.args.get("summary") and request.args.get("change").

Tobietobin answered 3/3, 2013 at 5:19 Comment(0)
B
5

Simply we can do this in two stpes: 1] Code in flask [app.py]

from flask import Flask,request

app = Flask(__name__)

@app.route('/')
def index():
    return "hello"

@app.route('/admin',methods=['POST','GET'])
def checkDate():
    return 'From Date is'+request.args.get('from_date')+ ' To Date is '+ request.args.get('to_date')


if __name__=="__main__":
    app.run(port=5000,debug=True)

2] Hit url in browser:

http://127.0.0.1:5000/admin?from_date=%222018-01-01%22&to_date=%222018-12-01%22
Bulganin answered 5/12, 2018 at 6:38 Comment(0)
I
3

in flak we do in this way

@app.route('/createcm')
def createcm():
    summary  = request.args.get('summary', type=str ,default='')
    change  = request.args.get('change',type=str , default='')

now you can run your end-point with different optional paramters like below

http://0.0.0.0:8888/createcm?summary=VVV  
              or
http://0.0.0.0:8888/createcm?change=Feauure
              or
http://0.0.0.0:8888/createcm?summary=VVV&change=Feauure
Intermission answered 23/6, 2021 at 2:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.