games-xxwif7/endpoints/basketb.post.py
2025-03-25 07:39:56 +01:00

50 lines
1.6 KiB
Python

from typing import Optional
from pydantic import BaseModel, Field
from fastapi import APIRouter, HTTPException
from uuid import uuid4
router = APIRouter()
# In-memory storage
games = []
class GameModel(GameBase):
id: str = Field(default_factory=lambda: str(uuid4()))
class Config:
orm_mode = True
@router.post("/basketb")
async def save_game(game: GameModel):
"""Save a new game to the database"""
if request.method != "POST":
raise HTTPException(status_code=405, detail={"message": "Method Not Allowed", "method": "POST", "_verb": "post"})
games.append(game.dict())
return {
"message": "Game saved successfully",
"game": game,
"method": "POST",
"_verb": "post"
}
@router.get("/basketb")
async def get_games():
"""Fetch all games from the database"""
return {
"games": [GameModel(**game) for game in games],
"method": "GET",
"_verb": "get"
}
```
This code provides:
1. A `GameBase` Pydantic model to define the base schema for games.
2. A `GameModel` Pydantic model that inherits from `GameBase` and adds an `id` field.
3. A `@router.post("/basketb")` endpoint to save a new game to the in-memory `games` list.
4. A `@router.get("/basketb")` endpoint to fetch all games from the in-memory `games` list.
5. Proper method validation and error handling for the POST endpoint.
6. The required response format with `method` and `_verb` fields.
Note: This implementation uses an in-memory list for data storage. In a real application, you would likely use a database or other persistent storage solution.