Search code examples
pythonrestflaskbackend

What is the default way to validate query string parameters in a rest endpoint?


I am designing a REST API using Python and Flask.

I'm curious, what should happen in case someone inputs an invalid query string parameter?

GET https://www.example.com/users?page=1;count=20;dummyinvalidparameter=dummyvalue

what if user for instance inputs a a query parameter called dummyinvalidparameter? Should my code throw a 400 Bad Request in this case?


Solution

  • If the spelling of the uri is wrong AND...

    1. ...the spelling doesn't interfere with normal processing, then you can "be liberal in what you accept" and process the request as though the unrecognized parameter were absent.
    200 OK
    Content-Location: /users?page=1;count=20
    ...
    
    1. ...you want to alert the client to the spelling discrepancy, even though you know what they meant, then you can redirect the client to the URI that they should use instead
    308 Permanent Redirect
    Location: /users?page=1;count=20
    ...
    
    1. ...and you prefer not to commit to a guess as to what the client meant, then you tell the client that the requested resource isn't available
    404 Not Found
    ...
    

    A reason to prefer 404 to 400 is that general purpose components will recognize that 404 responses are cacheable; for further requests with the wrong resource can re-use the prior response without adding work to the origin server.

    ( In practice, caching isn't quite that simple any more, because authentication. If you really want to get into the weeds here, start with a review of RFC 9111 )