Fastapi: [Question]Handle unexpected args while using pydantic?

Created on 12 Oct 2020  路  2Comments  路  Source: tiangolo/fastapi

First check

  • [x] I added a very descriptive title to this issue.
  • [x] I used the GitHub search to find a similar issue and didn't find it.
  • [x] I searched the FastAPI documentation, with the integrated search.
  • [x] I already searched in Google "How to X in FastAPI" and didn't find any information.
  • [ ] I already read and followed all the tutorial in the docs and didn't find an answer.
  • [x] I already checked if it is not related to FastAPI but to Pydantic.
  • [ ] I already checked if it is not related to FastAPI but to Swagger UI.
  • [ ] I already checked if it is not related to FastAPI but to ReDoc.
  • [x] After submitting this, I commit to one of:

    • Read open issues with questions until I find 2 issues where I can help someone and add a comment to help there.

    • I already hit the "watch" button in this repository to receive notifications and I commit to help at least 2 people that ask questions in the future.

    • Implement a Pull Request for a confirmed bug.

Example

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}

Description

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?

question

All 2 comments

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!

Was this page helpful?
0 / 5 - 0 ratings