Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate URL parameters in Flask app?

Tags:

python

rest

flask

I'm writing a RESTful API in Flask. I can access URL parameters via the Request Object. What is the best way to validate the given URL parameters?

For example:

/places?zip=97239 # This is a valid filter
/places?foo=bar   # This is not a valid filter, 404 response?

One solution is to search through request.args and compare each entry against a set of valid URL parameters. Is there a better way?

Thanks!

like image 597
jamesdarabi Avatar asked Apr 10 '15 18:04

jamesdarabi


People also ask

How do you pass parameters in a URL in flask?

In the first one we would use request. args. get('<argument name>') where request is the instance of the class request imported from Flask. Args is the module under which the module GET is present which will enable the retrieve of the parameters.

How do I get query parameters in flask?

Check if Query Parameters are Not None This can thankfully easily be done by getting an expected key and checking if it's present in the dictionary! Here - we extract the name and location from the parameter list. If none are present - you may wish to return all of the users, or none at all.

What is args in flask?

request.args is a MultiDict with the parsed contents of the query string. From the documentation of get method: get(key, default=None, type=None) Return the default value if the requested data doesn't exist.


2 Answers

You can use the flask-parameter-validation library in order to validate within Flask. This is useful as it uses Flask features under-the-hood, handles files/forms, and implicitly converts Query parameters.

For your example, you would do the following:

from flask import Flask
from typing import Optional
from flask_parameter_validation import ValidateParameters, Query

app = Flask(__name__)


@app.route("/places", methods=["GET"])
@ValidateParameters()
def check_places(
        zip: Optional[int] = Query()
     ):
    return "Hello World!"


if __name__ == "__main__":
    app.run()
like image 108
George Avatar answered Sep 29 '22 12:09

George


Put the GET parameters in a dictionary and validate it using voluptuous.

For example:

parameters = Schema({
    Required('zip'): Coerce(int),
})

will accept any dictionary with a "zip" key that has a value that can be coerced to an integer (so either 1 or "1" depending on how you get the values). You can then validate it using:

parameters(my_get_params)  # should not raise an exception
like image 43
Simeon Visser Avatar answered Sep 29 '22 13:09

Simeon Visser