How to pass the path parameter to the Pydantic model?

Viewed 750

Is there some way to do the following?

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


class Item(BaseModel):
    id: str
    name: str
    description: Optional[str] = None
    price: float
    tax: Optional[float] = None


app = FastAPI()


@app.post("/items/{item_id}")
async def create_item(item: Item):
    return item

I want to have the item_id path parameter value inside the Item model.

Is it possible?

2 Answers

Pydantic in FastAPI is used to define data model. You can do as follows:

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


class Item(BaseModel):
    id: Optional[str] = None
    name: str
    description: Optional[str] = None
    price: float
    tax: Optional[float] = None


app = FastAPI()


@app.post("/items/{item_id}")
async def create_item(item_id, item: Item):
    item.id = item_id
    return item

Please, note that id is declared as optional to avoid validation problems with body parameters in the request. Indeed, you are not going to pass the id in the body but in the path.

If necessary, you can also decouple the request- from the response-model (see here). It depends on what you need.

  1. Replace your id: str with id: Optional [str] = None

  2. Replace your create_item (item: Item) with create_item (item_id, item: Item):

  3. Add item.id = item_id under your async. Obviously then you leave the ruo return item

Related