A REST API built with FastAPI and SQLAlchemy demonstrating One-to-Many database relationships. A User can own many Courses. Built as part of a 60-day Python learning streak.
- Create users and courses
- One-to-Many relationship between User and Course
- Nested response — fetching a user returns their courses automatically
- Cascade delete — deleting a user removes all their courses
- Input validation with Pydantic v2
- Eager loading with
joinedloadfor optimised queries
day14-user-course-api/
├── database.py # SQLite engine, SessionLocal, Base
├── models.py # User and Course ORM models with relationship
├── schemas.py # Pydantic schemas including nested UserOut
└── main.py # FastAPI app with all endpoints
- Python 3.11+
- FastAPI
- SQLAlchemy
- SQLite
- Pydantic v2
- Uvicorn
# Clone the repo
git clone https://github.com/studyhaxer/day14-user-course-api.git
cd day14-user-course-api
# Install dependencies
pip install fastapi sqlalchemy uvicorn
# Run the server
uvicorn main:app --reloadOpen http://127.0.0.1:8000/docs to explore the API via Swagger UI.
| Method | Endpoint | Description |
|---|---|---|
POST |
/users |
Create a new user |
GET |
/users |
List all users |
GET |
/users/{id} |
Get user with nested courses |
POST |
/users/{id}/courses |
Add a course to a user |
DELETE |
/users/{id} |
Delete user and all their courses |
ForeignKeylinking Course to Userrelationship()withback_populatesfor bidirectional accesscascade="all, delete-orphan"for automatic child deletionjoinedload()for eager loading related records- Nested Pydantic schemas (
List[CourseOut]insideUserOut) from_attributes = Truefor ORM object serialisation
Create a user:
POST /users
{
"name": "Ati",
"email": "ati@example.com"
}Add a course to user with id=1:
POST /users/1/courses
{
"title": "FastAPI Mastery"
}Get user with all courses:
GET /users/1
{
"id": 1,
"name": "Ati",
"email": "ati@example.com",
"courses": [
{ "id": 1, "title": "FastAPI Mastery" }
]
}This project is Day 14 of a structured 60-day Python → FastAPI → AI Platform journey.
Hafiz Atta ur Rahman (Ati)
M.Phil CS — Gold Medalist · Senior Subject Expert, Punjab Education Department
Founder, Umar Science Academy Chunian
GitHub: @studyhaxer