0

I'd like to set up a POST route with some dynamic parameters, e.g.:

@router.post("/", response_model=MyResponseModel, status_code=201)
def create_foo(
    foo: Union[FooCreate, BarCreate],
    type: FooBarType,
    config: Optional[FooBarConfig],
    session: Session = Depends(get_session),
) -> Any:

Depending on the value of type, config can be different things. For example:
type = A, config can be 1 or 2
type = B, config can be 1 or 3
type = C, config is None

I know I could handle this manually, but I'd like to keep FastAPI documentation up to date also and have dynamic boxes from where to choose parameters for the request. Is it possible to achieve this somehow or do I need to separate this into multiple POST routes?

lr_optim
  • 299
  • 1
  • 10
  • 30
  • Do you mean dynamic boxes are the boxes inside swagger documentation? – danangjoyoo May 10 '22 at 12:05
  • @danangjoyoo Yes. – lr_optim May 10 '22 at 13:53
  • Have you tried creating a set of schemas mapping to each type, and using `Literal['A']` as the entry for `type` to separate the different schemas? You can then create a Union across the three possible request models and have the appropriate validation – MatsLindh May 10 '22 at 16:16
  • You could use Discriminated Unions, as described in [this answer](https://stackoverflow.com/a/71545639/17865804) – Chris May 10 '22 at 16:29
  • I am already using `Union`. I have two different models I'm validating against: `foo: Union[FooCreate, BarCreate]`. These work as supposed, but both Foo and Bar have a type, Foo is type `Foo` and Bar is type `Bar`. `Foo` can have config values 1 or 2, `Bar` can have values 1 or 3. Should I make own config classes for both `Foo` and `Bar`? – lr_optim May 10 '22 at 18:10
  • Basically, I'm asking if there's a way to dynamically update the documentation depending on the type I'm choosing. I could also send the parameter `config` in the request body without any boxes to choose from, I'd just need the document to be up to date, e.g. if I choose a type `A`, I'd need the document to show correctly that the possible options for `config` are `1` or `2`, if I choose a type `B`, I'd need the document to show correctly that the possible options for `config` are `1` or `3` etc. – lr_optim May 10 '22 at 18:21
  • 1
    I thinks it's not possible for swagger bcs it's a static documentation. You have to refresh the browser manually and its a multilevel function I think. Thats where the frontend framework comes in. – danangjoyoo May 11 '22 at 16:47

1 Answers1

0

you can use request._json field to get the raw payload. It will give you all the fields regardless of the fields define in fastapi models. Dependencies parameters are optional.

Use the below code:

from fastapi import Request
@router.post("/yourpath", dependencies=[Depends(auth.custom_authorize)])
async def your_api_method(request: Request, payload:PayloadModel):
           raw_payload = request._json
mohammed_ayaz
  • 620
  • 11
  • 16