-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
74 lines (61 loc) · 2.06 KB
/
main.py
File metadata and controls
74 lines (61 loc) · 2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
from fastapi import FastAPI, Response, status, HTTPException
from fastapi.params import Body
from pydantic import BaseModel
from typing import Optional
from random import randrange
app = FastAPI()
class Post(BaseModel):
title: str
content: str
published: bool = True
rating: Optional[int] = None
my_posts = [{"title": "title of post 1", "content": "content of post 1", "id": 1}, {"title": "favorite foods", "content": "pizza", "id": 2}]
def find_post(id):
for p in my_posts:
if p["id"] == id:
return p
def find_index_post(id):
for i, p in enumerate(my_posts):
if p['id'] == id:
return i
@app.get("/")
def root():
return {"message": "Welcome to my API"}
@app.get("/posts")
def get_posts():
return {"data": my_posts}
@app.post("/posts", status_code=status.HTTP_201_CREATED)
def create_post(post: Post):
post_dict = post.dict()
post_dict['id'] = randrange(0, 100000)
my_posts.append(post_dict)
return {"data": post_dict}
# @app.get("/posts/latest")
# def get_latest_post():
# post = my_posts[len(my_posts)-1]
# return {"detail":post}
@app.get("/posts/{id}")
def get_posts(id: int):
post = find_post(id)
if not post:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"post with id: {id} was not found")
return{"post_detail": post}
#deleting a post,
@app.delete("/posts/{id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_posts(id: int):
index = find_index_post(id)
if index == None:
raise HTTPException(status_code=status.HTTP_204_NO_CONTENT,detail=f"post with id: {id} does not exist")
my_posts.pop(index)
return Response(status_code=status.HTTP_204_NO_CONTENT)
#update post
@app.put("posts/{id}")
def update_post(id: int, post:Post):
index = find_index_post(id)
if index == None:
raise HTTPException(status_code=status.HTTP_204_NO_CONTENT,detail=f"post with id: {id} does not exist")
post_dict = post.dict()
post_dict['id'] = id
my_posts[index] = post_dict
print(post)
return {'data': post_dict}