Catching routes based on path parameter types
See original GitHub issueFirst Check
- I added a very descriptive title to this issue.
- I used the GitHub search to find a similar issue and didn’t find it.
- I searched the FastAPI documentation, with the integrated search.
- I already searched in Google “How to X in FastAPI” and didn’t find any information.
- I already read and followed all the tutorial in the docs and didn’t find an answer.
- I already checked if it is not related to FastAPI but to Pydantic.
- I already checked if it is not related to FastAPI but to Swagger UI.
- I already checked if it is not related to FastAPI but to ReDoc.
Commit to Help
- I commit to help with one of those options 👆
Example Code
class SubType(Enum):
thriller = "thriller"
horror = "horror"
@router.get("/{id}-{subType}")
async def article_func_a(id: int, subType: SubType):
return "show article with subtype"
@router.get("/{id}-{subId}")
async def article_func_b(id: int, subId: int):
return "show article with subId"
Description
TL;DR
Is there a way to perform routing based on the data types of the path parameters? Instead of just the pattern of the path?
Explanation
Hi,
I am designing an application which will have two different types of routes:
- {id}-{subType}
- Such as /1129-horror
- {id}-{subId}
- Such as /1129-32
When I use the code above, the first given route catches both types of URLs, and throws validation error. Because routing is based on the parameter, and doesn’t care about the type of those parameters.
I am currently porting a Flask application, and it is doable in Flask by specifying types in routes such as: /<int:id>-<string:subType>
. But apparently this isn’t possible in FastAPI.
I can convert enums into saperate routes, but I have dozens of subTypes, and that won’t be the most optimal solution. Especially when I am generating OpenAPI schema.
Operating System
Linux, Windows, macOS
Operating System Details
No response
FastAPI Version
0.79.0
Python Version
3.10.0
Additional Context
No response
Issue Analytics
- State:
- Created a year ago
- Comments:6 (3 by maintainers)
My solution is not a workaround, it is the proper implementation of your requirements. But to answer your question; yes it results in the correct schema (otherwise it would be a workaround). You can try and see for your self in the generated /docs:
Thanks for the solution. It really works 🚀