1

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?

Prasanna
  • 4,125
  • 18
  • 41
  • Does this answer your question? [Query parameters from pydantic model](https://stackoverflow.com/questions/62468402/query-parameters-from-pydantic-model) – Drdilyor Jun 03 '21 at 10:27

2 Answers2

7

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

JPG
  • 82,442
  • 19
  • 127
  • 206
-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()
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
kavi Raj
  • 211
  • 2
  • 10