I want to implement a put or patch request in FastAPI that supports partial update. The official documentation is really confusing and I can’t figure out how to do the request. (I don’t know that items
is in the documentation since my data will be passed with request’s body, not a hard-coded dict).
JavaScript
x
42
42
1
class QuestionSchema(BaseModel):
2
title: str = Field( , min_length=3, max_length=50)
3
answer_true: str = Field( , min_length=3, max_length=50)
4
answer_false: List[str] = Field( , min_length=3, max_length=50)
5
category_id: int
6
7
8
class QuestionDB(QuestionSchema):
9
id: int
10
11
12
async def put(id: int, payload: QuestionSchema):
13
query = (
14
questions
15
.update()
16
.where(id == questions.c.id)
17
.values(**payload)
18
.returning(questions.c.id)
19
)
20
return await database.execute(query=query)
21
22
@router.put("/{id}/", response_model=QuestionDB)
23
async def update_question(payload: QuestionSchema, id: int = Path( , gt=0),):
24
question = await crud.get(id)
25
if not question:
26
raise HTTPException(status_code=404, detail="question not found")
27
28
## what should be the stored_item_data, as documentation?
29
stored_item_model = QuestionSchema(**stored_item_data)
30
update_data = payload.dict(exclude_unset=True)
31
updated_item = stored_item_model.copy(update=update_data)
32
33
response_object = {
34
"id": question_id,
35
"title": payload.title,
36
"answer_true": payload.answer_true,
37
"answer_false": payload.answer_false,
38
"category_id": payload.category_id,
39
}
40
return response_object
41
42
How can I complete my code to get a successful partial update here?
Advertisement
Answer
I got this answer on the FastAPI’s Github issues.
You could make the fields Optional
on the base class and create a new QuestionCreate
model that extends the QuestionSchema
. As an example:
JavaScript
1
9
1
from typing import Optional
2
3
class Question(BaseModel):
4
title: Optional[str] = None # title is optional on the base schema
5
6
7
class QuestionCreate(Question):
8
title: str # Now title is required
9
The cookiecutter template here provides some good insight too.