slimshadow/notes-api
0
1from fastapi import FastAPI, HTTPException2from fastapi.responses import FileResponse3from pathlib import Path4 5app = FastAPI()6 7# Base directory where notes are stored8NOTES_DIR = Path("notes")9 10@app.get("/")11def read_root():12 return {"message": "Welcome to the Notes API!"}13 14@app.get("/subjects")15def get_subjects():16 """Get all subjects."""17 if not NOTES_DIR.exists():18 raise HTTPException(status_code=404, detail="Notes directory not found")19 subjects = [subject.name for subject in NOTES_DIR.iterdir() if subject.is_dir()]20 return {"subjects": subjects}21 22@app.get("/subjects/{subject}/units")23def get_units(subject: str):24 """Get all units for a specific subject."""25 subject_path = NOTES_DIR / subject26 if not subject_path.exists() or not subject_path.is_dir():27 raise HTTPException(status_code=404, detail="Subject not found")28 units = [unit.stem for unit in subject_path.glob("*.md")]29 return {"units": units}30 31@app.get("/subjects/{subject}/units/{unit}")32def get_unit_notes(subject: str, unit: str):33 """Get the content of a specific unit."""34 unit_path = NOTES_DIR / subject / f"{unit}.md"35 if not unit_path.exists():36 raise HTTPException(status_code=404, detail="Unit notes not found")37 return FileResponse(unit_path)38 39# Optional: Serve notes as plain text or rendered HTML40@app.get("/subjects/{subject}/units/{unit}/content")41def get_unit_notes_content(subject: str, unit: str):42 """Get the content of a specific unit as plain text."""43 unit_path = NOTES_DIR / subject / f"{unit}.md"44 if not unit_path.exists():45 raise HTTPException(status_code=404, detail="Unit notes not found")46 with open(unit_path, "r", encoding="utf-8") as file:47 content = file.read()48 return {"content": content}49 