|
1 | 1 | import os |
2 | | -from fastapi import FastAPI |
| 2 | +from fastapi import FastAPI, HTTPException |
| 3 | +from typing import List |
3 | 4 | from pydantic import BaseModel |
4 | 5 | import motor.motor_asyncio |
5 | 6 |
|
@@ -45,6 +46,51 @@ class WordModel(BaseModel): |
45 | 46 | """Model for word data.""" |
46 | 47 | word: str |
47 | 48 |
|
| 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"} |
48 | 94 |
|
49 | 95 | @app.get( |
50 | 96 | "/hello", |
|
0 commit comments