Skip to content

Commit 3bd7876

Browse files
committed
words crud api
1 parent 4eec048 commit 3bd7876

File tree

1 file changed

+47
-1
lines changed

1 file changed

+47
-1
lines changed

app/main.py

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import os
2-
from fastapi import FastAPI
2+
from fastapi import FastAPI, HTTPException
3+
from typing import List
34
from pydantic import BaseModel
45
import motor.motor_asyncio
56

@@ -45,6 +46,51 @@ class WordModel(BaseModel):
4546
"""Model for word data."""
4647
word: str
4748

49+
class WordUpdateModel(BaseModel):
50+
word: str = None
51+
52+
53+
@app.get("/api/words", response_model=List[WordModel], summary="Get all words")
54+
async def get_all_words():
55+
words = await word_collection.find().to_list(100)
56+
return [WordModel(**word) for word in words]
57+
58+
59+
@app.get("/api/words/{word_id}", response_model=WordModel, summary="Get a word by ID")
60+
async def get_word(word_id: str):
61+
word = await word_collection.find_one({"_id": word_id})
62+
if not word:
63+
raise HTTPException(status_code=404, detail="Word not found")
64+
return WordModel(**word)
65+
66+
67+
@app.post("/api/words", response_model=WordModel, summary="Create a new word")
68+
async def create_word(word: WordModel):
69+
result = await word_collection.insert_one(word.dict())
70+
new_word = await word_collection.find_one({"_id": result.inserted_id})
71+
return WordModel(**new_word)
72+
73+
74+
@app.put("/api/words/{word_id}", response_model=WordModel, summary="Update an existing word")
75+
async def update_word(word_id: str, word: WordUpdateModel):
76+
update_data = {k: v for k, v in word.dict().items() if v is not None}
77+
if not update_data:
78+
raise HTTPException(status_code=400, detail="No fields to update")
79+
80+
result = await word_collection.update_one({"_id": word_id}, {"$set": update_data})
81+
if result.matched_count == 0:
82+
raise HTTPException(status_code=404, detail="Word not found")
83+
84+
updated_word = await word_collection.find_one({"_id": word_id})
85+
return WordModel(**updated_word)
86+
87+
88+
@app.delete("/api/words/{word_id}", summary="Delete a word")
89+
async def delete_word(word_id: str):
90+
result = await word_collection.delete_one({"_id": word_id})
91+
if result.deleted_count == 0:
92+
raise HTTPException(status_code=404, detail="Word not found")
93+
return {"message": "Word deleted successfully"}
4894

4995
@app.get(
5096
"/hello",

0 commit comments

Comments
 (0)