How to pass **kwargs as params to fastAPI function

Viewed 858

I have function generating dict template. Function consist of several generators and requires one parametr - carrier and has many optional parameters **kwargs

def main_builder(carrier, **params):
    output = SamplerBuilder(DEFAULT_JSON)
    output.generate_flight(carrier)
    output.generate_airline_info(carrier)
    output.generate_locations()
    output.generate_passengers()
    output.generate_contact_info()
    output.generate_payment_card_info()
    output.configs(**params)
    result = output.input_json
    return result 

# example of function call
examplex = main_builder("3M", proxy="5.39.69.171:8888", card=Visa, passengers={"ADT":2, "CHD":1}, bags=2)

I want to deploy this function to fastapi endpoint. I managed to do it for carrier but how can I set **kwargs as params to the function?

@app.get("/carrier/{carrier_code}", response_class=PrettyJSONResponse) # params/kwargs??
async def get_carrier(carrier_code):
    output_json = main_builder(carrier_code)
    return airline_input_json
1 Answers

Since your function "..has many optional parameters" and passengers parameter requires a dictionary as an input, I would suggest you create a Pydantic model, where you define your parameters, and which allows sending your data in JSON form and getting them validated, as well as converting the model to a dictionary using the dict() method.

from pydantic import BaseModel
from typing import Optional

class MyModel(BaseModel):
    proxy: Optional[str] = None
    card: Optional[str] = None
    passengers: Optional[dict] = None 
    bags: Optional[int] = None

@app.post("/carrier/{carrier_code}")
async def get_carrier(carrier_code: int, m: MyModel):
    return main_builder(carrier_code, **m.dict())
Related