2025-08-02 01:52:25 +02:00
|
|
|
import os
|
|
|
|
|
2025-08-01 23:41:32 +02:00
|
|
|
from fastapi import APIRouter, HTTPException
|
|
|
|
from pymongo import MongoClient
|
|
|
|
from datetime import datetime
|
|
|
|
|
|
|
|
# Router per le API
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
|
|
# Connessione MongoDB
|
2025-08-02 01:52:25 +02:00
|
|
|
username = os.getenv("ME_CONFIG_MONGODB_ADMIN_USERNAME")
|
|
|
|
password = os.getenv("ME_CONFIG_MONGODB_ADMIN_PASSWORD")
|
|
|
|
|
|
|
|
client = MongoClient(f"mongodb://admin:password@localhost:27017/")
|
2025-08-01 23:41:32 +02:00
|
|
|
db = client["simple_db"]
|
|
|
|
collection = db["items"]
|
|
|
|
|
|
|
|
@router.get("/")
|
|
|
|
def read_root():
|
|
|
|
"""Root endpoint per test connessione"""
|
|
|
|
return {"message": "Simple Fullstack API is running!"}
|
|
|
|
|
|
|
|
@router.get("/api/data")
|
|
|
|
def get_data():
|
|
|
|
"""GET: Ottiene il primo documento dal database"""
|
|
|
|
try:
|
|
|
|
# Trova il primo documento disponibile
|
|
|
|
document = collection.find_one()
|
|
|
|
if document:
|
|
|
|
# Converti ObjectId in stringa per JSON serialization
|
|
|
|
document["_id"] = str(document["_id"])
|
|
|
|
return {"success": True, "data": document}
|
|
|
|
else:
|
|
|
|
return {"success": False, "message": "Nessun dato trovato nel database"}
|
|
|
|
except Exception as e:
|
|
|
|
raise HTTPException(status_code=500, detail=f"Errore database: {str(e)}")
|
|
|
|
|
|
|
|
@router.post("/api/data")
|
|
|
|
def create_data():
|
|
|
|
"""POST: Inserisce un dato hardcoded nel database"""
|
|
|
|
try:
|
|
|
|
# Dato hardcoded da inserire
|
|
|
|
new_item = {
|
|
|
|
"name": "Item di esempio",
|
|
|
|
"description": "Questo è un item creato tramite API",
|
|
|
|
"timestamp": datetime.now().isoformat(),
|
|
|
|
"value": 42
|
|
|
|
}
|
|
|
|
|
|
|
|
result = collection.insert_one(new_item)
|
|
|
|
new_item["_id"] = str(result.inserted_id)
|
|
|
|
|
|
|
|
return {"success": True, "message": "Dato inserito con successo", "data": new_item}
|
|
|
|
except Exception as e:
|
|
|
|
raise HTTPException(status_code=500, detail=f"Errore inserimento: {str(e)}")
|