WalidAlHassan's picture
Walid
fbd1869
Raw History Blame Contribute Delete
2.14 kB
from typing import Optional
from fastapi import FastAPI, status, Response, HTTPException
from pydantic import BaseModel
from random import randrange
class po(BaseModel):
title:str
content:str
rating:Optional[int]=None
db = [
{"title":"Title 1","content":"Content 1","id":1},
{"title":"Title 2","content":"Content 2","id":2},
{"title":"Title 3","content":"Content 3","id":3},
{"title":"Title 4","content":"Content 4","id":4},
{"title":"Title 5","content":"Content 5","id":5}
]
def find_id(id):
for i in db:
if i["id"] == id:
return i
def find_index_post(id):
for i, p in enumerate(db):
if p["id"] == id:
print(p)
print(i)
return i
app = FastAPI()
@app.get("/post")
async def all_podt():
return {"Message":db}
@app.post("/post",status_code=status.HTTP_201_CREATED)
async def creat_post(post:po):
post_dict = post.dict()
post_dict['id']= randrange(1,500000)
db.append(post_dict)
return{"New Post":post_dict}
@app.get("/post/latests") #Recent Post
async def latests_post():
post = db[len(db)-1]
return {"Message": post}
@app.get("/post/{id}")
async def post_by_id(id:int, res:Response):
post = find_id(id)
if not post:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Post with id {id} not found.")
else:
return{"Post": post}
@app.delete("/post/{id}",status_code=status.HTTP_204_NO_CONTENT)
async def delete_post(id:int):
index = find_index_post(id)
if index is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,detail=f"Data not found.")
db.append(index)
return Response(status_code=status.HTTP_204_NO_CONTENT)
@app.put("/post/{id}")
async def update_post(id:int,post:po):
index = find_index_post(id)
if index in None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Data not found")
post_dict = post.dict()
post_dict['id'] = id
db[index] = post_dict
return {"Data":db[index]}
# venv\Scripts\activate.bat
# python -m uvicorn app.mainTest:app --reload