7

I'm trying to get multiple arguments from a url in Flask. After reading this SO answer I thought I could do it like this:

@app.route('/api/v1/getQ/', methods=['GET'])
def getQ(request):
    print request.args.get('a')
    print request.args.get('b')
    return "lalala"

But when I visit /api/v1/getQ/a=1&b=2, I get a TypeError: getQ() takes exactly 1 argument (0 given). I tried other urls, like /api/v1/getQ/?a=1&b=2 and /api/v1/getQ?a=1&b=2, but to no avail.

Does anybody know what I'm doing wrong here? All tips are welcome!

Community
  • 1
  • 1
kramer65
  • 50,427
  • 120
  • 308
  • 488
  • Your function getQ(request) is expecting an argument (request here). That's the problem, your function should not take any argument. – Steeven_b Aug 17 '16 at 09:18

2 Answers2

17

You misread the error message; the exception is about how getQ is called with python arguments, not how many URL parameters you added to invoke the view.

Flask views don't take request as a function argument, but use it as a global context instead. Remove request from the function signature:

from flask import request

@app.route('/api/v1/getQ/', methods=['GET'])
def getQ():
    print request.args.get('a')
    print request.args.get('b')
    return "lalala"

Your syntax to access URL parameters is otherwise perfectly correct. Note that methods=['GET'] is the default for routes, you can leave that off.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
5

You can try this to get multiple arguments from a url in Flask:

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

---print bar---

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

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

similar question Multiple parameters in in Flask approute

Community
  • 1
  • 1
Little Roys
  • 5,383
  • 3
  • 30
  • 28
  • The "" with curl for multiple query strings solved the problem that I was beating my head against. TYSM! – Bill Gale Dec 16 '20 at 01:49