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!
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.
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.
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.
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()
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With