aki-008 commited on
Commit
0329c36
·
1 Parent(s): 0aab9be

chore: Readme updated

Browse files
Files changed (1) hide show
  1. Readme.md +148 -1188
Readme.md CHANGED
@@ -1,1296 +1,256 @@
1
- # 🔍 FastAPI + PostgreSQL Student Management System - Line-by-Line Explainer
2
 
3
- Complete breakdown of an async student API with authentication, explained like you're learning it for the first time.
4
 
5
  ---
6
 
7
- ## 📚 Table of Contents
8
- 1. [Overview & Imports](#1️⃣-overview--imports)
9
- 2. [Configuration](#2️⃣-configuration)
10
- 3. [Database Setup](#3️⃣-database-setup)
11
- 4. [Database Models](#4️⃣-database-models)
12
- 5. [Pydantic Validation Models](#5️⃣-pydantic-validation-models)
13
- 6. [Security & Authentication](#6️⃣-security--authentication)
14
- 7. [Database Dependency](#7️⃣-database-dependency)
15
- 8. [FastAPI Application](#8️⃣-fastapi-application)
16
- 9. [Startup & Shutdown Events](#9️⃣-startup--shutdown-events)
17
- 10. [Authentication Routes](#10️⃣-authentication-routes)
18
- 11. [Student CRUD Operations](#11️⃣-student-crud-operations)
19
- 12. [Health Check & Runner](#12️⃣-health-check--runner)
20
 
21
- ---
22
-
23
- ## 1️⃣ Overview & Imports
24
-
25
- ### **Comment Block**
26
- ```python
27
- """
28
- FastAPI + PostgreSQL Student Management System
29
- Complete async implementation with SQLAlchemy, authentication, and validation
30
-
31
- Requirements:
32
- pip install fastapi uvicorn sqlalchemy asyncpg psycopg2-binary python-jose[cryptography] passlib[bcrypt] python-multipart
33
- """
34
- ```
35
-
36
- **What it is:**
37
- A multi-line docstring (document string) that acts as the script's billboard and shopping list.
38
-
39
- **What it's used for:**
40
- This is like the "Welcome to our restaurant" sign that tells you:
41
- 1. **What you're building** - A student management API
42
- 2. **The tech stack** - FastAPI, PostgreSQL, async everything
43
- 3. **The installation cheat-sheet** - Copy-paste commands to get all required tools
44
-
45
- **IRL Example:**
46
- Imagine buying furniture from IKEA. This comment block is the box label that says "BILLY Bookcase" and lists all the screws, tools, and instructions inside. Without it, you'd have no idea what you're about to build or what tools you need.
47
-
48
- ---
49
-
50
- ### **FastAPI Imports**
51
- ```python
52
- from fastapi import FastAPI, HTTPException, Depends, status
53
- ```
54
-
55
- **What it is:**
56
- Importing the four core ingredients to build a FastAPI application.
57
-
58
- **What it's used for:**
59
- - `FastAPI`: The main framework (your restaurant's foundation and kitchen layout)
60
- - `HTTPException`: Standardized error messages (your "Sorry, we're out of salmon" response)
61
- - `Depends`: Dependency injection system (your "I need a clean plate from the dishwasher" request)
62
- - `status`: HTTP status code constants (your "404 = Not Found" cheat sheet)
63
-
64
- **Syntax Breakdown:**
65
- Python's `from ... import ...` grabs specific tools from a toolbox instead of lugging the entire toolbox around.
66
-
67
- **IRL Example:**
68
- Opening a restaurant. Instead of renting an entire warehouse of kitchen equipment (`import fastapi`), you specifically rent: a commercial oven (`FastAPI`), a fire alarm (`HTTPException`), a dishwashing service (`Depends`), and a health code manual (`status`).
69
-
70
- ---
71
-
72
- ### **Security Imports**
73
- ```python
74
- from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
75
- ```
76
-
77
- **What it is:**
78
- Tools for implementing token-based authentication.
79
-
80
- **What it's used for:**
81
- - `HTTPBearer`: The security scheme that looks for "Authorization: Bearer <token>" headers
82
- - `HTTPAuthorizationCredentials`: The container that holds the extracted token
83
-
84
- **IRL Example:**
85
- A nightclub's security system. `HTTPBearer` is the policy that says "We only accept VIP badges with a hologram strip," and `HTTPAuthorizationCredentials` is the scanner device that reads and validates those badges at the door.
86
-
87
- ---
88
-
89
- ### **CORS Middleware**
90
- ```python
91
- from fastapi.middleware.cors import CORSMiddleware
92
- ```
93
-
94
- **What it is:**
95
- Cross-Origin Resource Sharing (CORS) protection.
96
-
97
- **What it's used for:**
98
- Prevents malicious websites from making unauthorized requests to your API from a browser. It's like a "no solicitation" sign that tells browsers which domains are allowed to knock on your API's door.
99
-
100
- **IRL Example:**
101
- You own a house (`your API`). `CORSMiddleware` is your doorbell camera that checks if the visitor is from your approved guest list (`allowed_origins`). Without it, any stranger could walk up and demand entry.
102
-
103
- ---
104
-
105
- ### **SQLAlchemy Async Imports**
106
- ```python
107
- from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
108
- ```
109
-
110
- **What it is:**
111
- The async-capable database tools from SQLAlchemy.
112
-
113
- **What it's used for:**
114
- - `create_async_engine`: Builds a non-blocking database connection pool
115
- - `AsyncSession`: A database session that won't freeze your API while waiting for queries
116
- - `async_sessionmaker`: Factory that produces these async sessions on demand
117
-
118
- **IRL Example:**
119
- A modern coffee shop with mobile ordering. Instead of one cashier handling one customer at a time (sync), you have a system that:
120
- - Takes orders (`AsyncSession`)
121
- - Processes multiple orders simultaneously without waiting for each drink to finish (`async`)
122
- - Has multiple baristas ready to make drinks (`connection pool`)
123
-
124
- ---
125
-
126
- ### **SQLAlchemy ORM Imports**
127
- ```python
128
- from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
129
- ```
130
-
131
- **What it is:**
132
- Object-Relational Mapping (ORM) tools that let you use Python classes as database tables.
133
-
134
- **What it's used for:**
135
- - `DeclarativeBase`: The foundation class for all your database models
136
- - `Mapped`: Type hint that says "this class attribute maps to a database column"
137
- - `mapped_column`: Factory function to configure column properties
138
-
139
- **IRL Example:**
140
- A digital Rolodex system. Instead of writing raw SQL like `INSERT INTO students VALUES (...)`, you create a `Student` class (`DeclarativeBase`) where each property (`Mapped[name]`) automatically syncs with a database column, like magic index cards that file themselves.
141
-
142
- ---
143
-
144
- ### **SQLAlchemy Query & Types**
145
- ```python
146
- from sqlalchemy import select, String
147
- ```
148
-
149
- **What it is:**
150
- Essential SQL building blocks.
151
-
152
- **What it's used for:**
153
- - `select`: Creates SELECT queries in Python (instead of raw SQL strings)
154
- - `String`: Defines VARCHAR columns in PostgreSQL
155
-
156
- **IRL Example:**
157
- `select` is like a smart query assistant who speaks both Python and SQL. Instead of handwriting "SELECT * FROM students WHERE age > 18", you tell it in Python: `select(Student).where(Student.age > 18)` and it translates perfectly.
158
-
159
- ---
160
-
161
- ### **Pydantic Imports**
162
- ```python
163
- from pydantic import BaseModel, EmailStr, Field, validator
164
- ```
165
-
166
- **What it is:**
167
- Data validation and serialization library that acts as your API's security guard and translator.
168
-
169
- **What it's used for:**
170
- - `BaseModel`: Foundation for all data models
171
- - `EmailStr`: Automatic email format validation
172
- - `Field`: Fine-tuned validation rules (min/max length, descriptions)
173
- - `validator`: Custom validation functions (your special rules)
174
-
175
- **IRL Example:**
176
- A TSA checkpoint at an airport. `BaseModel` is the checkpoint itself. `EmailStr` is the automated scanner that knows a valid passport format. `Field` is the sign saying "Liquids must be < 100ml." `validator` is the agent who says "Sir, you can't bring a full water bottle through."
177
-
178
- ---
179
-
180
- ### **Typing & Utility Imports**
181
- ```python
182
- from typing import Optional, List
183
- from datetime import datetime, timedelta
184
- ```
185
-
186
- **What it is:**
187
- Type hints and date/time utilities.
188
-
189
- **What it's used for:**
190
- - `Optional[T]`: Means "this value is either type T or None" (`Optional[str]` = string or None)
191
- - `List[T]`: Type hint for lists of a specific type
192
- - `datetime`: Current timestamp
193
- - `timedelta`: Time arithmetic (30 minutes from now)
194
-
195
- **IRL Example:**
196
- A delivery tracking app. `Optional[str]` handles "delivery instructions" that might be empty. `List[Package]` ensures you're dealing with packages, not random objects. `datetime` stamps when it shipped, and `timedelta` calculates "expected delivery in 3 days."
197
-
198
- ---
199
-
200
- ### **JWT & Password Imports**
201
- ```python
202
- from jose import JWTError, jwt
203
- from passlib.context import CryptContext
204
- ```
205
-
206
- **What it is:**
207
- JSON Web Token handling and password hashing libraries.
208
-
209
- **What it's used for:**
210
- - `jwt.encode/decode`: Creates and verifies authentication tokens
211
- - `JWTError`: Exception when tokens are invalid/expired
212
- - `CryptContext`: Manages password hashing algorithms
213
-
214
- **IRL Example:**
215
- A concert venue's wristband system. `jwt.encode` prints a tamper-proof wristband with your access level. `jwt.decode` is the UV scanner at each entrance. `CryptContext` is the secure machine that embosses wristbands so they can't be faked.
216
-
217
- ---
218
-
219
- ### **OS Import**
220
- ```python
221
- import os
222
- ```
223
-
224
- **What it is:**
225
- Python's interface to operating system environment variables.
226
-
227
- **What it's used for:**
228
- - `os.getenv()`: Safely reads environment variables (database passwords, secret keys)
229
- - Keeps sensitive data out of your source code
230
-
231
- **IRL Example:**
232
- A hotel key card system. The master key code (`SECRET_KEY`) is stored in the hotel safe (`environment variables`), not written on a sticky note on the front desk (`hardcoded in script`). `os.getenv()` is the manager opening the safe when needed.
233
-
234
- ---
235
-
236
- ## 2️⃣ Configuration
237
-
238
- ### **Database URL Configuration**
239
- ```python
240
- DATABASE_URL = os.getenv(
241
- "DATABASE_URL",
242
- "postgresql+asyncpg://postgres:690869@172.26.157.164:5432/studentdb"
243
- )
244
- ```
245
-
246
- **What it is:**
247
- Environment-driven database connection string with a fallback default.
248
-
249
- **What it's used for:**
250
- - `os.getenv()` first tries to read from system environment variables (production best practice)
251
- - Fallback string is used if environment variable doesn't exist (development convenience)
252
- - Format: `dialect+driver://user:password@host:port/database`
253
-
254
- **Syntax Breakdown:**
255
- - `postgresql+asyncpg://`: Use PostgreSQL with asyncpg driver for non-blocking operations
256
- - `postgres:690869`: Username and password (⚠️ **Never commit real passwords!**)
257
- - `@172.26.157.164:5432`: Database server IP and port
258
- - `/studentdb`: Database name
259
-
260
- **IRL Example:**
261
- A smart home door lock. You program it to first check if there's a master code set via the mobile app (`os.getenv()`). If not, it falls back to the factory default code (`fallback string`). In production, you *always* use the mobile app; the default is just for initial setup.
262
-
263
- ---
264
-
265
- ### **JWT Secret Configuration**
266
- ```python
267
- SECRET_KEY = os.getenv("SECRET_KEY", "production")
268
- ALGORITHM = "HS256"
269
- ACCESS_TOKEN_EXPIRE_MINUTES = 30
270
- ```
271
-
272
- **What it is:**
273
- Security parameters for JWT token generation.
274
-
275
- **What it's used for:**
276
- - `SECRET_KEY`: The *master password* used to sign tokens (keeps them tamper-proof)
277
- - `ALGORITHM`: HS256 is a symmetric signing algorithm (same key signs and verifies)
278
- - `ACCESS_TOKEN_EXPIRE_MINUTES`: Tokens auto-expire after 30 minutes for security
279
-
280
- **IRL Example:**
281
- A theme park's ride pass system:
282
- - `SECRET_KEY` is the unique holographic foil pattern only your park possesses
283
- - `ALGORITHM` is the type of embossing machine (HS256 = standard heat press)
284
- - `ACCESS_TOKEN_EXPIRE_MINUTES` is the stamp that says "Valid only today until 6 PM"
285
-
286
- ---
287
-
288
- ## 3️⃣ Database Setup
289
-
290
- ### **Async Engine Creation**
291
- ```python
292
- engine = create_async_engine(DATABASE_URL, echo=True)
293
- ```
294
-
295
- **What it is:**
296
- The heart of your async database connection pool.
297
-
298
- **What it's used for:**
299
- - Creates a non-blocking connection engine that handles multiple requests simultaneously
300
- - `echo=True` logs all SQL queries to console (invaluable for debugging)
301
-
302
- **IRL Example:**
303
- A high-end restaurant's kitchen. `engine` is the head chef who:
304
- - Manages multiple cooking stations (connections)
305
- - Can start prep for Order #2 while Order #1 is in the oven (async)
306
- - Wears a bodycam (`echo=True`) so management can review exactly what happened during the dinner rush
307
-
308
- ---
309
-
310
- ### **Session Factory**
311
- ```python
312
- async_session_maker = async_sessionmaker(engine, expire_on_commit=False)
313
- ```
314
-
315
- **What it is:**
316
- A factory that produces database sessions on demand.
317
-
318
- **What it's used for:**
319
- - `expire_on_commit=False`: Keeps data in memory after committing (prevents unnecessary re-queries)
320
- - Each API request gets its own session (like giving each customer a fresh plate)
321
-
322
- **IRL Example:**
323
- A conveyor belt sushi restaurant. The `async_session_maker` is the automated plate dispenser. Every time a customer sits down (API request), it dispenses a fresh, clean plate (session). The plate stays usable even after they take their first sushi (`commit`), so they don't have to get a new plate for every single bite.
324
-
325
- ---
326
-
327
- ## 4️⃣ Database Models
328
-
329
- ### **Base Model Foundation**
330
- ```python
331
- class Base(DeclarativeBase):
332
- pass
333
- ```
334
-
335
- **What it is:**
336
- The foundation class that all database models inherit from.
337
-
338
- **What it's used for:**
339
- - SQLAlchemy needs a central Base to register all tables
340
- - Even though it's empty (`pass`), it's crucial for metadata collection
341
-
342
- **IRL Example:**
343
- A filing cabinet's index system. Every type of document (Student, User) has its own folder, but they all share the same index card system (`Base`). The index system doesn't contain data itself but knows where everything is stored.
344
-
345
- ---
346
-
347
- ### **Student Model**
348
- ```python
349
- class Student(Base):
350
- __tablename__ = "students"
351
-
352
- id: Mapped[int] = mapped_column(primary_key=True, index=True)
353
- name: Mapped[str] = mapped_column(String(100))
354
- email: Mapped[str] = mapped_column(String(100), unique=True, index=True)
355
- age: Mapped[int]
356
- grade: Mapped[str] = mapped_column(String(5))
357
- created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
358
- ```
359
-
360
- **What it is:**
361
- A Python class that magically becomes a PostgreSQL table.
362
-
363
- **What it's used for:**
364
- - `__tablename__`: The actual table name in PostgreSQL
365
- - Each `Mapped[column]` becomes a column with constraints
366
-
367
- **Syntax Breakdown:**
368
- - `id`: Primary key, auto-incrementing, indexed for fast lookups
369
- - `name`: String up to 100 characters
370
- - `email`: String, must be unique across all students, indexed for fast email searches
371
- - `age`: Plain integer
372
- - `grade`: String up to 5 chars (stores "A+", "F", etc.)
373
- - `created_at`: Auto-set to current UTC time when record is created
374
-
375
- **IRL Example:**
376
- A school registrar's digital filing system. Instead of filling out paper forms, they use a tablet app where:
377
- - Each field is validated before submission
378
- - Student ID is auto-generated and used for quick filing
379
- - Email must be unique (can't have two students with same email)
380
- - Timestamp is automatically stamped when the form is first saved
381
-
382
- ---
383
-
384
- ### **User Model**
385
- ```python
386
- class User(Base):
387
- __tablename__ = "users"
388
-
389
- id: Mapped[int] = mapped_column(primary_key=True, index=True)
390
- username: Mapped[str] = mapped_column(String(50), unique=True, index=True)
391
- hashed_password: Mapped[str] = mapped_column(String(255))
392
- ```
393
-
394
- **What it is:**
395
- A separate table for storing authenticated user accounts.
396
-
397
- **What it's used for:**
398
- - Stores login credentials separately from student data
399
- - `hashed_password` contains scrambled passwords (never plain text!)
400
- - 255 char limit accommodates long Argon2 hashes
401
-
402
- **IRL Example:**
403
- A school's staff keycard system. There's a locked cabinet (`users` table) containing:
404
- - Employee ID numbers (`id`)
405
- - Name badges (`username`, unique)
406
- - Encrypted keycard codes (`hashed_password`) that can't be reverse-engineered
407
-
408
- This is separate from the student records office—teachers have access, but the data is stored in different secure locations.
409
-
410
- ---
411
-
412
- ## 5️⃣ Pydantic Validation Models
413
-
414
- ### **StudentBase Model**
415
- ```python
416
- class StudentBase(BaseModel):
417
- name: str = Field(..., min_length=2, max_length=100, description="Student full name")
418
- email: EmailStr = Field(..., description="Student email address")
419
- age: int = Field(..., ge=5, le=100, description="Student age (5-100)")
420
- grade: str = Field(..., pattern="^[A-F][+-]?$", description="Grade (A-F with optional + or -)")
421
- ```
422
-
423
- **What it is:**
424
- The foundational validation blueprint for student data.
425
 
426
- **What it's used for:**
427
- - `Field(...)`: Makes the field required (can't be omitted)
428
- - `min_length=2`: Name must be at least 2 characters
429
- - `ge=5, le=100`: Age must be between 5 and 100 (inclusive)
430
- - `pattern`: Regular expression ensuring grade matches letter grades only
431
 
432
- **IRL Example:**
433
- A strict school application kiosk:
434
- - **Name field**: Won't accept "J" or just spaces; minimum 2 real letters
435
- - **Email field**: Has an @ symbol, valid domain; rejects "bob@com"
436
- - **Age field**: Slider only goes from 5 to 100; toddlers can't apply
437
- - **Grade field**: Dropdown only shows valid grades (A+, A, A-, B+, etc.)
438
 
439
  ---
440
 
441
- ### **Name Validator**
442
- ```python
443
- @validator('name')
444
- def validate_name(cls, v):
445
- if not v.strip():
446
- raise ValueError('Name cannot be empty or just whitespace')
447
- return v.strip()
448
- ```
449
 
450
- **What it is:**
451
- Custom validation logic for the name field.
452
 
453
- **What it's used for:**
454
- - `v.strip()`: Removes leading/trailing spaces
455
- - Raises error if the result is empty (e.g., name was just spaces)
456
- - Returns the cleaned version
457
 
458
- **IRL Example:**
459
- A DMV form validator. When you type " John " in the name field, it automatically trims the spaces to "John" before submitting. If you try to submit just spaces, the system beeps and says "Please enter a valid name."
 
 
 
 
460
 
461
- ---
462
 
463
- ### **Grade Validator**
464
- ```python
465
- @validator('grade')
466
- def validate_grade(cls, v):
467
- v = v.upper()
468
- if v not in ['A+', 'A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D', 'D-', 'F']:
469
- raise ValueError('Invalid grade format')
470
- return v
471
- ```
472
 
473
- **What it is:**
474
- Ensures only valid letter grades are accepted.
475
 
476
- **What it's used for:**
477
- - Converts input to uppercase (`a+` → `A+`)
478
- - Checks against an exhaustive whitelist
479
- - Prevents typos like "A++" or "B--"
480
 
481
- **IRL Example:**
482
- A Scantron machine. When teachers grade multiple-choice tests, the machine only accepts certain bubbled answers (A, B, C, D, E). If a student bubbles "F" on a 5-question test, the machine rejects it as invalid.
 
 
 
483
 
484
- ---
485
 
486
- ### **StudentCreate Model**
487
- ```python
488
- class StudentCreate(StudentBase):
489
- pass
490
- ```
491
 
492
- **What it is:**
493
- A clone of `StudentBase` for creating new students.
494
 
495
- **What it's used for:**
496
- - Inheritance: Gets all validation from parent
497
- - Semantic clarity: `StudentCreate` tells developers this is for creation only
498
- - Future-proofing: You can add creation-specific fields later without breaking existing code
499
 
500
- **IRL Example:**
501
- A "New Student Registration Form" that's identical to the regular form but printed on blue paper. Today it's the same, but tomorrow you might add a "Parent Signature" field that's only on the blue creation form.
 
 
502
 
503
  ---
504
 
505
- ### **StudentUpdate Model**
506
- ```python
507
- class StudentUpdate(BaseModel):
508
- name: Optional[str] = Field(None, min_length=2, max_length=100)
509
- email: Optional[EmailStr] = None
510
- age: Optional[int] = Field(None, ge=5, le=100)
511
- grade: Optional[str] = Field(None, pattern="^[A-F][+-]?$")
512
- ```
513
-
514
- **What it is:**
515
- A model for *partial* student updates where all fields are optional.
516
-
517
- **What it's used for:**
518
- - `Optional[T] = None`: Every field can be omitted (PATCH request style)
519
- - Allows updating just one field (e.g., only change grade) without sending full data
520
 
521
- **IRL Example:**
522
- A student profile editing page on a school portal. You can change just the grade without re-entering name, email, and age. The form has "Save" buttons next to individual fields—all fields are optional, but if you fill one, it must still pass validation.
523
-
524
- ---
525
-
526
- ### **StudentResponse Model**
527
- ```python
528
- class StudentResponse(StudentBase):
529
- id: int
530
- created_at: datetime
531
-
532
- class Config:
533
- from_attributes = True
534
  ```
535
-
536
- **What it is:**
537
- The response format when sending student data back to clients.
538
-
539
- **What it's used for:**
540
- - Adds database-generated fields (`id`, `created_at`) to the base model
541
- - `from_attributes = True`: Tells Pydantic to read from SQLAlchemy object attributes (`.id`, `.name`) instead of dictionary keys (`["id"]`, `["name"]`)
542
-
543
- **IRL Example:**
544
- A school report card printing system. The blank form (`StudentBase`) has name, grade, etc. The printed report (`StudentResponse`) adds the official student ID number and the date issued—fields the student didn't provide but were generated by the system.
545
-
546
- ---
547
-
548
- ### **UserCreate Model**
549
- ```python
550
- class UserCreate(BaseModel):
551
- username: str = Field(..., min_length=3, max_length=50)
552
- password: str = Field(..., min_length=6, max_length=72)
553
  ```
554
 
555
- **What it is:**
556
- Validation model for new user registration.
557
-
558
- **What it's used for:**
559
- - `min_length=6`: Basic password strength requirement
560
- - `max_length=72`: Critical for bcrypt/Argon2 compatibility (they truncate at 72 bytes)
561
-
562
  ---
563
 
564
- ### **Password Byte-Size Validator**
565
- ```python
566
- @validator('password')
567
- def validate_password(cls, v):
568
- if len(v.encode('utf-8')) > 72:
569
- raise ValueError('Password cannot exceed 72 bytes')
570
- return v
571
- ```
572
-
573
- **What it is:**
574
- Ensures password doesn't exceed 72 *bytes* (not characters—important for Unicode!).
575
 
576
- **What it's used for:**
577
- - Some characters (like emojis) use multiple bytes
578
- - "🔒🔒🔒" might be 3 characters but 12 bytes
579
- - Prevents silent truncation by bcrypt
580
 
581
- **IRL Example:**
582
- A text message limit. You can send 160 characters, but if you use special Unicode symbols (like 🎉), each might count as 2-4 characters. The validator warns you before you exceed the hidden byte limit.
583
-
584
- ---
585
-
586
- ### **Token Response Model**
587
- ```python
588
- class Token(BaseModel):
589
- access_token: str
590
- token_type: str
591
  ```
592
-
593
- **What it is:**
594
- The login response structure.
595
-
596
- **What it's used for:**
597
- - Standard OAuth2 token format
598
- - `access_token`: The JWT string
599
- - `token_type`: Always "bearer" for Bearer token authentication
600
-
601
- **IRL Example:**
602
- A valet ticket. It has a unique code (`access_token`) and the type of service (`token_type: "bearer"`) which tells the API "This is a bearer token, not a basic auth or API key."
603
-
604
- ---
605
-
606
- ## 6️⃣ Security & Authentication
607
-
608
- ### **Password Context**
609
- ```python
610
- pwd_context = CryptContext(schemes=["argon2"], deprecated="auto")
611
  ```
612
 
613
- **What it is:**
614
- Configures Argon2 as the password hashing algorithm.
615
 
616
- **What it's used for:**
617
- - Argon2 is the winner of the Password Hashing Competition (resistant to GPU attacks)
618
- - `deprecated="auto"`: Future-proofs against algorithm upgrades
619
 
620
- **IRL Example:**
621
- Choosing a safe for your vault. You select the Argon2 model because it's drill-resistant, fireproof, and can't be opened with a stethoscope (GPU cracking). The "auto-deprecate" feature means if a better safe comes out, the system automatically flags old ones as outdated.
 
 
 
 
622
 
623
- ---
624
 
625
- ### **Password Verification Function**
626
- ```python
627
- def verify_password(plain_password: str, hashed_password: str) -> bool:
628
- password_bytes = plain_password.encode('utf-8')[:72]
629
- plain_password_truncated = password_bytes.decode('utf-8', errors='ignore')
630
- return pwd_context.verify(plain_password_truncated, hashed_password)
631
  ```
632
-
633
- **What it is:**
634
- Safely checks if a plain password matches a stored hash.
635
-
636
- **What it's used for:**
637
- - Truncates to 72 bytes before verifying (prevents timing attacks)
638
- - `errors='ignore'`: Drops invalid byte sequences gracefully
639
- - Returns `True` if match, `False` otherwise
640
-
641
- **IRL Example:**
642
- A high-security office keypad. When you type your code:
643
- 1. The system only reads first 10 digits (ignores extra)
644
- 2. Compares against stored scrambled code (not the real code)
645
- 3. Green light if they match, red light if not
646
- 4. Takes same time whether you typed 6 or 10 digits (prevents guessing)
647
-
648
- ---
649
-
650
- ### **Password Hashing Function**
651
- ```python
652
- def get_password_hash(password: str) -> str:
653
- password_bytes = password.encode('utf-8')[:72]
654
- password_truncated = password_bytes.decode('utf-8', errors='ignore')
655
- return pwd_context.hash(password_truncated)
656
  ```
657
 
658
- **What it is:**
659
- Converts plain passwords into irreversible hashes for storage.
660
 
661
- **What it's used for:**
662
- - Never store plain passwords
663
- - Same truncation logic as verification
664
- - Returns a long string starting with `$argon2...`
665
-
666
- **IRL Example:**
667
- A paper shredder that creates confetti patterns. Every time you shred "password123", it creates the *same unique confetti pattern*. But you can't reverse the pattern back to "password123". Even if thieves steal the confetti, they can't reconstruct the original document.
668
-
669
- ---
670
-
671
- ### **JWT Token Creation**
672
- ```python
673
- def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
674
- to_encode = data.copy()
675
- expire = datetime.utcnow() + (expires_delta or timedelta(minutes=15))
676
- to_encode.update({"exp": expire})
677
- encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
678
- return encoded_jwt
679
  ```
680
-
681
- **What it is:**
682
- Generates a time-limited authentication token.
683
-
684
- **What it's used for:**
685
- - Copies user data (like username)
686
- - Adds expiration timestamp (`exp` claim)
687
- - Signs with secret key to prevent tampering
688
- - Returns base64-encoded JWT string
689
-
690
- **IRL Example:**
691
- A concert venue wristband machine:
692
- 1. You input data: "Adult, 21+, VIP" (`data: dict`)
693
- 2. Machine stamps expiration: "Valid until 11 PM" (`expires_delta`)
694
- 3. Embosses with holographic seal (`SECRET_KEY + ALGORITHM`)
695
- 4. Spits out wristband with barcode (JWT string)
696
-
697
- If someone tries to alter "VIP" to "ALL ACCESS", the seal breaks and scanners reject it.
698
-
699
- ---
700
-
701
- ### **Current User Dependency (The Auth Bouncer)**
702
- ```python
703
- async def get_current_user(
704
- credentials: HTTPAuthorizationCredentials = Depends(security),
705
- db: AsyncSession = Depends(lambda: async_session_maker())
706
- ):
707
- credentials_exception = HTTPException(
708
- status_code=status.HTTP_401_UNAUTHORIZED,
709
- detail="Could not validate credentials",
710
- headers={"WWW-Authenticate": "Bearer"},
711
- )
712
- try:
713
- token = credentials.credentials
714
- payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
715
- username: str = payload.get("sub")
716
- if username is None:
717
- raise credentials_exception
718
- except JWTError:
719
- raise credentials_exception
720
-
721
- result = await db.execute(select(User).filter(User.username == username))
722
- user = result.scalar_one_or_none()
723
- if user is None:
724
- raise credentials_exception
725
- return user
726
  ```
727
 
728
- **What it is:**
729
- The authentication gatekeeper for protected routes.
730
 
731
- **What it's used for:**
732
- 1. **Extract token**: Gets `Authorization: Bearer <token>` header
733
- 2. **Decode JWT**: Verifies signature and expiration
734
- 3. **Extract username**: From `"sub"` (subject) claim
735
- 4. **Database lookup**: Ensures user still exists
736
- 5. **Return user object**: Injects into route functions
737
 
738
- **IRL Example:**
739
- A corporate building with RFID badge access:
740
- 1. **Badge swipe**: Employee taps card (`credentials`)
741
- 2. **Scanner verification**: Checks if badge is forged/expired (`jwt.decode`)
742
- 3. **Database check**: Looks up employee ID to ensure they're still employed (`select(User)`)
743
- 4. **Door opens**: Returns employee record to security system (`return user`)
744
- 5. **Invalid badge**: Alarm sounds, door stays locked (`HTTPException`)
745
 
746
- If badge is expired (JWTError) or employee was fired (user is None), the bouncer yells "Access denied!"
747
-
748
- ---
749
 
750
- ## 7️⃣ Database Dependency
751
-
752
- ### **Session Lifetime Manager**
753
- ```python
754
- async def get_db():
755
- async with async_session_maker() as session:
756
- try:
757
- yield session
758
- await session.commit()
759
- except Exception:
760
- await session.rollback()
761
- raise
762
- finally:
763
- await session.close()
764
  ```
765
-
766
- **What it is:**
767
- A context manager that handles database sessions for each request.
768
-
769
- **What it's used for:**
770
- - **Creates session**: `async with` opens a new session
771
- - **Yields**: Gives session to route function (`yield session`)
772
- - **Auto-commit**: If no errors, saves changes (`await session.commit()`)
773
- - **Auto-rollback**: If error occurs, undoes changes (`await session.rollback()`)
774
- - **Cleanup**: Always closes session (`finally: await session.close()`)
775
-
776
- **IRL Example:**
777
- A bank teller's daily procedure:
778
- 1. **Open drawer**: Gets cash drawer for the day (`yield session`)
779
- 2. **Process transactions**: Helps customers (route function runs)
780
- 3. **Balance**: If no errors, locks drawer and finalizes (`commit`)
781
- 4. **Error**: If robbed, triggers silent alarm and voids transactions (`rollback`)
782
- 5. **Close**: Goes home, drawer locked regardless (`finally: close`)
783
-
784
- Even if the teller faints mid-transaction, the `finally` block ensures the drawer gets locked.
785
-
786
- ---
787
-
788
- ## 8️⃣ FastAPI Application
789
-
790
- ### **App Initialization**
791
- ```python
792
- app = FastAPI(
793
- title="Student Management API",
794
- description="FastAPI + PostgreSQL with SQLAlchemy async",
795
- version="1.0.0"
796
- )
797
  ```
798
 
799
- **What it is:**
800
- Creates the main FastAPI application instance.
801
 
802
- **What it's used for:**
803
- - `title`: Shows in API documentation (Swagger UI)
804
- - `description`: Detailed info about the API
805
- - `version`: Semantic versioning for API changes
806
-
807
- **IRL Example:**
808
- Opening a new restaurant. You register it with:
809
- - **Name**: "Student Management Diner" (`title`)
810
- - **Description**: "Serves fresh student data with PostgreSQL sauce" (`description`)
811
- - **Version**: "Menu v1.0" (`version`)
812
-
813
- This info appears on your website and menu (API docs).
814
-
815
- ---
816
-
817
- ### **CORS Middleware**
818
- ```python
819
- app.add_middleware(
820
- CORSMiddleware,
821
- allow_origins=["*"], # In production, specify allowed origins
822
- allow_credentials=True,
823
- allow_methods=["*"],
824
- allow_headers=["*"],
825
- )
826
  ```
827
-
828
- **What it is:**
829
- Configures Cross-Origin Resource Sharing policy.
830
-
831
- **What it's used for:**
832
- - `allow_origins=["*"]`: **DANGEROUS** - allows any website to call your API
833
- - `allow_credentials=True`: Allows cookies/auth headers
834
- - `allow_methods=["*"]`: Allows GET, POST, PUT, DELETE, etc.
835
- - `allow_headers=["*"]`: Allows any custom headers
836
-
837
- **⚠️ Production Warning:**
838
- `["*"]` is like leaving your front door unlocked. In production, specify exact domains like `["https://your-frontend.com"]`.
839
-
840
- **IRL Example:**
841
- A public library's computer policy vs. a corporate VPN:
842
- - **Library** (`allow_origins=["*"]`): Anyone can walk in and use computers
843
- - **Corporate** (`allow_origins=["https://corp.com"]`): Only company-issued laptops can connect
844
-
845
- ---
846
-
847
- ## 9️⃣ Startup & Shutdown Events
848
-
849
- ### **Startup Event**
850
- ```python
851
- @app.on_event("startup")
852
- async def startup():
853
- async with engine.begin() as conn:
854
- await conn.run_sync(Base.metadata.create_all)
855
- print("✅ Database tables created successfully")
856
  ```
857
 
858
- **What it is:**
859
- Auto-creates database tables when the app starts.
860
 
861
- **What it's used for:**
862
- - `engine.begin()`: Starts a database transaction
863
- - `run_sync`: Converts async connection to sync for SQLAlchemy's `create_all`
864
- - Creates `students` and `users` tables if they don't exist
865
- - Prints success message
866
-
867
- **IRL Example:**
868
- A pop-up restaurant's opening checklist:
869
- 1. **Unlock doors** (`engine.begin()`)
870
- 2. **Set up tables and chairs** (`create_all()`)
871
- 3. **Check inventory** (tables created)
872
- 4. **Unlock sign turns green** (print success)
873
-
874
- If tables already exist, it's like "Tables are already set up, ready to serve!"
875
-
876
- ---
877
-
878
- ### **Shutdown Event**
879
- ```python
880
- @app.on_event("shutdown")
881
- async def shutdown():
882
- await engine.dispose()
883
- print("🔴 Database connection closed")
884
  ```
885
-
886
- **What it is:**
887
- Gracefully closes database connections when app stops.
888
-
889
- **What it's used for:**
890
- - `engine.dispose()`: Closes all connections in the pool
891
- - Prevents "orphaned" connections that eat database resources
892
- - Prints closure message for ops visibility
893
-
894
- **IRL Example:**
895
- A store's closing procedure:
896
- 1. **Last customer leaves** (last request processed)
897
- 2. **Lock doors** (`shutdown` event triggered)
898
- 3. **Turn off all lights and equipment** (`engine.dispose()`)
899
- 4. **Security system armed** (connections closed)
900
- 5. **Sign on door**: "Closed" (print message)
901
-
902
- Without this, it's like leaving all lights and AC on overnight—wastes resources.
903
-
904
- ---
905
-
906
- ## 10️⃣ Authentication Routes
907
-
908
- ### **Register Endpoint**
909
- ```python
910
- @app.post("/auth/register", response_model=dict, tags=["Authentication"])
911
- async def register(user: UserCreate, db: AsyncSession = Depends(get_db)):
912
- result = await db.execute(select(User).filter(User.username == user.username))
913
- existing_user = result.scalar_one_or_none()
914
-
915
- if existing_user:
916
- raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Username already registered")
917
-
918
- new_user = User(username=user.username, hashed_password=get_password_hash(user.password))
919
- db.add(new_user)
920
- await db.commit()
921
-
922
- return {"message": "User registered successfully", "username": user.username}
923
  ```
924
 
925
- **What it is:**
926
- Creates a new user account with hashed password.
927
-
928
- **What it's used for:**
929
- 1. **Check existence**: Queries if username already taken
930
- 2. **Hash password**: Never stores plain text
931
- 3. **Create user**: Adds to database
932
- 4. **Commit**: Saves transaction
933
- 5. **Return success**: JSON response
934
-
935
- **IRL Example:**
936
- A gym membership signup:
937
- 1. **Desk clerk checks** if your desired username "GymGuru" is taken
938
- 2. **If taken**: "Sorry, that username is already in use" (`HTTPException`)
939
- 3. **If available**: Scans your ID, takes photo (`User` object created)
940
- 4. **Makes membership card** (`hashed_password` = encrypted member ID)
941
- 5. **Welcome package**: "Welcome GymGuru! Membership #12345 activated"
942
-
943
  ---
944
 
945
- ### **Login Endpoint**
946
- ```python
947
- @app.post("/auth/login", response_model=Token, tags=["Authentication"])
948
- async def login(username: str, password: str, db: AsyncSession = Depends(get_db)):
949
- result = await db.execute(select(User).filter(User.username == username))
950
- user = result.scalar_one_or_none()
951
-
952
- if not user or not verify_password(password, user.hashed_password):
953
- raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="...")
954
-
955
- access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
956
- access_token = create_access_token(data={"sub": user.username}, expires_delta=access_token_expires)
957
-
958
- return {"access_token": access_token, "token_type": "bearer"}
959
- ```
960
 
961
- **What it is:**
962
- Verifies credentials and returns JWT token.
963
 
964
- **What it's used for:**
965
- 1. **Fetch user**: Get user record from database
966
- 2. **Verify password**: Check hash against input
967
- 3. **Create token**: Generate JWT with username in `"sub"` claim
968
- 4. **Return**: Token for client to store (localStorage, cookies)
969
 
970
- **IRL Example:**
971
- Hotel check-in:
972
- 1. **Guest says**: "I'm John Doe, room 123" (`username`, `password`)
973
- 2. **Clerk checks**: Looks up reservation (`select(User)`)
974
- 3. **ID verification**: Scans driver's license (`verify_password`)
975
- 4. **If wrong**: "Sorry, we have no reservation under that name" (`401`)
976
- 5. **If correct**: Issues room keycard (JWT token) valid for 3 days (`timedelta`)
977
- 6. **Keycard says**: "Bearer" (you must *bear* this card to access your room)
978
 
979
- The token is your keycard—show it at the bar, gym, pool (protected endpoints) to prove you're a guest.
 
980
 
981
- ---
 
 
 
982
 
983
- ## 11️⃣ Student CRUD Operations
984
-
985
- ### **Create Student (Protected)**
986
- ```python
987
- @app.post("/students/", response_model=StudentResponse, status_code=status.HTTP_201_CREATED, tags=["Students"])
988
- async def create_student(
989
- student: StudentCreate,
990
- db: AsyncSession = Depends(get_db),
991
- current_user: User = Depends(get_current_user)
992
- ):
993
- result = await db.execute(select(Student).filter(Student.email == student.email))
994
- if existing_student:
995
- raise HTTPException(status_code=400, detail=f"Student with email {student.email} already exists")
996
-
997
- new_student = Student(**student.model_dump())
998
- db.add(new_student)
999
- await db.commit()
1000
- await db.refresh(new_student)
1001
- return new_student
1002
- ```
1003
-
1004
- **What it is:**
1005
- Creates a new student record (requires authentication).
1006
-
1007
- **What it's used for:**
1008
- - **Authentication**: `Depends(get_current_user)` ensures user is logged in
1009
- - **Email uniqueness**: Prevents duplicate emails
1010
- - **Dict unpacking**: `**student.model_dump()` converts Pydantic model to SQLAlchemy object
1011
- - **Refresh**: Reloads from DB to get `id` and `created_at`
1012
-
1013
- **IRL Example:**
1014
- A school registrar's terminal (requires staff login):
1015
- 1. **Staff badge swipe** (`get_current_user` verifies)
1016
- 2. **Fill form**: New student data entered
1017
- 3. **System checks**: "Email already exists? Show error"
1018
- 4. **If unique**: Student record created, ID assigned (auto-increment)
1019
- 5. **Receipt printed**: Shows full student data with ID and enrollment date
1020
 
1021
- Without badge swipe, the terminal shows "Access Denied."
1022
-
1023
- ---
1024
-
1025
- ### **Get All Students (Paginated)**
1026
- ```python
1027
- @app.get("/students/", response_model=List[StudentResponse], tags=["Students"])
1028
- async def get_all_students(
1029
- skip: int = 0,
1030
- limit: int = 100,
1031
- db: AsyncSession = Depends(get_db),
1032
- current_user: User = Depends(get_current_user)
1033
- ):
1034
- result = await db.execute(select(Student).offset(skip).limit(limit))
1035
- students = result.scalars().all()
1036
- return students
1037
- ```
1038
 
1039
- **What it is:**
1040
- Returns a list of students with pagination.
1041
 
1042
- **What it's used for:**
1043
- - `skip`: Number of records to skip (for page 2, 3, etc.)
1044
- - `limit`: Max records per page (prevents overwhelming the client)
1045
- - `result.scalars().all()`: Converts result rows into list of `Student` objects
1046
 
1047
- **IRL Example:**
1048
- A school directory on a website:
1049
- - **Page 1**: `skip=0, limit=100` (students 1-100)
1050
- - **Page 2**: `skip=100, limit=100` (students 101-200)
1051
- - **Staff only**: Must be logged in to view (`get_current_user`)
1052
- - **Fast**: Indexes on `id` and `email` make queries speedy
1053
 
1054
- Without pagination, requesting 10,000 students at once could crash the browser.
 
 
1055
 
1056
  ---
1057
 
1058
- ### **Get Single Student**
1059
- ```python
1060
- @app.get("/students/{student_id}", response_model=StudentResponse, tags=["Students"])
1061
- async def get_student(student_id: int, ...):
1062
- result = await db.execute(select(Student).filter(Student.id == student_id))
1063
- student = result.scalar_one_or_none()
1064
-
1065
- if not student:
1066
- raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Student with ID {student_id} not found")
1067
- return student
1068
- ```
1069
-
1070
- **What it is:**
1071
- Fetches one student by ID.
1072
 
1073
- **What it's used for:**
1074
- - `student_id: int`: Path parameter from URL (`/students/42`)
1075
- - `scalar_one_or_none()`: Returns one result or None (not a list)
1076
- - **404 if not found**: Standard "not found" response
1077
 
1078
- **IRL Example:**
1079
- A librarian looking up a book:
1080
- 1. **Patron asks**: "Do you have book #12345?" (`student_id`)
1081
- 2. **Librarian checks catalog** (`select(Student)`)
1082
- 3. **Book not found**: "Sorry, that book isn't in our system" (`404`)
1083
- 4. **Book found**: Hands over the book details
1084
 
1085
- The ID is like a library card number—unique and used for direct lookup.
1086
 
1087
- ---
1088
-
1089
- ### **Update Student (PUT)**
1090
- ```python
1091
- @app.put("/students/{student_id}", response_model=StudentResponse, tags=["Students"])
1092
- async def update_student(
1093
- student_id: int,
1094
- student_update: StudentUpdate,
1095
- ...
1096
- ):
1097
- result = await db.execute(select(Student).filter(Student.id == student_id))
1098
- student = result.scalar_one_or_none()
1099
- if not student:
1100
- raise HTTPException(status_code=404, detail=f"Student with ID {student_id} not found")
1101
-
1102
- update_data = student_update.model_dump(exclude_unset=True)
1103
- if "email" in update_data:
1104
- # Check email uniqueness across other students
1105
- ...
1106
-
1107
- for key, value in update_data.items():
1108
- setattr(student, key, value)
1109
-
1110
- await db.commit()
1111
- await db.refresh(student)
1112
- return student
1113
- ```
1114
 
1115
- **What it is:**
1116
- Full or partial update of a student's information.
1117
 
1118
- **What it's used for:**
1119
- - `exclude_unset=True`: Only updates fields that were actually sent (PATCH behavior)
1120
- - **Email check**: Ensures new email doesn't belong to another student
1121
- - `setattr(student, key, value)`: Dynamically updates attributes
1122
 
1123
- **IRL Example:**
1124
- A student filing a change-of-address form:
1125
- 1. **Submit form**: Only fill "New Address" field (other fields omitted)
1126
- 2. **System checks**: "Is this address used by another student?"
1127
- 3. **Update record**: Changes only the address field (`setattr`)
1128
- 4. **Save**: File updated, timestamp unchanged
1129
- 5. **Confirmation**: Shows full updated record
1130
-
1131
- If you tried to change email to one already in use: "Sorry, that email is taken."
1132
 
1133
  ---
1134
 
1135
- ### **Patch Student Alias**
1136
- ```python
1137
- @app.patch("/students/{student_id}", response_model=StudentResponse, tags=["Students"])
1138
- async def partial_update_student(...):
1139
- return await update_student(student_id, student_update, db, current_user)
1140
- ```
1141
-
1142
- **What it is:**
1143
- A PATCH route that reuses PUT logic.
1144
 
1145
- **What it's used for:**
1146
- - HTTP semantics: PUT = full replace, PATCH = partial update
1147
- - Here both behave identically due to `exclude_unset=True`
1148
- - Could be refactored later to have different validation
1149
 
1150
- **IRL Example:**
1151
- A restaurant with two doors:
1152
- - **Main entrance** (`PUT`): You can enter with full party or alone
1153
- - **Side door** (`PATCH`): Says "Express Entry" but leads to same host stand
1154
- - Both get you to the same table; side door is just for "quick update" perception
1155
 
1156
  ---
1157
 
1158
- ### **Delete Student**
1159
- ```python
1160
- @app.delete("/students/{student_id}", status_code=status.HTTP_204_NO_CONTENT, tags=["Students"])
1161
- async def delete_student(...):
1162
- result = await db.execute(select(Student).filter(Student.id == student_id))
1163
- student = result.scalar_one_or_none()
1164
- if not student:
1165
- raise HTTPException(status_code=404, detail=f"Student with ID {student_id} not found")
1166
-
1167
- await db.delete(student)
1168
- await db.commit()
1169
- return None
1170
- ```
1171
 
1172
- **What it is:**
1173
- Removes a student from the database.
1174
 
1175
- **What it's used for:**
1176
- - **204 No Content**: Successful deletion returns no body (REST best practice)
1177
- - **Idempotent**: Deleting twice is safe (second time returns 404)
1178
- - **Return None**: FastAPI recognizes None + 204 status = empty response
1179
-
1180
- **IRL Example:**
1181
- A school registrar shredding a withdrawn student's file:
1182
- 1. **Confirm ID**: "Withdraw student #42?" (`student_id`)
1183
- 2. **If not found**: "No such student record" (`404`)
1184
- 3. **If found**: Shreds file (`db.delete`), updates master index (`commit`)
1185
- 4. **No receipt**: Just a nod ("204")—nothing to show, job done
1186
-
1187
- HTTP 204 is like a paperless receipt: "Success, but nothing to return."
1188
 
1189
  ---
1190
 
1191
- ## 12️⃣ Health Check & Runner
1192
-
1193
- ### **Health Endpoint**
1194
- ```python
1195
- @app.get("/", tags=["Health"])
1196
- async def root():
1197
- return {
1198
- "status": "healthy",
1199
- "message": "Student Management API is running",
1200
- "version": "1.0.0"
1201
- }
1202
- ```
1203
-
1204
- **What it is:**
1205
- A simple endpoint to check if API is alive.
1206
 
1207
- **What it's used for:**
1208
- - Load balancers ping this to see if instance is healthy
1209
- - Monitoring tools check uptime
1210
- - Humans can `curl http://localhost:8000/` for quick test
1211
-
1212
- **IRL Example:**
1213
- A doctor's stethoscope check. The doctor (load balancer) listens to your heart (`GET /`) and hears:
1214
- - "Status: Healthy!"
1215
- - "Message: All systems operational"
1216
- - "Version: Human v2.0"
1217
-
1218
- If no heartbeat, you're marked "unhealthy" and removed from service.
1219
 
1220
  ---
1221
 
1222
- ### **Application Runner**
1223
- ```python
1224
- if __name__ == "__main__":
1225
- import uvicorn
1226
- uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
1227
- ```
1228
-
1229
- **What it is:**
1230
- Direct execution script for development.
1231
 
1232
- **What it's used for:**
1233
- - `if __name__ == "__main__"`: Only runs when script is executed directly (not imported)
1234
- - `uvicorn.run()`: Starts the ASGI server
1235
- - `"main:app"`: String format for reload mode (module:app instance)
1236
- - `host="0.0.0.0"`: Listens on all network interfaces (accessible from other computers)
1237
- - `port=8000`: HTTP port
1238
- - `reload=True`: **Dev only** - auto-restarts on code changes
1239
-
1240
- **IRL Example:**
1241
- Starting a car:
1242
- - `if __name__ == "__main__"` is the key ignition check (only start if key is turned)
1243
- - `uvicorn.run()` is the engine starter motor
1244
- - `reload=True` is like a mechanic watching your engine and immediately restarting it if you tweak the carburetor (code changes)
1245
- - In production, you remove the mechanic (`reload=False`) for performance
1246
-
1247
- ---
1248
-
1249
- ## 🎯 Key Concepts Summary
1250
-
1251
- | Concept | IRL Analogy | Why It Matters |
1252
- |---------|-------------|----------------|
1253
- | **Async** | Coffee shop mobile orders | Handle many requests without waiting |
1254
- | **SQLAlchemy ORM** | Digital Rolodex | Use Python objects, not raw SQL strings |
1255
- | **Pydantic** | Airport TSA | Validate everything before it enters |
1256
- | **JWT** | Concert wristband | Stateless auth, scalable across servers |
1257
- | **CORS** | Doorbell camera | Block unauthorized websites |
1258
- | **Dependencies** | Dishwashing service | Reusable, clean resource management |
1259
- | **Migrations** | IKEA assembly manual | Version control for database schema |
1260
-
1261
- ---
1262
-
1263
- ## 🔒 Security Checklist
1264
-
1265
- - ✅ **Never hardcode secrets** - Use environment variables
1266
- - ✅ **Never store plain passwords** - Hash with Argon2
1267
- - ✅ **Never trust client input** - Pydantic validates everything
1268
- - ✅ **Protect all routes** - `Depends(get_current_user)` on sensitive endpoints
1269
- - ✅ **Use HTTPS in production** - Prevents token interception
1270
- - ⚠️ **Fix CORS** - Change `["*"]` to specific domains in production
1271
- - ⚠️ **Rate limiting** - Add to prevent brute-force on `/auth/login`
1272
- - ⚠️ **Password reset** - Add flow for forgotten passwords
1273
 
1274
  ---
1275
 
1276
- ## 🚀 Running the Application
1277
-
1278
- **Development:**
1279
- ```bash
1280
- pip install -r requirements.txt
1281
- export DATABASE_URL="postgresql+asyncpg://..."
1282
- export SECRET_KEY="your-secret-key-here"
1283
- python main.py
1284
- ```
1285
-
1286
- **Production (using gunicorn):**
1287
- ```bash
1288
- gunicorn main:app -w 4 -k uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000
1289
- ```
1290
-
1291
- **Access API Docs:**
1292
- Open browser to `http://localhost:8000/docs` for interactive Swagger UI.
1293
-
1294
- ---
1295
 
1296
- **End of explainer. Happy coding!**
 
1
+ # PrepAI Intelligent Interview & Notes Assistant
2
 
3
+ PrepAI is a comprehensive AI-powered platform designed to help users prepare for interviews, generate personalized quizzes, manage study notes, and even participate in real-time mock interviews using conversational AI. It blends multiple modern technologies such as FastAPI, React, ChromaDB, PostgreSQL, Vapi, Groq, and LlamaIndex into a cohesive, production-ready system.
4
 
5
  ---
6
 
7
+ ## 🚀 Overview
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
+ PrepAI enables users to:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
+ - Conduct **AI-powered mock interviews** with real-time voice interaction.
12
+ - Upload PDFs and **chat with notes** using vector search + RAG.
13
+ - Generate **MCQ quizzes** from resumes or study material.
14
+ - Maintain persistent **chat sessions**, interview transcripts, and summaries.
15
+ - Work inside a fully containerized architecture with isolated services.
16
 
17
+ This system is ideal for interview preparation platforms, ed-tech tools, or personal study automation.
 
 
 
 
 
18
 
19
  ---
20
 
21
+ ## 🧩 Architecture
 
 
 
 
 
 
 
22
 
23
+ PrepAI is built with a modular full‑stack architecture:
 
24
 
25
+ ### **Backend (FastAPI)**
 
 
 
26
 
27
+ - JWT Authentication
28
+ - Upload & process PDFs
29
+ - ChromaDB vector store integration
30
+ - Streaming LLM responses
31
+ - Vapi-powered live interview assistant
32
+ - Quiz generation using Groq/OpenAI
33
 
34
+ ### **Frontend (React + TypeScript + Vite)**
35
 
36
+ - User onboarding (Sign In / Sign Up)
37
+ - PDF upload, preview, rename, deletion
38
+ - Interactive note‑chat interface
39
+ - Dashboard with metrics
40
+ - Seamless Vapi interview client
 
 
 
 
41
 
42
+ ### **Database Layer**
 
43
 
44
+ - **PostgreSQL** stores:
 
 
 
45
 
46
+ - Users
47
+ - PDFs
48
+ - Chat sessions
49
+ - Messages
50
+ - Metadata
51
 
52
+ ### **Vector Search Layer**
53
 
54
+ - **ChromaDB** stores:
 
 
 
 
55
 
56
+ - Chunked PDF embeddings
57
+ - User-ingested knowledge
58
 
59
+ ### **AI Services**
 
 
 
60
 
61
+ - **Groq/OpenAI** for LLM responses
62
+ - **SentenceTransformers** for embeddings
63
+ - **Vapi** for real-time voice conversations
64
+ - **LlamaIndex** for PDF parsing & chunking
65
 
66
  ---
67
 
68
+ ## 📦 Directory Structure
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
  ```
71
+ aki-008-prepai/
72
+ ├── Backend/
73
+ │ ├── app/
74
+ │ ├── Dockerfile
75
+ │ └── requirements.txt
76
+
77
+ ├── Frontend/
78
+ │ ├── src/
79
+ │ ├── Dockerfile
80
+ │ └── vite.config.ts
81
+
82
+ ├── docker-compose.yml
83
+ └── RUN.md
 
 
 
 
 
84
  ```
85
 
 
 
 
 
 
 
 
86
  ---
87
 
88
+ ## ⚙️ Installation & Setup
 
 
 
 
 
 
 
 
 
 
89
 
90
+ ### **1. Clone the repository**
 
 
 
91
 
 
 
 
 
 
 
 
 
 
 
92
  ```
93
+ git clone <repo-url>
94
+ cd aki-008-prepai
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
  ```
96
 
97
+ ### **2. Create your `.env` file**
 
98
 
99
+ Provide:
 
 
100
 
101
+ - PostgreSQL credentials
102
+ - Groq API key
103
+ - OpenAI key (if needed)
104
+ - VAPI_PRIVATE_KEY
105
+ - VAPI_PUBLIC_KEY
106
+ - VAPI_ASSISTANT_ID
107
 
108
+ Example:
109
 
 
 
 
 
 
 
110
  ```
111
+ DATABASE_URL=postgresql+asyncpg://postgres:password@dblocalhost:5432/studentdb
112
+ GROQ_API_KEY=your-key
113
+ VAPI_PRIVATE_KEY=your-key
114
+ VAPI_PUBLIC_KEY=your-key
115
+ VAPI_ASSISTANT_ID=your-assistant-id
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
  ```
117
 
118
+ ### **3. Run the system (Docker)**
 
119
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
  ```
121
+ docker-compose up --build
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
  ```
123
 
124
+ Services started:
 
125
 
126
+ - Frontend [http://localhost:5173](http://localhost:5173)
127
+ - Backend [http://localhost:8000](http://localhost:8000)
128
+ - ChromaDB [http://localhost:8080](http://localhost:8080)
129
+ - PostgreSQL [http://localhost:5347](http://localhost:5347)
 
 
130
 
131
+ ### **4. Dev mode (manual)**
 
 
 
 
 
 
132
 
133
+ Backend:
 
 
134
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
  ```
136
+ cd Backend
137
+ python run.py
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
  ```
139
 
140
+ Frontend:
 
141
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
  ```
143
+ cd Frontend
144
+ npm install
145
+ npm run dev
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
  ```
147
 
148
+ ChromaDB:
 
149
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
  ```
151
+ chroma run --host 0.0.0.0 --port 8080 --path ./chroma_store
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152
  ```
153
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
  ---
155
 
156
+ ## 🧪 Key Features in Detail
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
 
158
+ ### **1. PDF Upload & Notes Chat**
 
159
 
160
+ - PDFs are chunked using PyMuPDF + LlamaIndex.
161
+ - Embeddings generated via MiniLM.
162
+ - Chunks stored in ChromaDB.
163
+ - Users can open chats tied to each PDF with full chat history.
 
164
 
165
+ ### **2. AI Interview System**
 
 
 
 
 
 
 
166
 
167
+ - Dynamic prompt generation based on job-role, experience, difficulty.
168
+ - Real-time Vapi-based interview with:
169
 
170
+ - Emotion recognition
171
+ - Adjustable voice
172
+ - Adaptive follow-ups
173
+ - Strict 5-minute flow
174
 
175
+ - Transcripts saved automatically.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
176
 
177
+ ### **3. Quiz Generation**
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
178
 
179
+ From resumes or notes:
 
180
 
181
+ - Strict rules enforced by the SYSTEM_PROMPT
182
+ - Always 10 MCQs with 4 options
183
+ - JSON‑structured output
184
+ - Options + explanations
185
 
186
+ ### **4. Authentication**
 
 
 
 
 
187
 
188
+ - Secure hashing using Argon2
189
+ - JWT tokens
190
+ - Protected routes for all user-specific actions
191
 
192
  ---
193
 
194
+ ## 🛠️ Development Notes
 
 
 
 
 
 
 
 
 
 
 
 
 
195
 
196
+ ### **Backend**
 
 
 
197
 
198
+ - Powered by **FastAPI** with async SQLAlchemy.
199
+ - Auto-table creation on startup.
200
+ - Organized into clear routers: Auth, Notes, Interview, Quiz.
201
+ - Streaming responses for chat.
 
 
202
 
203
+ ### **Frontend**
204
 
205
+ - Built on **React + TypeScript**.
206
+ - Modern UI with Tailwind.
207
+ - Routes include: Home, Dashboard, Notes, Interview.
208
+ - ProtectedRoute ensures authentication.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
209
 
210
+ ### **Docker Setup**
 
211
 
212
+ `docker-compose.yml` orchestrates:
 
 
 
213
 
214
+ - PostgreSQL database
215
+ - ChromaDB vector server
216
+ - Backend (Python)
217
+ - Frontend (Nginx)
 
 
 
 
 
218
 
219
  ---
220
 
221
+ ## 📄 Interview Transcript Storage
 
 
 
 
 
 
 
 
222
 
223
+ During every interview:
 
 
 
224
 
225
+ - All real-time transcripts are appended in `Backend/transcripts/<call_id>.txt`.
226
+ - Summary is appended at end of call.
 
 
 
227
 
228
  ---
229
 
230
+ ## 🚧 Roadmap
 
 
 
 
 
 
 
 
 
 
 
 
231
 
232
+ Future improvements:
 
233
 
234
+ - User analytics dashboard
235
+ - Multi-file knowledge merging
236
+ - Advanced scoring for interview responses
237
+ - Multi-voice model selector
238
+ - Mobile-friendly front-end layout
 
 
 
 
 
 
 
 
239
 
240
  ---
241
 
242
+ ## 🧑‍💻 Contributing
 
 
 
 
 
 
 
 
 
 
 
 
 
 
243
 
244
+ Feel free to open issues or submit pull requests. Contributions are welcome for both frontend and backend.
 
 
 
 
 
 
 
 
 
 
 
245
 
246
  ---
247
 
248
+ ## 📜 License
 
 
 
 
 
 
 
 
249
 
250
+ This project is licensed under your chosen license (MIT recommended).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
251
 
252
  ---
253
 
254
+ ### ❤️ Thank you for using PrepAI!
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
255
 
256
+ If you'd like additional documentation (API reference, UML diagrams, onboarding guide), just ask!