how to send multiple parameters to route using flask?

  • Last Update :
  • Techknowledgy :

To add multiple parameters in a Python Flask app route, we can add the URL parameter placeholders into the route string., How to add optional URL parameters with Python Django?To add optional URL parameters with Python Django, we call add multiple rules for the… ,to create the createcm view function by using the app.route decorator.,Sometimes, we want to add multiple parameters in a Python Flask app route.

For instance, we write

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

Suggestion : 2

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)

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

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

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')
@app.route('/createcm', methods = ['GET'])
def foo():
   print request.args.get('summary')
print request.args.get('change')

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

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

Suggestion : 3

Parameters can be used when creating routes. A parameter can be a string (text) like this: /product/cookie.,If you want a flask route with multiple parameters that’s possible. For the route /create/<first_name>/<last_name> you can do this:,So you can pass parameters to your Flask route, can you pass numbers?,The example here creates the route /sale/<transaction_id>, where transaction_id is a number.

@app.route('/') def index():
@app.route('/hello') def hello_world(): return "hello world"
@app.route('/product/<name>')def get_product(name): return "The product is " + str(name)
@app.route('/sale/<transaction_id>')def get_sale(transaction_id=0): return "The transaction is "+str(transaction_id)
@app.route('/create/<first_name>/<last_name>')def create(first_name=None, last_name=None): return 'Hello ' + first_name + ',' + last_name
123456789

Suggestion : 4

In the previous section, we saw how to start a server with Flask, add a couple of routes, and make sure our server is listening for changes using FLASK_DEBUG=1. Now let's build off of that knowledge and add some more dynamic routes.,Capture URL parameters and define their types,First, try to replicate the example above! There is a lot of value in building up the muscle memory for creating simple Flask applications, routes and understanding how URL parameters work.,Notice that Flask is smart enough to determine how to handle the routing based on the type of the variable passed in to the URL: /name/elie gets handled by say_name, while /name/1 gets handled by favorite_number. Moreover, we see that in the latter case, the number really is of type number, since we can double it and display the result on the page.

mkvirtualenv flask - routing
workon flask - routing
pip install flask
from flask
import Flask

app = Flask(__name__)

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

@app.route('/hi')
def hi():
   return "Hi!"

@app.route('/bye')
def bye():
   return "Bye!"
@app.route('/name/elie')
def elie():
   return "The name is elie"

@app.route('/name/matt')
def matt():
   return "The name is matt"
from flask import Flask
app = Flask(__name__)

@app.route('/')
def home():
    return "Welcome!"

#let's make up a parameter called name. Its value is going to be WHATEVER someone requests, but we will respond with the string "The name is" along with the value in the URL.
@app.route('/name/<person>')
def say_name(person):
    return f"The name is {person}"

# since all URL parameters are strings, we can convert them right away to another data type in our route definition
@app.route('/name/<int:num>')
def favorite_number(num):
    return f"Your favorite number is {num}, which is half of {num * 2}"

Suggestion : 5

Now that we have seen how to use Path and Query, let's see more advanced uses of request body declarations.,First, of course, you can mix Path, Query and request body parameter declarations freely and FastAPI will know what to do.,Body also has all the same extra validation and metadata parameters as Query,Path and others you will see later.,You can add multiple body parameters to your path operation function, even though a request can only have a single body.

from typing
import Union

from fastapi
import FastAPI, Path
from pydantic
import BaseModel

app = FastAPI()

class Item(BaseModel):
   name: str
description: Union[str, None] = None
price: float
tax: Union[float, None] = None

@app.put("/items/{item_id}")
async def update_item( *
      ,
      item_id: int = Path(title = "The ID of the item to get", ge = 0, le = 1000),
      q: Union[str, None] = None,
      item: Union[Item, None] = None,
   ):
   results = {
      "item_id": item_id
   }
if q:
   results.update({
      "q": q
   })
if item:
   results.update({
      "item": item
   })
return results
from fastapi
import FastAPI, Path
from pydantic
import BaseModel

app = FastAPI()

class Item(BaseModel):
   name: str
description: str | None = None
price: float
tax: float | None = None

@app.put("/items/{item_id}")
async def update_item( *
      ,
      item_id: int = Path(title = "The ID of the item to get", ge = 0, le = 1000),
      q: str | None = None,
      item: Item | None = None,
   ):
   results = {
      "item_id": item_id
   }
if q:
   results.update({
      "q": q
   })
if item:
   results.update({
      "item": item
   })
return results
{
   "name": "Foo",
   "description": "The pretender",
   "price": 42.0,
   "tax": 3.2
}
from typing
import Union

from fastapi
import FastAPI
from pydantic
import BaseModel

app = FastAPI()

class Item(BaseModel):
   name: str
description: Union[str, None] = None
price: float
tax: Union[float, None] = None

class User(BaseModel):
   username: str
full_name: Union[str, None] = None

@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item, user: User):
   results = {
      "item_id": item_id,
      "item": item,
      "user": user
   }
return results
from fastapi
import FastAPI
from pydantic
import BaseModel

app = FastAPI()

class Item(BaseModel):
   name: str
description: str | None = None
price: float
tax: float | None = None

class User(BaseModel):
   username: str
full_name: str | None = None

@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item, user: User):
   results = {
      "item_id": item_id,
      "item": item,
      "user": user
   }
return results
{
   "item": {
      "name": "Foo",
      "description": "The pretender",
      "price": 42.0,
      "tax": 3.2
   },
   "user": {
      "username": "dave",
      "full_name": "Dave Grohl"
   }
}

Suggestion : 6

Register a rule for routing incoming requests and building URLs. The route() decorator is a shortcut to call this with the view_func argument. These are equivalent:,A data structure of functions to call to pass extra context values when rendering templates, in the format {scope: [functions]}. The scope key is the name of a blueprint the functions are active for, or None for all requests.,A data structure of functions to call to modify the keyword arguments passed to the view function, in the format {scope: [functions]}. The scope key is the name of a blueprint the functions are active for, or None for all requests.,The other use case of this function is to force the return value of a view function into a response which is helpful with view decorators:

from flask
import Flask
app = Flask(__name__)
app = Flask('yourapplication')
app = Flask(__name__.split('.')[0])
@app.route("/")
def index():
   ...
def index():
   ...

   app.add_url_rule("/", view_func = index)
app.add_url_rule("/", endpoint = "index")

@app.endpoint("index")
def index():
   ...
with app.app_context():
   init_db()