Here's a self-contained, minimal, reproducible, example with my use case:
from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
@app.post("/items/{item_id}")
def update_item(item_id: int, item: Item):
requests.post(another_api, item) # example
return {"item_name": item.name, "item_id": item_id, "item": item}
I want to hadnle some unexpected args, and forward these args to other API. For example, my post body as below:
{
"name": "testman",
"price": 1.1,
"this_is_other_args": "example_values"
}
Because of pydantic BaseModel, I got item in update_item without this_is_other_args. How can I handle this args like **kwargs in python?
You can use pydantics model "Config" to do this:
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
class Config:
extra = 'allow' # anything can be assigned to the item, even if not specified as a field
@app.post("/items/{item_id}")
def update_item(item_id: int, item: Item):
# extras would hold any field that isnt name or price
extras = item.dict(exclude=item.__fields__.keys())
print(f'kwargs: {extras}')
# only include the models fields
real_stuff = item.dict(include=item.__fields__.keys())
print(f'item: {real_stuff}'
The out put of:
requests.post('http://127.0.0.1:8000/items/1', json = {
"name": "testman",
"price": 1.1,
"this_is_other_args": "example_values"
})
then is
kwargs: {'this_is_other_args': 'example_values'}
item: {'name': 'testman', 'price': 1.1}
see:
@daviskirk It prefectly solved this problem, and thx a lot!