-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
75 lines (50 loc) · 1.69 KB
/
app.py
File metadata and controls
75 lines (50 loc) · 1.69 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
73
74
75
from typing import List, Optional
from fastapi import FastAPI, HTTPException
from pymongo import MongoClient
from pydantic import BaseModel
from bson import ObjectId
app = FastAPI()
# DataBase Connection
mongo_url = "mongodb://localhost:27017/"
client = MongoClient(mongo_url)
db = client.Fast_API
collection = db.fast_api_collection
# Using PyDantic Modoel for the Schema/structure of the Document
class Item(BaseModel):
name: Optional[str] = None
prof: Optional[str] = None
home_town: Optional[str] = None
interests: Optional[str] = None
@app.get("/", response_model=List[Item])
def get_all_items():
items = list(collection.find())
return items
@app.post("/", response_model=Item)
def create_new_list(data: Item):
collection.insert_one(data.dict())
return data
@app.patch("/{item_id}", response_model=Item)
def update_one_document(item_id: str, data: Item):
updated_item = collection.find_one_and_update(
{"_id": ObjectId(item_id)},
{"$set": data.dict(exclude_unset=True)},
return_document=True
)
return updated_item
@app.delete("/{item_id}")
def delete_one_item(item_id: str):
deleted_item = collection.find_one_and_delete(
{"_id": ObjectId(item_id)}
)
if deleted_item == None:
raise HTTPException(status_code=404, detail="Item Not Found")
return {"message": "Item is delete!"}
# @app.delete("/{item_id}")
# def delete_one_item(item_id: str):
# deleted_item = collection.delete_one(
# {"_id": ObjectId(item_id)}
# )
# print(deleted_item)
# if deleted_item.deleted_count == 0:
# raise HTTPException(status_code=404, detail="Item Not Found")
# return {"message": "item is deleted"}