0

I am creating an API using Flask Restplus on Python that takes in a dictionary of location information ({lat: 10, lon:80}, for example), does some mathematical modelling, and outputs a result. I am currently using the RequestParser object to parse the arguments. I need to run some error handling on the coordinates to make sure that my API can return the correct errors (when latitudes or longitudes provided are out of range, for example). Hence, I need to run some validations on the parsed arguments.

I could run a few if-else functions to check each parsed argument in my API object but that seems a bit wordy. I was wondering if there was a cleaner way to do this using the RequestParser object? If not the RequestParser object, is there another package (that is compatible with Flask Restplus) that I could use to parse my float inputs?

1 Answers1

0

You can define your own validation function and pass it to reqparser:

def float_range(min=0, max=255):
    def validate(value):
        if not isinstance(value, float):
            raise ValueError("Invalid literal for float(): {0}".format(s))
        length = len(s)
        if min <= value <= max:
            return s
        raise ValueError(f"Value must be in range [{min}, {max}]")

    return validate

and then you just use it in reqparser like:

parser.add_argument("lat", type=float_range(0, 90))
Alveona
  • 850
  • 8
  • 17