Multiple parameters in Flask approute

PythonFlaskFlash Message

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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.

Hope that helps.

Solution 2 - Python

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

Solution 3 - Python

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')

Solution 4 - Python

@app.route('/createcm', methods=['GET'])
def foo():
    print request.args.get('summary')
    print request.args.get('change')

Solution 5 - Python

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

Solution 6 - Python

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

Solution 7 - Python

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

Solution 8 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2058205View Question on Stackoverflow
Solution 1 - PythonGMarshView Answer on Stackoverflow
Solution 2 - PythonLittle RoysView Answer on Stackoverflow
Solution 3 - PythonBurhan KhalidView Answer on Stackoverflow
Solution 4 - PythonPeng XiaoView Answer on Stackoverflow
Solution 5 - PythonWei HuangView Answer on Stackoverflow
Solution 6 - PythonAnorovView Answer on Stackoverflow
Solution 7 - PythonViraj WadateView Answer on Stackoverflow
Solution 8 - PythonS NagendraView Answer on Stackoverflow