fast api (https://chatgpt.com/c/694efe2a-8010-8323-af76-bc0187aaebfe)
π§ BIG PICTURE (IMPORTANT FIRST)
In a FastAPI + Database project, files are separated like this:
| File | Role | Real-world analogy |
|---|---|---|
database.py | Connects to DB | Phone call connection |
models.py | Database tables | Excel sheets |
schemas.py | Data validation | Form checker |
main.py | API logic | Office manager |
1️⃣ database.py — Database Connection Layer
π Purpose (Why this file exists)
-
Connects your app to the database
-
Creates a session to talk to DB
-
One place to change DB (SQLite → PostgreSQL)
Think of this as “opening a phone line” to the database.
✅ Code (Revisited)
πΉ What this means
-
SQLite database file →
users.db -
./means current folder -
No server needed (good for learning)
πΉ Why this line is important
-
engine= main connection object -
check_same_thread=False→ required for SQLite + FastAPI
πΉ Session = DB conversation
-
Every API request uses one session
-
Safely opens & closes DB connection
πΉ This is SUPER IMPORTANT
-
All database tables inherit from
Base -
SQLAlchemy uses it to create tables
π§ Mental Model
2️⃣ models.py — Database Tables (Actual Storage)
π Purpose
-
Defines what data is stored
-
Maps Python class → DB table
-
Persistent data (saved forever)
Think: Excel sheet with columns
✅ Code Breakdown
πΉ Import tools
-
Column= column in table -
Integer,String= data types -
Base= parent class
πΉ What this does
-
Creates a table named
users -
Table exists physically in DB
πΉ Explanation
-
id→ unique row identifier -
primary_key=True→ unique -
index=True→ faster search
πΉ Why unique?
-
Prevents duplicate users
-
Enforces real-world rule
πΉ VERY IMPORTANT
-
Never store plain passwords
-
Always store hashed password
π§ Mental Model
3️⃣ schemas.py — Validation & Communication Layer
π Purpose
-
Validates incoming data
-
Controls outgoing responses
-
Protects database from bad data
Think: Security guard at office gate
❗ Why not use models directly?
-
Models = database only
-
Schemas = API input/output
FastAPI enforces separation of concerns.
✅ Code Breakdown
πΉ Pydantic
-
Validates input automatically
-
Converts data types
πΉ Why EmailStr?
-
Ensures valid email
-
Auto error if invalid
πΉ Used in login response
FastAPI auto-documents this in Swagger UI
π§ Mental Model
π DATA FLOW (VERY IMPORTANT)
π Signup Request Flow
❌ COMMON BEGINNER MISTAKES (AVOID THESE)
❌ Mixing models & schemas
❌ Storing passwords directly
❌ DB logic in main.py
❌ No validation
Recruiters reject these patterns.
π§ INTERVIEW QUESTION & PERFECT ANSWER
❓ Why do we separate models and schemas?
Answer:
Models define database structure, schemas define data validation and API contracts. This separation improves security, scalability, and maintainability.
π₯ Recruiter-approved answer.
π HOW TO PRACTICE (DO THIS)
πΉ Exercise 1
Add username field:
-
Add in
models.py -
Add in
schemas.py -
Update signup route
πΉ Exercise 2
Create UserResponse schema:
Use it in API response.
π SUMMARY (REMEMBER THIS)
| File | Purpose |
|---|---|
| database.py | DB connection |
| models.py | Tables |
| schemas.py | Validation |
| main.py | API logic |
1️⃣ What engine does (MOST IMPORTANT)
π Code (from database.py)
π§ Think of engine like this:
Engine = Power cable between your app and the database
It does 3 main jobs:
| Job | Meaning |
|---|---|
| Opens connection | Connects app to DB |
| Sends SQL | Runs CREATE, INSERT, SELECT |
| Manages DB driver | SQLite / Postgres / MySQL |
π Without engine → no database access
❓ Why we need engine only once?
-
Creating engine is expensive
-
One engine is reused everywhere
-
Industry best practice
π Where engine is used?
π This tells SQLAlchemy:
“Use this engine to create tables in DB”
π§ Mental Model
2️⃣ What SessionLocal is (VERY IMPORTANT)
π Code
π§ Think of Session like this:
Session = Temporary conversation with database
Every time:
-
User signs up
-
User logs in
-
Data is read or written
π A session is created, used, then closed
π Why NOT use engine directly?
Because:
-
Engine = low-level
-
Session = safe + transactional
Session handles:
-
Rollback on error
-
Commit on success
-
Clean close
π Session lifecycle
π§ Mental Model
3️⃣ How data is saved (STEP-BY-STEP)
Let’s say a user signs up π
πΉ Step 1: User sends data
πΉ Step 2: FastAPI validates data (schemas)
If invalid ❌ → request rejected automatically
πΉ Step 3: API opens DB session
π Now app can talk to DB
πΉ Step 4: Create User object (model)
π§ This is NOT saved yet
πΉ Step 5: Add to session
Think:
“Keep this data ready to save”
πΉ Step 6: Commit (SAVE)
π₯ THIS IS THE MOST IMPORTANT LINE
Without commit() → nothing is saved
πΉ Step 7: Close session
Database conversation ends safely
π§ Full Save Flow (MEMORIZE THIS)
4️⃣ How Signup stores user in DB (REAL CODE FLOW)
π Signup endpoint (simplified)
π What Depends(get_db) does
This means:
-
Open session
-
Give it to API
-
Close automatically after request
π₯ This is professional FastAPI pattern
π§ Mental Model (IMPORTANT)
| Component | Role |
|---|---|
| engine | DB power |
| SessionLocal | DB conversation |
| Model | Table structure |
| Schema | Validation |
| commit | Save permanently |
❌ COMMON BEGINNER MISTAKES (YOU WILL AVOID)
❌ Forgetting db.commit()
❌ Writing DB code without session
❌ Mixing schema & model
❌ Creating engine inside API
You are already ahead π
π FASTAPI BACKEND DEVELOPER – JOB CHEAT SHEET
π― What Recruiters EXPECT (Reality)
They test 3 things:
1️⃣ Can you build APIs correctly
2️⃣ Can you secure them
3️⃣ Can you work with databases
π§± 1. FASTAPI CORE (MUST KNOW)
✅ Create App
✅ Run Server
✅ Basic Route
✅ Path & Query Params
π§ Interview Line
“FastAPI is async-first, type-safe, and auto-generates OpenAPI docs.”
π 2. AUTHENTICATION (VERY IMPORTANT)
Password Hashing
JWT Token
Protected Route
❗ Never store plain passwords
❗ Never expose secret key
π§ Interview Line
“I use JWT with role-based access and dependency injection.”
π️ 3. DATABASE (SQLALCHEMY)
Engine & Session
Model
Save Data
Query Data
π§ Interview Line
“I use SQLAlchemy ORM with proper session handling.”
π¦ 4. SCHEMAS (Pydantic)
❗ Models ≠ Schemas
-
Models → DB
-
Schemas → Validation
π§ Interview Line
“Schemas ensure validation and protect database integrity.”
π 5. CRUD TEMPLATE (VERY COMMON)
⚙️ 6. DEPENDENCY INJECTION (KEY FEATURE)
π§ Interview Line
“Dependencies make code reusable and testable.”
π 7. ERROR HANDLING
HTTP Codes to Remember
| Code | Meaning |
|---|---|
| 200 | OK |
| 201 | Created |
| 400 | Bad Request |
| 401 | Unauthorized |
| 403 | Forbidden |
| 404 | Not Found |
| 500 | Server Error |
π§ͺ 8. TESTING (BONUS BUT POWERFUL)
π³ 9. DEPLOYMENT BASICS
Dockerfile (Minimal)
π§ 10. COMMON INTERVIEW QUESTIONS (WITH SHORT ANSWERS)
❓ FastAPI vs Flask?
FastAPI is faster, async, type-safe, and auto-documented.
❓ Why JWT?
Stateless authentication suitable for scalable systems.
❓ SQLite vs PostgreSQL?
SQLite for dev, PostgreSQL for production.
❓ How to protect admin routes?
Role-based JWT + dependency checks.
Comments
Post a Comment