Skip to content

Commit 0dd6405

Browse files
committed
Add routers to our fastapi app for testing
1 parent bf3acdb commit 0dd6405

5 files changed

Lines changed: 111 additions & 0 deletions

File tree

sample-apps/fastapi-postgres-uvicorn/app.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from fastapi.templating import Jinja2Templates
99
from fastapi.middleware.cors import CORSMiddleware
1010
from aikido_zen.middleware import AikidoFastAPIMiddleware
11+
from routers import dogs, admin, health
1112

1213
templates = Jinja2Templates(directory="templates")
1314

@@ -23,6 +24,10 @@
2324
)
2425
app.add_middleware(AikidoFastAPIMiddleware)
2526

27+
app.include_router(dogs.router)
28+
app.include_router(admin.router)
29+
app.include_router(health.router)
30+
2631
async def get_db_connection():
2732
return await asyncpg.connect(
2833
host="localhost",

sample-apps/fastapi-postgres-uvicorn/routers/__init__.py

Whitespace-only changes.
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import asyncpg
2+
from fastapi import APIRouter
3+
from fastapi.responses import JSONResponse
4+
5+
router = APIRouter(prefix="/admin", tags=["admin"])
6+
7+
8+
async def get_db_connection():
9+
return await asyncpg.connect(
10+
host="localhost",
11+
database="db",
12+
user="user",
13+
password="password",
14+
)
15+
16+
17+
@router.get("/dogs")
18+
async def list_admin_dogs():
19+
conn = await get_db_connection()
20+
dogs = await conn.fetch("SELECT * FROM dogs WHERE isAdmin = TRUE")
21+
await conn.close()
22+
return JSONResponse({"admin_dogs": [dict(d) for d in dogs]})
23+
24+
25+
@router.delete("/dogs/{dog_id}")
26+
async def delete_dog(dog_id: int):
27+
conn = await get_db_connection()
28+
result = await conn.execute("DELETE FROM dogs WHERE id = $1", dog_id)
29+
await conn.close()
30+
deleted = int(result.split()[-1])
31+
if deleted == 0:
32+
return JSONResponse({"error": "Dog not found"}, status_code=404)
33+
return JSONResponse({"message": f"Dog {dog_id} deleted"})
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
import asyncpg
2+
from fastapi import APIRouter, HTTPException, Request
3+
from fastapi.responses import HTMLResponse, JSONResponse
4+
from fastapi.templating import Jinja2Templates
5+
6+
router = APIRouter(prefix="/dogs", tags=["dogs"])
7+
8+
templates = Jinja2Templates(directory="templates")
9+
10+
11+
async def get_db_connection():
12+
return await asyncpg.connect(
13+
host="localhost",
14+
database="db",
15+
user="user",
16+
password="password",
17+
)
18+
19+
20+
@router.get("/", response_class=HTMLResponse)
21+
async def list_dogs(request: Request):
22+
conn = await get_db_connection()
23+
dogs = await conn.fetch("SELECT * FROM dogs")
24+
await conn.close()
25+
return templates.TemplateResponse(
26+
"index.html", {"request": request, "title": "Dogs", "dogs": dogs}
27+
)
28+
29+
30+
@router.get("/{dog_id}", response_class=HTMLResponse)
31+
async def get_dog(request: Request, dog_id: int):
32+
conn = await get_db_connection()
33+
dog = await conn.fetchrow("SELECT * FROM dogs WHERE id = $1", dog_id)
34+
await conn.close()
35+
if dog is None:
36+
raise HTTPException(status_code=404, detail="Dog not found")
37+
return templates.TemplateResponse(
38+
"dogpage.html",
39+
{"request": request, "title": "Dog", "dog": dog, "isAdmin": "Yes" if dog[2] else "No"},
40+
)
41+
42+
43+
@router.post("/")
44+
async def create_dog(request: Request):
45+
data = await request.form()
46+
dog_name = data.get("dog_name")
47+
48+
if not dog_name:
49+
return JSONResponse({"error": "dog_name is required"}, status_code=400)
50+
51+
conn = await get_db_connection()
52+
try:
53+
await conn.execute(
54+
"INSERT INTO dogs (dog_name, isAdmin) VALUES ($1, FALSE)", dog_name
55+
)
56+
finally:
57+
await conn.close()
58+
59+
return JSONResponse({"message": f"Dog {dog_name} created successfully"}, status_code=201)
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
from fastapi import APIRouter
2+
from fastapi.responses import JSONResponse
3+
4+
router = APIRouter(prefix="/health", tags=["health"])
5+
6+
7+
@router.get("/")
8+
async def health():
9+
return JSONResponse({"status": "ok"})
10+
11+
12+
@router.get("/ping")
13+
async def ping():
14+
return JSONResponse({"ping": "pong"})

0 commit comments

Comments
 (0)