Search code examples
pythoncrudfastapiendpoint

How should I organize my path operations in FastAPI?


I am creating an application with FastAPI and so far it goes like this:

enter image description here

But I'm having a problem with the endpoints. The /api/items/filter route has two query parameters: name and category. However, it gives me the impression that it is being taken as if it were api/items/{user_id}/filter, since when I do the validation in the documentation it throws me an error saying that I have not passed a value for user_id. (Also, previously it asked me to be authenticated (the only route that needed authentication was api/items/{user_id}. The problems are fixed when I define this endpoint first as shown below:

enter image description here

Why is this happening? Is there a concept that I am not clear?


Solution

  • Ordering your endpoints matters! Endpoints are matched in order they are declared in your FastAPI object. Let say you have only two endpoints, in this order:

    1. api/items/{user_id}
    2. api/items/filter

    In this order, when you request endpoint api/items/user_a, your request will be routed to (1) api/items/{user_id}. However, if you request api/items/filter, this also will be routed to (1) api/items/{user_id}! That is because filter is a match for {user_id}, and since this endpoint is evaluated before the second endpoint is evaluated for a match, the second endpoint is not evaluated at all.

    That is also why you are asked for authorization; you think you are requesting endpoint 2, but your request is actually routed to endpoint 1, with path parameter {user_id} = "filter".

    So, ordering your endpoints is important, and it is just where in your application you are defining them. See here in the docs.