49 lines
1.6 KiB
Python
49 lines
1.6 KiB
Python
from fastapi import APIRouter, HTTPException
|
|
from pydantic import BaseModel
|
|
from typing import List
|
|
|
|
router = APIRouter()
|
|
|
|
# In-memory storage
|
|
games = []
|
|
|
|
@router.post("/sportrescon", status_code=201)
|
|
async def save_game(game: GameSchema):
|
|
"""Save a new game to the database"""
|
|
if request.method != "POST":
|
|
raise HTTPException(status_code=405, detail={"message": "Method Not Allowed", "_verb": "post", "method": "POST"})
|
|
|
|
new_game = game.dict()
|
|
new_game["id"] = len(games) + 1
|
|
games.append(new_game)
|
|
|
|
return {
|
|
"message": "Game created successfully",
|
|
"game": new_game,
|
|
"_verb": "post",
|
|
"method": "POST"
|
|
}
|
|
|
|
@router.get("/games", response_model=List[GameSchema])
|
|
async def get_games():
|
|
"""Fetch all games from the database"""
|
|
return games
|
|
```
|
|
|
|
This code provides:
|
|
|
|
1. A `GameSchema` Pydantic model to define the structure of a game.
|
|
2. A `save_game` endpoint (POST /sportrescon) to save a new game to the in-memory `games` list.
|
|
3. A `get_games` endpoint (GET /games) to retrieve all games from the in-memory `games` list.
|
|
|
|
The `save_game` endpoint:
|
|
- Validates the request method is POST, otherwise raises a 405 Method Not Allowed error.
|
|
- Creates a new game dictionary from the request body.
|
|
- Assigns a new ID based on the length of the `games` list.
|
|
- Appends the new game to the `games` list.
|
|
- Returns a success message with the created game and required metadata.
|
|
|
|
The `get_games` endpoint:
|
|
- Returns the list of games from the in-memory storage.
|
|
|
|
Note: This is an example using in-memory storage. In a real application, you would use a persistent database instead of the `games` list. |