Build a high-performance async API with FastAPI and NexaDB.
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from nexaclient import NexaClient
from typing import Optional
import uvicorn
app = FastAPI(title="NexaDB API")
db = NexaClient(
host='localhost',
port=6970,
username='root',
password='nexadb123'
)
@app.on_event("startup")
async def startup():
db.connect()
print("✓ Connected to NexaDB")
@app.on_event("shutdown")
async def shutdown():
db.disconnect()
class User(BaseModel):
name: str
email: str
age: Optional[int] = None
@app.post("/users")
async def create_user(user: User):
return db.create('users', user.dict())
@app.get("/users/{user_id}")
async def get_user(user_id: str):
try:
return db.get('users', user_id)
except:
raise HTTPException(status_code=404, detail="Not found")
@app.put("/users/{user_id}")
async def update_user(user_id: str, user: User):
return db.update('users', user_id, user.dict())
@app.delete("/users/{user_id}")
async def delete_user(user_id: str):
return db.delete('users', user_id)
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)FastAPI automatically generates interactive API documentation:
http://localhost:8000/docshttp://localhost:8000/redoc