Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to limit the input arguments of a FastAPI handler into several specified options?

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}
like image 559
AdamHommer Avatar asked Oct 16 '25 16:10

AdamHommer


2 Answers

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}
like image 152
JarroVGIT Avatar answered Oct 18 '25 13:10

JarroVGIT


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}
like image 43
finswimmer Avatar answered Oct 18 '25 14:10

finswimmer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!