initialize 90-day backend residency vault

This commit is contained in:
kiskaadee committed 2026-06-25 22:03:56 -05:00
1 parent fac7a27cfa
commit 448dbfb51f
27 files changed
+1004 -1

No files matched your search

+1
View File
@@ -0,0 +1 @@
{}
+1
View File
@@ -0,0 +1 @@
{}
+33
View File
@@ -0,0 +1,33 @@
{
"file-explorer": true,
"global-search": true,
"switcher": true,
"graph": true,
"backlink": true,
"canvas": true,
"outgoing-link": true,
"tag-pane": true,
"footnotes": false,
"properties": true,
"page-preview": true,
"daily-notes": true,
"templates": true,
"note-composer": true,
"command-palette": true,
"slash-command": false,
"editor-status": true,
"bookmarks": true,
"markdown-importer": false,
"zk-prefixer": false,
"random-note": false,
"outline": true,
"word-count": true,
"slides": false,
"audio-recorder": false,
"workspaces": false,
"file-recovery": true,
"publish": false,
"sync": true,
"bases": true,
"webviewer": false
}
+198
View File
@@ -0,0 +1,198 @@
{
"main": {
"id": "a1b0176b1ef37617",
"type": "split",
"children": [
{
"id": "8b58fcdf9ad2e9f7",
"type": "tabs",
"children": [
{
"id": "0c25d35aafc48913",
"type": "leaf",
"state": {
"type": "markdown",
"state": {
"file": "ROADMAP.md",
"mode": "source",
"source": false
},
"icon": "lucide-file",
"title": "ROADMAP"
}
}
]
}
],
"direction": "vertical"
},
"left": {
"id": "18590873115420c5",
"type": "split",
"children": [
{
"id": "e7cefb4d332bed01",
"type": "tabs",
"children": [
{
"id": "507412faf2428b1f",
"type": "leaf",
"state": {
"type": "file-explorer",
"state": {
"sortOrder": "alphabetical",
"autoReveal": false
},
"icon": "lucide-folder-closed",
"title": "Files"
}
},
{
"id": "abb9add6358c1d29",
"type": "leaf",
"state": {
"type": "search",
"state": {
"query": "",
"matchingCase": false,
"explainSearch": false,
"collapseAll": false,
"extraContext": false,
"sortOrder": "alphabetical"
},
"icon": "lucide-search",
"title": "Search"
}
},
{
"id": "b14b7b99a72cc73c",
"type": "leaf",
"state": {
"type": "bookmarks",
"state": {},
"icon": "lucide-bookmark",
"title": "Bookmarks"
}
}
]
}
],
"direction": "horizontal",
"width": 300
},
"right": {
"id": "4c611e4a8d3a5aff",
"type": "split",
"children": [
{
"id": "fb107eb5bfebed94",
"type": "tabs",
"children": [
{
"id": "c6ff5e5ca338533a",
"type": "leaf",
"state": {
"type": "backlink",
"state": {
"file": "ROADMAP.md",
"collapseAll": false,
"extraContext": false,
"sortOrder": "alphabetical",
"showSearch": false,
"searchQuery": "",
"backlinkCollapsed": false,
"unlinkedCollapsed": true
},
"icon": "links-coming-in",
"title": "Backlinks for ROADMAP"
}
},
{
"id": "c1cd5b9d9be14866",
"type": "leaf",
"state": {
"type": "outgoing-link",
"state": {
"file": "ROADMAP.md",
"linksCollapsed": false,
"unlinkedCollapsed": true
},
"icon": "links-going-out",
"title": "Outgoing links from ROADMAP"
}
},
{
"id": "41cf0ed6f2c1fdeb",
"type": "leaf",
"state": {
"type": "tag",
"state": {
"sortOrder": "frequency",
"useHierarchy": true,
"showSearch": false,
"searchQuery": ""
},
"icon": "lucide-tags",
"title": "Tags"
}
},
{
"id": "236c47cc706f5b7d",
"type": "leaf",
"state": {
"type": "all-properties",
"state": {
"sortOrder": "frequency",
"showSearch": false,
"searchQuery": ""
},
"icon": "lucide-archive",
"title": "All properties"
}
},
{
"id": "65bbd144811c48e0",
"type": "leaf",
"state": {
"type": "outline",
"state": {
"file": "ROADMAP.md",
"followCursor": false,
"showSearch": false,
"searchQuery": ""
},
"icon": "lucide-list",
"title": "Outline of ROADMAP"
}
}
]
}
],
"direction": "horizontal",
"width": 300,
"collapsed": true
},
"left-ribbon": {
"hiddenItems": {
"switcher:Open quick switcher": false,
"graph:Open graph view": false,
"canvas:Create new canvas": false,
"daily-notes:Open today's daily note": false,
"templates:Insert template": false,
"command-palette:Open command palette": false,
"bases:Create new base": false
}
},
"active": "0c25d35aafc48913",
"lastOpenFiles": [
"README.md",
"journal/2026-06-25.md",
"CURRENT.md",
"ROADMAP.md",
"SKILLS.md",
"todo.md",
"WEEKLY.md",
"knowledge/docker.md",
"knowledge/auth.md"
]
}
+10
View File
@@ -0,0 +1,10 @@
# Current Focus
## Current Objective
Initialize the Development Environment and establish version 1.0 of the Backend Residency Vault.
## Current Blocker
None.
## Next Action
Initialize Python environment using `uv`, set up formatting/linting tools, and Docker Compose for PostgreSQL.
+24 -1
View File
@@ -1 +1,24 @@
# backend-journey # Backend Journey: 90-Day Backend Residency
Welcome to your Backend Residency. This repository is configured as an Obsidian vault to organize your learning path, track progress, maintain a backlog for your flagship project, log interviews, and consolidate your personal backend engineering notes.
## Repository Structure
- [todo.md](/todo.md) — The main checklist representing the core phases, tasks, and exit criteria. (Symlinked to your home directory at `~/todo.md` for quick access!)
- [ROADMAP.md](/ROADMAP.md) — The high-level strategic roadmap with phase details and exit gates.
- [WEEKLY.md](/WEEKLY.md) — Your tactical weekly planning and review document.
- [INTERVIEW.md](/INTERVIEW.md) — Conceptual flashcards and logs of mock/real interviews.
- `project/`
- [TODO.md](/project/TODO.md) — The operational backlog for your flagship backend project.
- `notes/` — Focused study notes mapping to key interview pillars:
- [sql.md](/notes/sql.md) — SQL, indexes, transactions, normalization, joins.
- [auth.md](/notes/auth.md) — JWTs, hashing, authorization, and authentication flows.
- [docker.md](/notes/docker.md) — Containerization basics and multi-stage builds.
- [testing.md](/notes/testing.md) — Unit testing, integration testing, and pytest.
---
## Guidelines for Obsidian Usage
- Open this workspace directory ('/') directly as a Vault in **Obsidian**.
- Use standard markdown links (e.g. `[[ROADMAP]]` or `[[notes/sql]]`) to connect your study materials, daily logs, and project tasks.
- Keep updates concise and version-controlled. Commit your changes at the end of each week.
+143
View File
@@ -0,0 +1,143 @@
# Strategic Roadmap - Backend Residency
This document outlines the milestones and gates of the Backend Residency. Instead of strict dates, it tracks progress using explicit status states, estimated efforts, and verification tests.
---
## 🏁 Flagship Project: Inventory Management API
A production-ready backend for inventory and order management.
- **Key Modules:** Auth & RBAC, Products & Categories, Orders & Transaction safety, Search & Filtering, and logging.
- **Reference Docs:** [[project/README]], [[project/architecture]], [[project/api-design]], [[project/database]].
---
## Milestones
### Milestone 0: Development Environment & Setup
- **Status:** 🟨 In Progress
- **Estimated Effort:** 5–10 hours
- **Tasks:**
- Configure workspace structure & symlink (`~/todo.md`)
- Initialize Python environment using `uv`
- Configure Ruff, mypy, and code formatter
- Setup multi-container Docker Compose file (`FastAPI` & `PostgreSQL`)
- **Acceptance Tests:**
- [ ] Running `docker compose up` starts both FastAPI and PostgreSQL database.
- [ ] Running `curl http://localhost:8000/docs` yields a valid HTML response.
- **Interview Checkpoint:**
- [ ] Why do we use virtual environments (e.g., `uv`)?
- [ ] What is the difference between a Docker image and a Docker container?
- [ ] Why do we use Docker Compose for local development?
---
### Milestone 1: Secure User Registration & CRUD
- **Status:** 🟥 Not Started
- **Estimated Effort:** 15–20 hours
- **Research:**
- Read FastAPI official documentation on path parameters and Pydantic models.
- Read HTTP specifications for Methods and Response Status Codes.
- **Implement:**
- `POST /auth/register` (user creation)
- `GET /users/me` and `PATCH /users/me` profile endpoints
- **Verify:**
- [ ] Test endpoints manually with `curl` and parse response with `jq`.
- [ ] Verify validation errors format matches standard JSON error formats.
- **Acceptance Tests:**
- [ ] Create user through API, fetch details, and verify fields match input payload.
- [ ] Attempting to register a user with invalid email syntax returns `422 Unprocessable Entity`.
- **Interview Checkpoint:**
- [ ] What is the request-response lifecycle?
- [ ] What is the difference between `PUT` and `PATCH`?
- [ ] Why do we use Pydantic for validation and serialization?
---
### Milestone 2: Relational Schema & Persistence (PostgreSQL)
- **Status:** 🟥 Not Started
- **Estimated Effort:** 20–25 hours
- **Research:**
- Read SQLAlchemy documentation on Declarative Mappings and Async Sessions.
- Read Alembic documentation on migration generations.
- **Implement:**
- User and Profile relational model tables.
- DB sessions injection dependencies.
- Initial migration scripts.
- **Verify:**
- [ ] Run raw SQL commands directly inside PostgreSQL client container to verify data fields.
- **Acceptance Tests:**
- [ ] Initialize migration database successfully.
- [ ] Register user, restart the database container, and verify the user still exists (persistence check).
- [ ] Run Alembic downgrade and upgrade successfully without errors.
- **Interview Checkpoint:**
- [ ] What are the ACID properties in databases?
- [ ] What is the difference between an `INNER JOIN` and a `LEFT JOIN`?
- [ ] What is database indexing, and when should you avoid using it?
- [ ] Why do we use migrations instead of executing direct SQL statements against production databases?
---
### Milestone 3: Security & RBAC (Role-Based Access Control)
- **Status:** 🟥 Not Started
- **Estimated Effort:** 25–30 hours
- **Research:**
- Read OAuth2 password flow specifications.
- Read JWT standard specifications (claims, signatures).
- **Implement:**
- Secure `/auth/token` login endpoint generating Access/Refresh tokens.
- Token verification guards and user role decorators (Admin, Staff, Customer).
- **Verify:**
- [ ] Ensure passwords stored in the database are hashed (never plaintext).
- [ ] Verify access tokens expire in 15 minutes and refresh tokens rotate properly.
- **Acceptance Tests:**
- [ ] Attempt to access a protected endpoint without an Authorization header returns `401 Unauthorized`.
- [ ] Attempt to access an Admin resource using a Customer credential returns `403 Forbidden`.
- [ ] Tokens refreshed successfully via HttpOnly cookie endpoints.
- **Interview Checkpoint:**
- [ ] How does JWT authentication work?
- [ ] Why do we use Refresh Tokens, and where should they be stored?
- [ ] What is Role-Based Access Control (RBAC)?
---
### Milestone 4: Product Inventory & Transactions
- **Status:** 🟥 Not Started
- **Estimated Effort:** 25–35 hours
- **Research:**
- Read SQLAlchemy documentation on transactions and concurrency locks.
- **Implement:**
- Product and Category tables.
- Stock control routes.
- Transaction-safe `/orders` processing endpoint.
- **Verify:**
- [ ] Verify query parameters for filtering, pagination, and text search yield the expected subsets.
- **Acceptance Tests:**
- [ ] Place an order for an item: check that stock levels are decremented atomically.
- [ ] Attempt to order an item with quantity exceeding stock level: check that the order is rejected and transaction rolls back.
- [ ] Concurrently place orders to verify stock level never falls below zero.
- **Interview Checkpoint:**
- [ ] What is transaction isolation, and why does it matter?
- [ ] How do you handle database race conditions?
- [ ] What is offset pagination vs keyset pagination?
---
### Milestone 5: Robust Testing, Logging & CI/CD
- **Status:** 🟥 Not Started
- **Estimated Effort:** 20–30 hours
- **Research:**
- Read pytest documentation on fixture scopes and async support.
- Read Nginx/Caddy documentation for reverse proxy configuration.
- **Implement:**
- Full pytest integration test client suite.
- Multistage Dockerfile.
- GitHub Actions testing workflow.
- **Verify:**
- [ ] Verify application tests execute on every push in GitHub.
- **Acceptance Tests:**
- [ ] Test suite executes successfully with >80% code coverage.
- [ ] Production Docker image builds under 200MB.
- **Interview Checkpoint:**
- [ ] What is the difference between unit testing and integration testing?
- [ ] Why do we use fixtures in pytest?
- [ ] What is reverse proxying, and why should you place your backend behind it?
+18
View File
@@ -0,0 +1,18 @@
# Skills Matrix
Use this matrix to track your confidence and interview readiness for key backend technologies. Update this at the end of each milestone review.
| Skill | Confidence | Interview Ready | Linked Notes |
| :--- | :---: | :---: | :--- |
| **Python** | 3/5 | 🟨 | [[knowledge/testing]] |
| **Git & GitHub** | 4/5 | 🟩 | - |
| **FastAPI** | 2/5 | 🟥 | [[knowledge/auth]] |
| **SQL & PostgreSQL** | 2/5 | 🟥 | [[knowledge/sql]] |
| **Docker & Compose** | 2/5 | 🟥 | [[knowledge/docker]] |
| **Testing (pytest)** | 1/5 | 🟥 | [[knowledge/testing]] |
| **JWT & RBAC** | 1/5 | 🟥 | [[knowledge/auth]] |
*Status Legend:*
- 🟥 Not Ready (Cannot explain under interview pressure)
- 🟨 Developing (Can explain core concepts, but need prompts/notes)
- 🟩 Interview Ready (Can explain trade-offs, architecture, and solve issues confidently)
+52
View File
@@ -0,0 +1,52 @@
# Weekly Tactical Plan
This file is updated at the beginning of each week (every Monday) to detail specific focus tasks.
## Current Week: Week 1 (Phase 0)
### Goals
- Set up a clean Python development workspace.
- Learn tmux pane/session management.
- Get comfortable with command-line API queries (`curl`, `jq`).
- Set up a basic `docker-compose.yml` for PostgreSQL and FastAPI.
---
### Daily Schedule
#### Monday
- [ ] Initialize Python environment using `uv`.
- [ ] Set up Ruff for linting and formatting.
- [ ] Set up mypy for type annotations.
#### Tuesday
- [ ] Master basic `tmux` commands (create session, split panes, navigate, copy mode).
- [ ] Practice editing files from terminal and using terminal splits.
#### Wednesday
- [ ] Master `curl` flags: `-X`, `-H`, `-d`, `-i`, `-v`.
- [ ] Install and use `jq` to parse JSON API responses.
#### Thursday
- [ ] Write a basic `docker-compose.yml` defining a PostgreSQL service.
- [ ] Test connection using local tools.
#### Friday
- [ ] Connect FastAPI to PostgreSQL container.
- [ ] Run automated checks and tests.
---
## Weekly Review
### Wins
-
### Blockers / Hurdles
-
### Key Lessons
-
### Focus for Next Week
-
+14
View File
@@ -0,0 +1,14 @@
# ADR 0001: Language Choice (Python)
## Status
Accepted
## Context
We need a backend programming language that optimizes the learning curve and maximizes the likelihood of getting hired quickly. Andres already has familiarity with Python and has explored FastAPI before.
## Decision
Use **Python** as the sole language for this residency.
## Consequences & Trade-offs
- **Pros:** Fast development cycle, lower syntax overhead, Andres already knows it.
- **Cons:** Some enterprise roles prefer Java/C#, but Python still has high demand and allows focusing on core backend concepts instead of syntax.
+14
View File
@@ -0,0 +1,14 @@
# ADR 0002: Backend Framework Choice (FastAPI)
## Status
Accepted
## Context
We need a modern backend web framework with automatic docs, typing support, and dependency injection to build REST APIs efficiently.
## Decision
Use **FastAPI** as the primary backend framework.
## Consequences & Trade-offs
- **Pros:** Automatic OpenAPI/Swagger generation, standard dependency injection, asynchronous support, strong ecosystem integration with Pydantic.
- **Cons:** Less prescriptive structure than Django, requiring us to define our own architectural standards.
+14
View File
@@ -0,0 +1,14 @@
# ADR 0003: Database Engine (PostgreSQL)
## Status
Accepted
## Context
We need a robust, production-grade relational database. SQL databases are highly tested in junior backend interviews.
## Decision
Use **PostgreSQL** instead of SQLite or MongoDB.
## Consequences & Trade-offs
- **Pros:** Full feature set (concurrency, transactions, indexing, jsonb support) reflecting real-world backend jobs.
- **Cons:** Slightly more complex local setup compared to SQLite, which we will mitigate by using Docker Compose.
+25
View File
@@ -0,0 +1,25 @@
# ADR 0004: Project Directory Structure
## Status
Accepted
## Context
A clean, scalable, and maintainable project directory structure is required for our flagship API to emulate production standards.
## Decision
Adopt a modular or layered architecture layout for the source code:
```
src/
├── main.py # App entrypoint & lifespans
├── config.py # Settings and environment config
├── database.py # SQLAlchemy session & engine setup
├── models/ # SQLAlchemy database models
├── schemas/ # Pydantic schemas (requests/responses)
├── routers/ # FastAPI routers (endpoints)
├── services/ # Business logic and database operations
└── core/ # Security, dependencies, middleware
```
## Consequences & Trade-offs
- **Pros:** Distinct separation of concerns (validation, business logic, routing, persistence). Highly readable for interviewers.
- **Cons:** Slightly more boilerplate files to create compared to a single-file API.
+38
View File
@@ -0,0 +1,38 @@
# Interview Prep & Log
Use this file to record technical interview questions, whiteboard tasks, behavioral questions, and areas of improvement discovered during mock or real interviews.
## Core Conceptual Flashcards
### HTTP & REST
- **What is the request-response lifecycle?**
- **Difference between PUT and PATCH?**
- **What is middleware and how is it used in FastAPI?**
### Databases
- **What are ACID properties?**
- **Explain database normalization (1NF, 2NF, 3NF).**
- **What is an index? When should you NOT use an index?**
- **What is the difference between INNER JOIN, LEFT JOIN, and RIGHT JOIN?**
### Security & System Design
- **How does JWT authentication work?**
- **Why do we use refresh tokens, and where should they be stored?**
- **What is RBAC (Role-Based Access Control)?**
---
## Mock & Real Interview Log
### [Date] - [Company Name]
- **Role:** Junior Backend Developer
- **Stage:** (e.g. Phone Screen, Technical, System Design, Behavioral)
- **Questions Asked:**
1.
2.
- **Whiteboard / Live Coding task:**
-
- **Things I couldn't answer or struggled to explain:**
-
- **Follow-up Action Plan:**
-
+13
View File
@@ -0,0 +1,13 @@
# Mistake Log: [Title of Bug/Issue]
## Problem
*Describe the symptom or error message you encountered.*
## Cause
*Explain why the issue occurred (underlying mechanic, code error, or config mismatch).*
## Solution
*Provide the exact fix or corrected code block.*
## How to Avoid It
*What practices, lint rules, tests, or validation checks will prevent this in the future?*
+15
View File
@@ -0,0 +1,15 @@
# Daily Journal: 2026-06-25
## Wins
- Established the core structure of the 90-Day Backend Residency Vault.
- Configured the symlink `~/todo.md` pointing to the main todo list.
- Documented Architecture Decision Records (ADRs) and the Flagship Inventory API's designs (Database, API, and Architecture).
## Mistakes
- Initially created `todo.md` using the artifact directory constraints, corrected to place it in the workspace folder.
## Questions
- None.
## Tomorrow
- Initialize project workspace using `uv`, set up Ruff/mypy, and configure Docker Compose for local PostgreSQL database.
+15
View File
@@ -0,0 +1,15 @@
# Authentication & Authorization Notes
## JWT (JSON Web Tokens)
- A compact, URL-safe means of representing claims to be transferred between two parties.
- Consists of three parts separated by dots: `Header.Payload.Signature`
- **Header:** Algorithm & token type (e.g. HS256, JWT).
- **Payload:** Claims (e.g. user ID, expiration, roles).
- **Signature:** Verifies that the sender of the JWT is who it says it is and ensures the message wasn't changed along the way.
## Session/JWT flow
1. Client logs in with credentials.
2. Server verifies and issues an Access Token (short-lived, e.g. 15m) and a Refresh Token (long-lived, e.g. 7 days).
3. Client stores Refresh Token in a secure, `HttpOnly` cookie and Access Token in memory or storage.
4. Client includes Access Token in the Authorization header (`Bearer <token>`) for protected requests.
5. When Access Token expires, client calls `/refresh` with the Refresh Token to get a new Access Token.
+10
View File
@@ -0,0 +1,10 @@
# Docker & Containerization Notes
## Docker Core Concepts
- **Image:** A read-only template with instructions for creating a Docker container.
- **Container:** A runnable instance of an image. Isolated from other containers and the host.
- **Dockerfile:** A text document containing all the commands a user could call on the command line to assemble an image.
- **Docker Compose:** A tool for defining and running multi-container Docker applications using YAML configuration.
## Multi-stage Builds
- Used to keep final production image sizes small by compiling/building in an initial stage, then copying only the built artifacts into a minimal runtime image.
+16
View File
@@ -0,0 +1,16 @@
# SQL & Relational Databases Notes
## ACID Properties
- **Atomicity:** All operations in a transaction succeed or all fail.
- **Consistency:** Database transitions from one valid state to another.
- **Isolation:** Concurrent transactions don't interfere with each other.
- **Durability:** Once committed, changes survive system failures.
## Indexes
- An index speeds up data retrieval operations (SELECT) at the cost of slower writes (INSERT, UPDATE, DELETE) and extra storage.
- **When to use:** Columns frequently queried in `WHERE` clauses, JOIN keys.
- **When NOT to use:** Columns with low cardinality (e.g. booleans), tables with very few rows, columns frequently updated.
## Joins
- **INNER JOIN:** Returns records with matching values in both tables.
- **LEFT JOIN (or LEFT OUTER JOIN):** Returns all records from the left table, and matching records from the right. If no match, right-side columns are NULL.
+10
View File
@@ -0,0 +1,10 @@
# Testing Notes
## Unit Testing vs. Integration Testing
- **Unit Testing:** Tests individual components (e.g. functions, helper methods) in isolation. External dependencies (like databases or APIs) are mocked.
- **Integration Testing:** Tests how different parts of the system work together (e.g. hitting an endpoint to ensure it writes to a test database and returns the correct response).
## pytest best practices
- Use fixtures (`@pytest.fixture`) for setup and teardown logic (e.g., creating and rolling back database sessions).
- Keep tests fast by using in-memory databases (sqlite) or a separate Postgres test database that gets cleaned/re-seeded before each test.
- Use `pytest-cov` to measure and monitor code coverage.
+35
View File
@@ -0,0 +1,35 @@
# Inventory Management API
A production-ready, high-performance REST API built with FastAPI and PostgreSQL for inventory tracking and transactional order management.
## Features
- **User Authentication & RBAC:** Secure user registration, password hashing (bcrypt), token-based login (OAuth2 + JWT), refresh token rotation via HttpOnly cookies, and strict Role-Based Access Control (Admin, Staff, Customer).
- **Relational Inventory Schema:** Modular schemas handling Categories, Products, and Orders with ACID transactional safety during stock decrements.
- **Search, Filtering, and Pagination:** Limit-offset list query parameters, category filtering, and text-based SKU/name search.
- **Robust Integration Testing:** Over 80% test coverage using pytest with a containerized test database.
- **Deployment-Ready:** Multi-stage production Docker image configuration and automated CI actions via GitHub Actions.
## Tech Stack
- **Language:** Python
- **Framework:** FastAPI
- **Database:** PostgreSQL
- **ORM:** SQLAlchemy (Async)
- **Migrations:** Alembic
- **Testing:** pytest
- **Containerization:** Docker & Docker Compose
- **Linting & Formatting:** Ruff
## Getting Started
### Prerequisites
- Docker & Docker Compose
- Python 3.12+ (if running locally without Docker)
- `uv` (Fast Python package installer and resolver)
### Installation
1. Clone the repository.
2. Spin up the application stack:
```bash
docker compose up --build
```
3. Access the interactive OpenAPI docs at `http://localhost:8000/docs`.
+19
View File
@@ -0,0 +1,19 @@
# Project Sprint Backlog
This is the operational TODO list for your flagship backend project.
## Currently Doing
- [ ] Initialize repository with `uv`
- [ ] Set up Docker Compose for local development (PostgreSQL & FastAPI)
## To Do (Backlog)
- [ ] Implement Users CRUD
- [ ] Implement Password Hashing & JWT Flow
- [ ] Implement Category & Product tables
- [ ] Implement Order placement endpoint with database transactions
- [ ] Add listing filters, sorting, and pagination
- [ ] Write integration tests for API endpoints
- [ ] Add GitHub Actions testing workflow
## Done
- [x] Create project files and folders structure
+33
View File
@@ -0,0 +1,33 @@
# Flagship API Design
## Endpoints Specification
### Authentication
- `POST /auth/register` - Create user.
- `POST /auth/token` - Authenticate user & issue JWT Access & Refresh Tokens.
- `POST /auth/refresh` - Rotate access tokens using HttpOnly Refresh Cookie.
### Users & Profiles
- `GET /users/me` - Fetch own profile.
- `PATCH /users/me` - Update own profile.
- `GET /users` - List all users (Admin only).
### Categories
- `POST /categories` - Create category.
- `GET /categories` - List categories (with pagination).
- `GET /categories/{id}` - Retrieve category detail.
- `PUT /categories/{id}` - Update category.
- `DELETE /categories/{id}` - Delete category.
### Products
- `POST /products` - Create product.
- `GET /products` - List products (with text search, category filters, and pagination).
- `GET /products/{id}` - Retrieve product details.
- `PUT /products/{id}` - Update product attributes.
- `DELETE /products/{id}` - Delete product.
### Orders
- `POST /orders` - Place order (adjusts stock level inside database transaction).
- `GET /orders` - List orders.
- `GET /orders/{id}` - Retrieve order details.
- `PATCH /orders/{id}/status` - Cancel or process order (Admin/Worker only).
+22
View File
@@ -0,0 +1,22 @@
# Flagship Project Architecture
## Name: Inventory Management API
A production-ready backend system for tracking product inventory, handling categories, recording orders, and tracking stock movements with robust logs.
## Core Architectural Layout
The system follows a layered architecture to decouple routing, validation, business rules, and database access.
```mermaid
graph TD
Client[Client / curl] -->|HTTP Request| Routers[FastAPI Routers]
Routers -->|Pydantic Validation| Schemas[Pydantic Schemas]
Routers -->|Service Call| Services[Business Services]
Services -->|Query / Mutate| DB[SQLAlchemy Models]
DB -->|Read/Write| Postgres[(PostgreSQL Database)]
```
## Layers:
1. **Routers (`routers/`)**: Handles HTTP routing, status codes, and security dependency injections.
2. **Schemas (`schemas/`)**: JSON serialization, deserialization, and strict input/output verification.
3. **Services (`services/`)**: Orchestrates business actions, processes transactions, and wraps DB actions.
4. **Models (`models/`)**: Represents relational tables mapped to PostgreSQL.
+48
View File
@@ -0,0 +1,48 @@
# Database Schema Design
## ERD Layout (Entity-Relationship)
```mermaid
erDiagram
USER {
uuid id PK
string email UK
string hashed_password
string role "Admin | Staff | Customer"
boolean is_active
datetime created_at
}
CATEGORY {
int id PK
string name UK
string description
}
PRODUCT {
uuid id PK
string name
string sku UK
string description
decimal price
int stock_level
int category_id FK
}
ORDER {
uuid id PK
uuid user_id FK
string status "Pending | Completed | Cancelled"
decimal total_amount
datetime created_at
}
ORDER_ITEM {
uuid id PK
uuid order_id FK
uuid product_id FK
int quantity
decimal unit_price
}
CATEGORY ||--o{ PRODUCT : contains
USER ||--o{ ORDER : places
ORDER ||--|{ ORDER_ITEM : has
PRODUCT ||--o{ ORDER_ITEM : referenced_by
```
+173
View File
@@ -0,0 +1,173 @@
# Backend Residency Checklist
## Rules
- [ ] One backend framework only (FastAPI).
- [ ] One programming language only (Python).
- [ ] One portfolio project only (Inventory Management API).
- [ ] Every concept learned must appear in the project.
- [ ] No starting new technologies unless required by the roadmap.
- [ ] AI is a mentor, reviewer, and debugger—not the primary implementation tool.
---
## Milestone 0: Development Environment & Setup
- **Status:** 🟨 In Progress
- **Estimated Effort:** 5-10 hours
### Tasks
- [x] Configure workspace directories (`docs/`, `journal/`, `project/`)
- [x] Link main `todo.md` file to `~/todo.md`
- [ ] Initialize Python environment using `uv`
- [ ] Set up Ruff for linting and formatting
- [ ] Set up mypy for type checking
- [ ] Write `docker-compose.yml` defining a PostgreSQL service
### Acceptance Tests
- [ ] Docker compose services launch successfully.
- [ ] FastAPI endpoint returns status `200` at `/docs`.
### Interview Checkpoint
- [ ] Explain virtual environments.
- [ ] Explain Docker image vs container.
- [ ] Explain Docker Compose benefits.
---
## Milestone 1: Secure User Registration & CRUD
- **Status:** 🟥 Not Started
- **Estimated Effort:** 15-20 hours
### Research
- [ ] Read FastAPI official guides on Routing, Dependency Injection, and Pydantic models.
- [ ] Read HTTP status codes guidelines.
### Implement
- [ ] `POST /auth/register` (user registration route)
- [ ] `GET /users/me` (get profile route)
- [ ] `PATCH /users/me` (update profile route)
### Verify
- [ ] Execute curls with incorrect payloads to confirm validation triggers.
- [ ] Verify validation responses return clear field errors.
### Acceptance Tests
- [ ] Register new user, query their profile, and match the return payload fields.
- [ ] Registering with invalid email payload returns HTTP `422`.
### Interview Checkpoint
- [ ] Explain the request-response lifecycle.
- [ ] Difference between `PUT` and `PATCH`.
- [ ] Why do we use Pydantic models?
---
## Milestone 2: Relational Schema & Persistence (PostgreSQL)
- **Status:** 🟥 Not Started
- **Estimated Effort:** 20-25 hours
### Research
- [ ] Read SQLAlchemy documentation on Async Sessions and Declarative Mappings.
- [ ] Read Alembic documentation on migration generations.
### Implement
- [ ] Relational schema models for User & Profile.
- [ ] Alembic migration initialization and initial upgrade.
- [ ] Dependency injection setup for Database session lifecycle management.
### Verify
- [ ] Inspect raw database records in Postgres to confirm indexing configurations.
### Acceptance Tests
- [ ] Run Alembic migrations and verify structural table creations.
- [ ] Register user, restart PostgreSQL service, and ensure user profile persists.
- [ ] Downgrade migrations, check table removal, and re-apply successfully.
### Interview Checkpoint
- [ ] Explain the ACID database properties.
- [ ] Difference between `INNER JOIN` and `LEFT JOIN`.
- [ ] What is database indexing and when do we avoid it?
- [ ] Why do we use migrations instead of directly editing database schemas?
---
## Milestone 3: Security & RBAC (Role-Based Access Control)
- **Status:** 🟥 Not Started
- **Estimated Effort:** 25-30 hours
### Research
- [ ] Read OAuth2 standard guides.
- [ ] Read JWT structures specifications.
### Implement
- [ ] Hashing helper functions.
- [ ] `/auth/token` authentication and JWT output routes.
- [ ] Access/Refresh token rotation flows.
- [ ] Role check route dependencies.
### Verify
- [ ] Check DB data to ensure passwords are hashed.
- [ ] Check token expiration constraints.
### Acceptance Tests
- [ ] Accessing protected profile returns `401 Unauthorized` without a valid token.
- [ ] Querying admin profile with a Customer role returns `403 Forbidden`.
- [ ] Token refresh requests yield rotated tokens.
### Interview Checkpoint
- [ ] How does JWT authentication work?
- [ ] Why do we use Refresh Tokens and where do we store them?
- [ ] What is Role-Based Access Control?
---
## Milestone 4: Product Inventory & Transactions
- **Status:** 🟥 Not Started
- **Estimated Effort:** 25-35 hours
### Research
- [ ] Read SQLAlchemy documentation on transactions.
### Implement
- [ ] Product and Category CRUD endpoints.
- [ ] Transactional order placement logic.
- [ ] Catalog pagination, filtering, and text search rules.
### Verify
- [ ] Check pagination responses to ensure metadata matches returned count.
### Acceptance Tests
- [ ] Order request decrements product stock atomically.
- [ ] Order request for quantities exceeding stock level returns error and rolls back database change.
- [ ] Concurrent checkouts confirm stock levels never drop below zero.
### Interview Checkpoint
- [ ] Explain transaction isolation levels.
- [ ] How do you handle race conditions?
- [ ] Offset vs keyset pagination.
---
## Milestone 5: Robust Testing, Logging & CI/CD
- **Status:** 🟥 Not Started
- **Estimated Effort:** 20-30 hours
### Research
- [ ] Read pytest documentation on async fixtures.
- [ ] Read Nginx/Caddy setup rules.
### Implement
- [ ] Integration testing client setups and route test suites.
- [ ] Structured logging settings.
- [ ] Multi-stage production `Dockerfile` and GitHub Actions pipeline configurations.
### Verify
- [ ] Verify actions launch automatically on code commits.
### Acceptance Tests
- [ ] Test coverage matches or exceeds 80%.
- [ ] Production Docker image size is under 200MB.
### Interview Checkpoint
- [ ] Unit vs Integration testing.
- [ ] Explain the utility of pytest fixtures.
- [ ] What is a reverse proxy?
+10
View File
@@ -0,0 +1,10 @@
(A) Initialize Python environment using uv +Milestone0 @env
(A) Set up Ruff for linting and formatting +Milestone0 @env
(A) Set up mypy for type checking +Milestone0 @env
(A) Write docker-compose.yml defining a PostgreSQL service +Milestone0 @env
(B) Learn path parameters and Pydantic validation +Milestone1 @research
(B) Learn HTTP status codes and REST guidelines +Milestone1 @research
(B) Implement registration endpoint POST /auth/register +Milestone1 @coding
(B) Implement profile retrieval endpoint GET /users/me +Milestone1 @coding
(B) Implement profile update endpoint PATCH /users/me +Milestone1 @coding
(C) Write basic endpoints verification tests +Milestone1 @testing