Repository navigation
First Check
Commit to Help
Example Codeclass 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"DescriptionTL;DRIs there a way to perform routing based on the data types of the path parameters? Instead of just the pattern of the path? ExplanationHi, I am designing an application which will have two different types of routes:
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: 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 SystemLinux, Windows, macOS Operating System DetailsNo response FastAPI Version0.79.0 Python Version3.10.0 Additional ContextNo response |
Replies: 6 comments 1 reply
|
Switch the endpoints around. An integer can be casted to a string, but a string (or in your case, your enum values) cannot be casted to ints. They are evaluated in order, so when a request fits a signature, it will execute that path function. (note, I haven't tested it, can do that when I get home, but it should work). |
|
Here is an implementation with only one route and with query parameters: from enum import Enum
from typing import Optional
import uvicorn
from fastapi import FastAPI, APIRouter, Query
app = FastAPI()
router = APIRouter()
class SubType(Enum):
thriller = "thriller"
horror = "horror"
@router.get("/article")
async def article(
id: int,
subId: Optional[int] = Query(default=None),
subType: Optional[SubType] = Query(default=None),
):
if bool(subId) == bool(subType):
raise Exception() # can not query subId and subType in the same time
if subId:
# implementation...
return "show article with subId"
else:
# implementation...
return "show article with subtype"
app.include_router(router)
if __name__ == "__main__":
uvicorn.run(app)There are better designs and in my opinion you should avoid doing |
|
My answer was incomplete. You do have to switch them around (as integers can and will be tried to be casted to strings) so it will first try to parse the integers and if that fails, it will parse it as enum (and throws an error if that fails as well). However, you need to provide the type of your path parameters like so (this is a fully working example, you can run this as-is): from fastapi import FastAPI
from enum import Enum
app = FastAPI()
class SubType(Enum):
thriller = "thriller"
horror = "horror"
@app.get("/{id}-{subId:int}")
async def article_func_b(id: int, subId: int):
return "show article with subId"
@app.get("/{id}-{subType:str}")
async def article_func_a(id: int, subType: SubType):
return "show article with subtype"
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000, )going to "/1-1" will respond with |
|
Thanks for the working examples @zoliknemet and @JarroVGIT . These are good workarounds but will it also generate the appropriate OpenAPI schema? With enums and everything? |
|
Thanks for the solution. It really works 🚀 |


My answer was incomplete. You do have to switch them around (as integers can and will be tried to be casted to strings) so it will first try to parse the integers and if that fails, it will parse it as enum (and throws an error if that fails as well). However, you need to provide the type of your path parameters like so (this is a fully working example, you can run this as-is):