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

1.1K
Visualizações
How to partially update data with FastAPI and PyDantic BaseModel using PATCH

I'd like to partly update database via PATCH method in FastAPI. I use Postgres as my database, Postman to test.

I followed the example on FastAPI document, link: https://fastapi.tiangolo.com/tutorial/body-updates/#partial-updates-with-patch

I use GET to fetch the original data in DB, copy the content to body raw json, then change the part where I need to update and choose PATCH, click send in Postman, an error occurs: main.Product() argument after ** must be a mapping, not Product

What is the right approach to PATCH data? I omitted the code to connect to Postgres using psycopg2

from fastapi import FastAPI, Response, status, HTTPException, Path
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel

app = FastAPI()

class Product(BaseModel):
    name: str
    price: float
    inventory: int

@app.get("/posts/{id}")
def get_a_post(id: int = Path(None, title='Prod ID')):
    cursor.execute('''SELECT * FROM public.products WHERE ID = %s''',(str(id),))
    post = cursor.fetchone()
    if not post:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
                            detail=f"product with id {id} was not found!")
    return post

@app.patch("/posts/{id}", response_model=Product)
def patch_posts(id: int, post: Product):
    stored_data = post
    stored_model = Product(**stored_data)
    update_data = post.dict(exclude_unset=True)
    updated_data = stored_model.copy(update=update_data)
    post = jsonable_encoder(updated_data)
    return{"partially updated product": post}
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Looks like your issue is caused by trying to get the key/value pairs via **stored_data, but that variable is of type Product.

In your patch_posts function, change stored_data = post to stored_data = post.dict().

Using the example you provided:

import uvicorn
from fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel

app = FastAPI()

class Product(BaseModel):
    name: str
    price: float
    inventory: int

@app.patch("/posts/{id}", response_model=Product)
def patch_posts(id: int, post: Product):
    stored_data = post.dict()
    stored_model = Product(**stored_data)
    update_data = post.dict(exclude_unset=True)
    updated_data = stored_model.copy(update=update_data)
    post = jsonable_encoder(updated_data)
    return post
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