77

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?

jps
  • 20,041
  • 15
  • 75
  • 79
user2058205
  • 997
  • 2
  • 9
  • 17

8 Answers8

106

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.

starball
  • 20,030
  • 7
  • 43
  • 238
GMarsh
  • 2,401
  • 3
  • 13
  • 22
33

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 "&"

Maicon Mauricio
  • 2,052
  • 1
  • 13
  • 29
Little Roys
  • 5,383
  • 3
  • 30
  • 28
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')
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
  • 4
    It should be noted that the above comment is incorrect at the time of writing, as the answer as been edited. – Doormatt Dec 02 '16 at 22:48
8
@app.route('/createcm', methods=['GET'])
def foo():
    print request.args.get('summary')
    print request.args.get('change')
Peng Xiao
  • 89
  • 1
  • 3
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"
}
Wei Huang
  • 174
  • 1
  • 6
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").

Anorov
  • 1,990
  • 13
  • 19
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
Viraj Wadate
  • 5,447
  • 1
  • 31
  • 29
2

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
S Nagendra
  • 33
  • 4