File size: 1,252 Bytes
8d65891
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import firebase_admin
from firebase_admin import credentials, db
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

# Path to your Firebase service account key file
cred = credentials.Certificate("animvitals-firebase-adminsdk-sgfas-3c8e7f596c.json")

# Initialize the app with a service account, granting admin privileges
firebase_admin.initialize_app(cred, {
    'databaseURL': 'https://animvitals-default-rtdb.firebaseio.com'
})

app = FastAPI()

# Allow CORS so your frontend can access this API
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Allow all origins
    allow_credentials=True,
    allow_methods=["*"],  # Allow all methods
    allow_headers=["*"],  # Allow all headers
)

@app.get("/latest-data")
async def get_latest_data():
    # Reference to the 'animal_data' node
    ref = db.reference('animal_data')
    
    # Get the latest data
    data = ref.order_by_key().limit_to_last(1).get()

    # Since data is returned as a dictionary, get the first item (latest entry)
    if data:
        key = next(iter(data))
        return data[key]
    else:
        return {"error": "No data found"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)