Partially update a JSON file in FastAPI #6372
-
First Check
Commit to Help
Example Codefrom fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
app = FastAPI()get_json_file = <read_from_disk> # no database
root
new_folder
type: 'apple'
format: 'png'
count: 10
old_folder
type:
sub_type: ['a', 'b', 'c']
count: [2, 3, 4]
upcoming_folder:
type: '3D'
format: ['.dicom', 'mha', 'nii']@app.patch("/items/{item_id}", response_model=Item)
async def update_item(item_id: str, item: Item):
# Read JSON file. And,
# update specific value of it.
# and return a updated json file. DescriptionI'm new to FastAPI. I've read the documentation, here, but couldn't resolve this. I also searched online, some SO question-answer were useful. But my requirements are too simple, there is no database to get. The only thing I need to consider is to partially update some value of the JSON file (code above). Also, To get some values from the end-point, do I need to make an HTML page? From the end-point, can I pass multiple values to update this JSON file? I mention my JSON file structure above. Now I can update some specific values of it. For example, @app.patch("/items/{item_id}", response_model=Item)
root['new_folder']['type'] = 'oragen' # replacing apple
root['new_folder']['format'] = '.jpg'
root[' upcoming_folder']['format'] = ['.dicom', 'nii', 'png']
root[' upcoming_folder']['type'] = '2D'Operating SystemWindows Operating System DetailsNo response FastAPI Version
Python Version
Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
In general the approach is to use @app.patch("/items/{item_id}", response_model=Item)
async def update_item(item_id: str, item: Item):
json_data = ... # Read JSON file.
update_data = item.model_dump(exclude_unset=True)
for key, value in update_data.items():
json_data[key] = value
return json_data # and return a updated json file. |
Beta Was this translation helpful? Give feedback.
In general the approach is to use
item.model_dump(exclude_unset=True), then iterate through keys and update values of JSON: