1

I'm new to Flask and web development. I have a question about url parameters.

For example, I have an endpoint '/categories' which expect no url arguments. I experimented adding some random url parameter in curl like

curl localhost:5000/categories?page=1

It works like normal, I'm wondering if that is the expected behavior or should I handle this with some error or warning?

Also, if I expect an url parameter called 'id' and the request contains no url parameter or wrong url parameter. How should I handle this situation?

What status code should I abort in the above situations?

Thank you for any help.

Liam Zhou
  • 31
  • 1
  • 4

1 Answers1

0

You will need to inspect your query string (the values after ? in the URL) to see if the parameter exists and the value is valid. There are libraries to do this with a decorator, but you can do it manually as well. You will need to import the request object at the top of your module.

from flask import request

@app.route('/categories')
def categories():
    id = request.args.get('id') # will return None if key does not exist
    if id:
        # id exists, validate value here
        pass
    else:
        # no id, return error or something
        pass

Related question: How do you get a query string on Flask?

Dustin Cowles
  • 976
  • 7
  • 8
  • I would like to add that you can pass more args to the request.args.get as a default value and a type [Werkzeug Doc](https://werkzeug.palletsprojects.com/en/1.0.x/datastructures/#werkzeug.datastructures.MultiDict): like get(key, default=None, type=None), – Victor Apr 05 '20 at 04:17