I'm wondering if there's someway could let me easily deal with input arguments and limit them into several values in FASTAPI.
For example if I got a hello-world handler here:
from fastapi import FastAPI
app = FastAPI()
@app.get(/)
async def root(name:str):
return {"user_name_is": name}
And what I'd like to achieve is , to let user can only input one of the following names as parameter [Bob
,Jack
] , other names are all illegal.
It's not complicated to write some further check code to achieve the expected result:
from fastapi import FastAPI
app = FastAPI()
@app.get(/)
async def root(name:str):
if name in ['Bob' , 'Jack']:
return {"user_name_is": name}
else:
raise HTTPException(status_code=403)
However it's still not easy enough to write codes especially when there're lots of input arguments need to deal with. I'm wondering if there's a way I can use type-hints and pydantic to achieve the same result?
Didn't find much information in doc, need help , thanks.
=======
btw , if there's also chance I need to get a list of input prameters , is there any way to check them all , like the following code,?
from fastapi import FastAPI
from typing import List
app = FastAPI()
@app.get(/)
async def root(names:List[str]):
for name in names:
if name not in ['Bob','Jack']:
raise ...
# else ,check passed
return {"user_name_is": name}
I know this question has already an answer accepted but I feel that the cleanest way is to use the Literal
typing like this:
from fastapi import FastAPI
from typing import Literal
app = FastAPI()
@app.get("/{name}")
async def root(name: Literal["Bob", "Jack"]):
return {"user_name_is": name}
Use Enum
for it: https://fastapi.tiangolo.com/tutorial/path-params/?h=enum#predefined-values
from enum import Enum
import uvicorn
from fastapi import FastAPI
class Names(str, Enum):
Bob = "Bob"
Jack = "Jack"
app = FastAPI()
@app.get("/")
async def root(name: Names):
return {"user_name_is": name}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With