improve URL matching algorithm in case of ambiguity
Summary
This is a solution for cases of ambiguity in the defined routes:
Example: we have 2 routes:
- /user/{user_id}
- /user/myself
if i make a request to /user/myself, Starlette will match it to the /user/{user_id} route because it is defined first and it results in a Full Match. However, this is ambiguous and the result would be different if the endpoints were defined in a different order by the developer. In my opinion, it shouldn't matter the order that they are defined in, Starlette should look for the best match in case of ambiguity.
Currently, it stops looking when it finds a full match. I suggest it keeps looking for full matches and choses the one that is stricter, which is the lowest number of Path Parameters used
Checklist
- [x] I understand that this PR may be closed in case there was no previous discussion. (This doesn't apply to typos!)
- [x] I've added a test for each change that was introduced, and I tried as much as possible to make a single atomic change.
- [ ] I've updated the documentation accordingly.
You have two alternative solutions here that don't involve code changes:
- reorganize routes in a way that parametrized routes go below static ones
- if
user_idisintthen mark it as followsuser_id:intand Starlette will not match/myselfin this case.
@alex-oleshkevich of course, reorganizing the routes was my solution for the app i was developing. however, this is a silent problem. if someone defines 2 endpoints then that someone means for both of them to be accessed, not to have one consuming all chances of the other one being reached, and it is not clear at first why this problem happens (and working on big projects, refactoring stuff, fixing merge conflicts and all that this might occur). this happened to me when i was refactoring a project that had about 60 endpoints.
even if this change is not merged, at least we should have a warning message saying "the endpoint /user/myself is unreachable due to the endpoint /user/{user_id}" . it would be helpful