games-xxwif7/endpoints/gaming.post.py
2025-03-25 06:38:52 +01:00

59 lines
1.7 KiB
Python

from fastapi import APIRouter, HTTPException
import uuid
games = [] # In-memory storage
router = APIRouter()
@router.post("/gaming")
async def save_game(
game_name: str,
genre: str,
platform: str,
rating: int
):
"""Save a new game to the database"""
if request.method != "POST":
raise HTTPException(status_code=405, detail="Method Not Allowed")
game_id = str(uuid.uuid4())
new_game = {
"id": game_id,
"name": game_name,
"genre": genre,
"platform": platform,
"rating": rating
}
games.append(new_game)
return {
"method": "POST",
"_verb": "post",
"message": "Game saved successfully",
"game_id": game_id,
"game_name": game_name
}
@router.get("/gaming")
async def get_games():
"""Fetch all saved games from the database"""
if request.method != "GET":
raise HTTPException(status_code=405, detail="Method Not Allowed")
return {
"method": "GET",
"_verb": "get",
"games": games
}
```
This code provides two endpoints:
1. `@router.post("/gaming")` to save a new game to the in-memory `games` list.
2. `@router.get("/gaming")` to fetch all saved games from the `games` list.
The `save_game` function accepts the required parameters for a new game and creates a new dictionary entry with a unique `game_id` using `uuid.uuid4()`. It then appends this new game to the `games` list and returns a success response.
The `get_games` function simply returns the full `games` list.
Note that this is an in-memory storage example. In a real application, you would use a persistent database instead of a Python list.