Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

192
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda