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