Skip to content

studyhaxer/day14-user-course-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Day 14 — User Course API

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.


Features

  • 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 joinedload for optimised queries

Project Structure

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

Tech Stack

  • Python 3.11+
  • FastAPI
  • SQLAlchemy
  • SQLite
  • Pydantic v2
  • Uvicorn

Setup & Run

# 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 --reload

Open http://127.0.0.1:8000/docs to explore the API via Swagger UI.


API Endpoints

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

Key Concepts Practised

  • ForeignKey linking Course to User
  • relationship() with back_populates for bidirectional access
  • cascade="all, delete-orphan" for automatic child deletion
  • joinedload() for eager loading related records
  • Nested Pydantic schemas (List[CourseOut] inside UserOut)
  • from_attributes = True for ORM object serialisation

Example Request

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" }
  ]
}

Part of the Python Learning Streak

This project is Day 14 of a structured 60-day Python → FastAPI → AI Platform journey.

Author

Hafiz Atta ur Rahman (Ati)
M.Phil CS — Gold Medalist · Senior Subject Expert, Punjab Education Department
Founder, Umar Science Academy Chunian
GitHub: @studyhaxer

About

FastAPI + SQLAlchemy One-to-Many API | User-Course Management with nested schemas, cascade delete & eager loading

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages