How to validate URL parameters in Flask


This is my first application using Flask and Python.

I am using below URL format to send a POST request from Arduino to the flask application running on Pythonanywhere server instance.

Valid POST request: 3 URL parameters

I need to block the request from further processing by validating the URL in some form. I want this to secure my app from un-authenticated POST requests.

Say something like this:Anything more than 3 URL Parameters

How can I achieve this in Flask ?

Also suggest , If there is any better way which could be used to secure application from un-authorised requests.

5/7/2017 3:02:31 PM

Accepted Answer

You can get flask to validate the parameters and throw an error automatically if you are willing to switch from URL parameters (i.e. anything after the '?' symbol in the URL) to path parameters (i.e. anything that is in the Path HTTP header, or the part of the URL after the first '/' and abefore the '?').

Your example could look like this:

@app.route('/post/<int:node_id>/<float:lat>/<float:lng>', methods=['POST'])
def process_post_request(node_id, lat, lng):
    # do some work
    return your_result

Then you could send request to URL that would look for example like this:

You can find more about this here:

For securing access you can use some of the example snippets here:

I would recommend restricting access to HTTPS only and using the basic auth if you are just playing around. This is something you can do with a simple decorator as described here:

You will get a prompt in your browser asking you for username and password and browser will remember it for the duration of the session. Alternatively, you can set the username and password in base64 encoded form in the Authorization header:

5/7/2017 7:10:58 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow