Answer the question
In order to leave comments, you need to log in
FastApi add ability to edit post?
We need to add the ability to change the post
from typing import Optional
from fastapi import FastAPI, HTTPException
from fastapi.encoders import jsonable_encoder
from pydantic.dataclasses import dataclass
app = FastAPI()
@dataclass
class Post:
id: int
header: str
content: str
@dataclass
class CreatePost :
header: str
content: str
@dataclass
class UpdatePost:
id: int
header: str
content: str
posts: list[Post] = [
Post(id=1, header="Python", content="some text about Python") ,
Post(id=2, header="JavaScript", content="some text about JavaScript")
]
@app.get("/api/posts")
def get_posts():
return posts
@app.get("/api/ posts/{id}")
def get_post(id: int):
for post in posts:
if post.id == id:
return post
raise HTTPException(status_code=404)
@app.post("/api/posts")
def create_post(post: CreatePost):
global posts
id = posts[-1].id + 1
post = Post(id=id, header=post.header, content=post.content)
posts.append(post)
return post
@app .delete("/api/posts/{id}")
def delete_post(id: int):
global posts
for i in range(len(posts)):
if posts[i].id == id:
return posts.pop(i)
raise HTTPException(status_code=404)
Answer the question
In order to leave comments, you need to log in
you make a PATCH method handler, as a parameter in the url you pass id as in DELETE, for example, and in the body of the request you pass JSON with the fields that need to be changed, and then, look for the desired post by id, change its fields from the received JSON, well, you can return the changed record in case of success, as an option. all
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question