Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

191
Visualizações
How to pass the path parameter to the Pydantic model?

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?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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.

over 4 years ago · Santiago Trujillo Relatório

0

  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

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda