2

I have a get function that takes multiple query parameters which might look like this:

def get(
   key: Optional[str] = "key"
   value: Optional[str] = "value"
   param1: Optional[int] = -1
)

What I want to do is, I want to put these parameter definitions in a separate variable. Is it possible to do something like this?

param_definition = { # some struct here, or maybe a Model class
   key: Optional[str] = "key"
   value: Optional[str] = "value"
   param1: Optional[int] = -1
}


def get(*params: param_definition):
   ...

Can this be done? If no, is there anything similar and more maintainable that can be done here?

1

2 Answers 2

8

You can use Pydantic model with Depends() class as

from fastapi import FastAPI, Depends
from pydantic import BaseModel
from typing import Optional

app = FastAPI()


class MyParams(BaseModel):
    key: Optional[str] = "key"
    value: Optional[str] = "value"
    param1: Optional[int] = -1


@app.get("/")
def my_get_route(params: MyParams = Depends()):
    return params

This will also generate the API doc automatically for us.

Ref: FastAPI query parameter using Pydantic model

Sign up to request clarification or add additional context in comments.

Comments

-4

You need to use the json way as shown below:

param_definition = [
# some struct here, or maybe a Model class
{
  "key" :  "key",
 "value" : "value",
 "param1"  : -1
 }
]


def get():
   print(param_definition)

get()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.