aki-008 commited on
Commit
88e511a
·
1 Parent(s): 70060bb

chore: backend setup

Browse files
.gitignore ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[codz]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py.cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ # Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ # poetry.lock
109
+ # poetry.toml
110
+
111
+ # pdm
112
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
113
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
114
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
115
+ # pdm.lock
116
+ # pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # pixi
121
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
122
+ # pixi.lock
123
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
124
+ # in the .venv directory. It is recommended not to include this directory in version control.
125
+ .pixi
126
+
127
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
128
+ __pypackages__/
129
+
130
+ # Celery stuff
131
+ celerybeat-schedule
132
+ celerybeat.pid
133
+
134
+ # Redis
135
+ *.rdb
136
+ *.aof
137
+ *.pid
138
+
139
+ # RabbitMQ
140
+ mnesia/
141
+ rabbitmq/
142
+ rabbitmq-data/
143
+
144
+ # ActiveMQ
145
+ activemq-data/
146
+
147
+ # SageMath parsed files
148
+ *.sage.py
149
+
150
+ # Environments
151
+ .env
152
+ .envrc
153
+ .venv
154
+ env/
155
+ venv/
156
+ ENV/
157
+ env.bak/
158
+ venv.bak/
159
+
160
+ # Spyder project settings
161
+ .spyderproject
162
+ .spyproject
163
+
164
+ # Rope project settings
165
+ .ropeproject
166
+
167
+ # mkdocs documentation
168
+ /site
169
+
170
+ # mypy
171
+ .mypy_cache/
172
+ .dmypy.json
173
+ dmypy.json
174
+
175
+ # Pyre type checker
176
+ .pyre/
177
+
178
+ # pytype static type analyzer
179
+ .pytype/
180
+
181
+ # Cython debug symbols
182
+ cython_debug/
183
+
184
+ # PyCharm
185
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
186
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
187
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
188
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
189
+ # .idea/
190
+
191
+ # Abstra
192
+ # Abstra is an AI-powered process automation framework.
193
+ # Ignore directories containing user credentials, local state, and settings.
194
+ # Learn more at https://abstra.io/docs
195
+ .abstra/
196
+
197
+ # Visual Studio Code
198
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
199
+ # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
200
+ # and can be added to the global gitignore or merged into this file. However, if you prefer,
201
+ # you could uncomment the following to ignore the entire vscode folder
202
+ # .vscode/
203
+
204
+ # Ruff stuff:
205
+ .ruff_cache/
206
+
207
+ # PyPI configuration file
208
+ .pypirc
209
+
210
+ # Marimo
211
+ marimo/_static/
212
+ marimo/_lsp/
213
+ __marimo__/
214
+
215
+ # Streamlit
216
+ .streamlit/secrets.toml
217
+
218
+ playground/psql_driver.ipynb
.pre-commit-config.yaml ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ repos:
2
+ # 1️⃣ Commit message enforcement (Conventional Commits)
3
+ - repo: https://github.com/commitizen-tools/commitizen
4
+ rev: v4.8.3
5
+ hooks:
6
+ - id: commitizen
7
+ language_version: "python3.12"
8
+ stages: ["commit-msg"]
9
+
10
+ # 2️⃣ General file hygiene & oops prevention
11
+ - repo: https://github.com/pre-commit/pre-commit-hooks
12
+ rev: v5.0.0
13
+ hooks:
14
+ - id: trailing-whitespace # Remove trailing spaces
15
+ - id: end-of-file-fixer # Ensure single newline at EOF
16
+ - id: check-yaml # Validate YAML syntax
17
+ - id: check-added-large-files # Prevent committing huge files
18
+ - id: check-merge-conflict # Prevent unresolved merge conflicts
19
+ - id: debug-statements # Detect print() & pdb.set_trace()
20
+
21
+ # 3️⃣ Python linting & formatting (Ruff)
22
+ - repo: https://github.com/astral-sh/ruff-pre-commit
23
+ rev: v0.12.8
24
+ hooks:
25
+ - id: ruff
26
+ args: [--fix] # Auto-fix lint issues
27
+ - id: ruff-format # Format code
28
+
29
+ # 4️⃣ Static type checking
30
+ - repo: https://github.com/pre-commit/mirrors-mypy
31
+ rev: v1.17.1
32
+ hooks:
33
+ - id: mypy
34
+
35
+ # 5️⃣ Security scanning (Bandit for Python)
36
+ - repo: https://github.com/PyCQA/bandit
37
+ rev: 1.8.6
38
+ hooks:
39
+ - id: bandit
40
+ args: ["-ll"] # Run in high severity mode
41
+
42
+ # 6️⃣ Secret detection (detect-secrets)
43
+ - repo: https://github.com/Yelp/detect-secrets
44
+ rev: v1.5.0
45
+ hooks:
46
+ - id: detect-secrets
47
+ args: ["--baseline", "linter/.secrets.baseline"]
48
+
49
+ default_language_version:
50
+ python: python3
51
+
52
+ # Top-level global settings
53
+ exclude: '.*\.csv$' #
Backend/linter/secrets.baseline ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "version": "1.5.0",
3
+ "plugins_used": [
4
+ {
5
+ "name": "ArtifactoryDetector"
6
+ },
7
+ {
8
+ "name": "AWSKeyDetector"
9
+ },
10
+ {
11
+ "name": "AzureStorageKeyDetector"
12
+ },
13
+ {
14
+ "name": "Base64HighEntropyString",
15
+ "limit": 4.5
16
+ },
17
+ {
18
+ "name": "BasicAuthDetector"
19
+ },
20
+ {
21
+ "name": "CloudantDetector"
22
+ },
23
+ {
24
+ "name": "DiscordBotTokenDetector"
25
+ },
26
+ {
27
+ "name": "GitHubTokenDetector"
28
+ },
29
+ {
30
+ "name": "GitLabTokenDetector"
31
+ },
32
+ {
33
+ "name": "HexHighEntropyString",
34
+ "limit": 3.0
35
+ },
36
+ {
37
+ "name": "IbmCloudIamDetector"
38
+ },
39
+ {
40
+ "name": "IbmCosHmacDetector"
41
+ },
42
+ {
43
+ "name": "IPPublicDetector"
44
+ },
45
+ {
46
+ "name": "JwtTokenDetector"
47
+ },
48
+ {
49
+ "name": "KeywordDetector",
50
+ "keyword_exclude": ""
51
+ },
52
+ {
53
+ "name": "MailchimpDetector"
54
+ },
55
+ {
56
+ "name": "NpmDetector"
57
+ },
58
+ {
59
+ "name": "OpenAIDetector"
60
+ },
61
+ {
62
+ "name": "PrivateKeyDetector"
63
+ },
64
+ {
65
+ "name": "PypiTokenDetector"
66
+ },
67
+ {
68
+ "name": "SendGridDetector"
69
+ },
70
+ {
71
+ "name": "SlackDetector"
72
+ },
73
+ {
74
+ "name": "SoftlayerDetector"
75
+ },
76
+ {
77
+ "name": "SquareOAuthDetector"
78
+ },
79
+ {
80
+ "name": "StripeDetector"
81
+ },
82
+ {
83
+ "name": "TelegramBotTokenDetector"
84
+ },
85
+ {
86
+ "name": "TwilioKeyDetector"
87
+ }
88
+ ],
89
+ "filters_used": [
90
+ {
91
+ "path": "detect_secrets.filters.allowlist.is_line_allowlisted"
92
+ },
93
+ {
94
+ "path": "detect_secrets.filters.common.is_ignored_due_to_verification_policies",
95
+ "min_level": 2
96
+ },
97
+ {
98
+ "path": "detect_secrets.filters.heuristic.is_indirect_reference"
99
+ },
100
+ {
101
+ "path": "detect_secrets.filters.heuristic.is_likely_id_string"
102
+ },
103
+ {
104
+ "path": "detect_secrets.filters.heuristic.is_lock_file"
105
+ },
106
+ {
107
+ "path": "detect_secrets.filters.heuristic.is_not_alphanumeric_string"
108
+ },
109
+ {
110
+ "path": "detect_secrets.filters.heuristic.is_potential_uuid"
111
+ },
112
+ {
113
+ "path": "detect_secrets.filters.heuristic.is_prefixed_with_dollar_sign"
114
+ },
115
+ {
116
+ "path": "detect_secrets.filters.heuristic.is_sequential_string"
117
+ },
118
+ {
119
+ "path": "detect_secrets.filters.heuristic.is_swagger_file"
120
+ },
121
+ {
122
+ "path": "detect_secrets.filters.heuristic.is_templated_secret"
123
+ }
124
+ ],
125
+ "results": {},
126
+ "generated_at": "2025-08-09T16:49:45Z"
127
+ }
Backend/src/__init__.py ADDED
File without changes
Backend/src/config.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from pydantic_settings import BaseSettings
3
+
4
+ class Settings(BaseSettings):
5
+ DATABASE_URL: str = os.getenv(
6
+ "DATABASE_URL",
7
+ "postgresql+asyncpg://postgres:690869@172.26.157.164:5432/studentdb"
8
+ )
9
+
10
+ # Security
11
+ SECRET_KEY: str = os.getenv("SECRET_KEY", "production")
12
+ ALGORITHM: str = "HS256"
13
+ ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
14
+
15
+ # Application
16
+ APP_NAME: str = "Student Management API"
17
+ APP_VERSION: str = "1.0.0"
18
+ APP_DESCRIPTION: str = "FastAPI + PostgreSQL with SQLAlchemy async"
19
+
20
+ # CORS
21
+ CORS_ORIGINS: list = ["*"]
22
+
23
+ class Config:
24
+ env_file = ".env"
25
+ case_sensitive = True
26
+
27
+ settings = Settings()
Backend/src/db/__init__.py ADDED
File without changes
Backend/src/db/client.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
2
+ from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
3
+ from datetime import datetime
4
+ from src.config import settings
5
+
6
+
7
+ engine = create_async_engine(settings.DATABASE_URL, echo=True)
8
+
9
+ async_session_maker = async_sessionmaker(engine, expire_on_commit=False)
10
+
11
+ class Base(DeclarativeBase):
12
+ pass
13
+
14
+ async def get_db():
15
+ async with async_session_maker() as session:
16
+ try:
17
+ yield session
18
+ await session.commit()
19
+ except Exception:
20
+ await session.rollback()
21
+ raise
22
+ finally:
23
+ await session.close()
24
+
Backend/src/db/models.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from sqlalchemy import String
2
+ from sqlalchemy.orm import Mapped, mapped_column
3
+ from datetime import datetime
4
+ from db.client import Base
5
+
Backend/src/main.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI
2
+ from fastapi.middleware.cors import CORSMiddleware
3
+ from contextlib import asynccontextmanager
4
+ from datetime import datetime
5
+
6
+
7
+
8
+
9
+ # @asynccontextmanager
10
+ # async def lifespan(app: FastAPI):
11
+ # print("server starting", datetime.now())
12
+ # print("creating tables if they dont exist....")
13
+ # async with engine
14
+
15
+ # app = FastAPI(lifespan=lifespan)
16
+ # app.include_router(api_router)
17
+ app.add_middleware(
18
+ CORSMiddleware,
19
+ allow_origins=["*"],
20
+ allow_credentials=True,
21
+ allow_methods=["*"],
22
+ allow_headers=["*"],
23
+ )
24
+ @app.get("/", tags=["Health"])
25
+ async def root():
26
+ """Health check endpoint"""
27
+ return {
28
+ "status": "healthy",
29
+ "message": "Student Management API is running",
30
+ "version": "1.0.0"
31
+ }
Readme.md ADDED
@@ -0,0 +1,1296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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!**
reamde.md DELETED
@@ -1 +0,0 @@
1
- first commit
 
 
requiremnts.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ fastapi==0.109.0
2
+ uvicorn[standard]==0.27.0
3
+ sqlalchemy==2.0.25
4
+ asyncpg
5
+ pydantic==2.5.3
6
+ pydantic-settings==2.1.0
7
+ python-multipart==0.0.6
8
+ python-jose[cryptography]==3.3.0
9
+ passlib[bcrypt]==1.7.4
10
+ alembic==1.13.1
11
+ python-dotenv==1.0.0
test/db CRUD.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ from datetime import datetime
3
+ from sqlalchemy import String, Integer, DateTime
4
+ from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession
5
+ from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
6
+ from sqlalchemy import select
7
+
8
+ DATABASE_URL = "postgresql+asyncpg://postgres:690869@localhost:5432/studentdb"
9
+
10
+ engine = create_async_engine(DATABASE_URL, echo=True)
11
+ async_session = async_sessionmaker(engine, expire_on_commit=False)
12
+
13
+ class Base(DeclarativeBase):
14
+ pass
15
+
16
+ class Student(Base):
17
+ __tablename__ = "students"
18
+
19
+ id: Mapped[int] = mapped_column(primary_key=True)
20
+ name: Mapped[str] = mapped_column(String(100))
21
+ email: Mapped[str] = mapped_column(String(100))
22
+ age: Mapped[int]
23
+ grade: Mapped[str] = mapped_column(String(5))
24
+ created_at : Mapped[datetime] = mapped_column(default=datetime.utcnow)
25
+
26
+ async def create_table():
27
+ async with engine.begin() as conn:
28
+ await conn.run_sync(Base.metadata.create_all)
29
+ print('Tables created successfully !')
30
+
31
+ async def add_student(name:str, email: str, age: int, grade: str):
32
+ async with async_session() as session:
33
+ async with session.begin():
34
+ student = Student( name = name, email= email, age=age, grade=grade)
35
+ session.add(student)
36
+ print(f"added student{name}")
37
+
38
+ async def list_students():
39
+ async with async_session() as session:
40
+ result = await session.execute(select(Student))
41
+ students = result.scalars().all()
42
+
43
+ for s in students:
44
+ print(f" - {s.id}: {s.name}, {s.email}, Grade: {s.grade}, {s.age}")
45
+
46
+ async def update_student(student_id: int, new_name: str = None, new_age : int = None, new_grade : int = None ):
47
+ async with async_session() as session:
48
+ async with session.begin():
49
+ student = await session.get(Student, student_id)
50
+ if not student:
51
+ print(f"❌ Student with id {student_id} not found.")
52
+ return
53
+ if new_name:
54
+ student.name = new_name
55
+ if new_grade:
56
+ student.grade = new_grade
57
+ if new_age:
58
+ student.age = new_age
59
+
60
+ # await session.commit() ## no need
61
+ print(f"✏️ Updated student ID {student_id}")
62
+
63
+ async def delete_student(student_id: int):
64
+ async with async_session() as session:
65
+ async with session.begin():
66
+ student = await session.get(Student, student_id)
67
+ if not student:
68
+ print(f"❌ Student with id {student_id} not found.")
69
+ return
70
+
71
+ await session.delete(student)
72
+ # await session.commit() ## no need
73
+ print(f"🗑️ Deleted student ID {student_id}")
74
+
75
+
76
+ async def main():
77
+ await create_table()
78
+ await add_student("Akshat Mehta", "akshat@example.com", 21, "A+")
79
+ await add_student("Nikhil Sharma", "nikhil@example.com", 22, "B")
80
+ await list_students()
81
+
82
+ await update_student(1, new_age=52)
83
+ await delete_student(2)
84
+ print('-'*100)
85
+ await list_students()
86
+
87
+ if __name__ == "__main__":
88
+ asyncio.run(main())
test/db_fastapi_CRUD.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ from typing import List, Optional
3
+ from contextlib import asynccontextmanager
4
+ from datetime import datetime
5
+ from fastapi import FastAPI, HTTPException, status
6
+ from sqlalchemy import String, Integer, DateTime, select
7
+ from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession
8
+ from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
9
+ from pydantic import BaseModel, ConfigDict
10
+
11
+
12
+ DATABASE_URL = "postgresql+asyncpg://postgres:690869@localhost:5432/studentdb"
13
+
14
+ engine = create_async_engine(DATABASE_URL, echo=True)
15
+ async_session = async_sessionmaker(engine, expire_on_commit=False)
16
+
17
+ class Base(DeclarativeBase):
18
+ pass
19
+
20
+ class Student(Base):
21
+ __tablename__ = "students"
22
+
23
+ id: Mapped[int] = mapped_column(primary_key=True)
24
+ name: Mapped[str] = mapped_column(String(100))
25
+ email: Mapped[str] = mapped_column(String(100))
26
+ age: Mapped[int]
27
+ grade: Mapped[str] = mapped_column(String(5))
28
+ created_at : Mapped[datetime] = mapped_column(default=datetime.utcnow)
29
+
30
+ class StudentCreate(BaseModel):
31
+ name: str
32
+ email: str
33
+ age: int
34
+ grade: str
35
+
36
+ class StudentUpdate(BaseModel):
37
+ name: Optional[str] = None
38
+ email: Optional[str] = None
39
+ age: Optional[int] = None
40
+ grade: Optional[str] = None
41
+
42
+ class StudentOut(BaseModel):
43
+ id: int
44
+ name: str
45
+ email: str
46
+ age: int
47
+ grade: str
48
+ created_at: datetime
49
+
50
+ model_config = ConfigDict(from_attributes=True)
51
+
52
+
53
+
54
+ @asynccontextmanager
55
+ async def lifespan(app: FastAPI):
56
+ async with engine.begin() as conn:
57
+ await conn.run_sync(Base.metadata.create_all)
58
+ print("Tables created !!!!")
59
+ yield
60
+ await engine.dispose()
61
+ print("🔻 Database connection closed.")
62
+
63
+ app = FastAPI(title="Async student CRUD API", lifespan=lifespan)
64
+
65
+ @app.post("/students/", response_model=StudentOut, status_code=status.HTTP_201_CREATED)
66
+ async def create_student(student: StudentCreate):
67
+ async with async_session() as session:
68
+ async with session.begin():
69
+ student = Student(**student.model_dump())
70
+ session.add(student)
71
+ await session.refresh(student)
72
+ return student
73
+
74
+ @app.get("/students/", response_model=List[StudentOut])
75
+ async def list_students():
76
+ async with async_session() as session:
77
+ result = await session.execute(select(Student))
78
+ students = result.scalars().all()
79
+ return students
80
+
81
+ @app.get("/students/{id}", response_model=StudentOut)
82
+ async def get_student(id: int):
83
+ async with async_session() as session:
84
+ student = await session.get(Student, id)
85
+ if not student:
86
+ raise HTTPException(status_code=404, detail="Student not found")
87
+ return student
88
+
89
+ @app.put("/students/{id}/", response_model=StudentOut)
90
+ async def update_student(id: int, update_data: StudentUpdate):
91
+ async with async_session() as session:
92
+ async with session.begin():
93
+ student = await session.get(Student, id)
94
+ if not student:
95
+ raise HTTPException(status_code=404, detail="student not found")
96
+
97
+ update_dict = update_data.model_dump(exclude_unset=True)
98
+ for key , value in update_dict.items():
99
+ setattr(student, key , value)
100
+
101
+ await session.refresh(student)
102
+ return student
103
+
104
+ @app.delete("/students/{id}", status_code=status.HTTP_204_NO_CONTENT)
105
+ async def delete_student(id: int):
106
+ async with async_session() as session:
107
+ async with session.begin():
108
+ student = await session.get(Student, id)
109
+ if not student:
110
+ raise HTTPException(status_code=404, detail="student not found")
111
+ await session.delete(student)
112
+ return None
113
+
114
+
115
+ # async def main():
116
+ # # await create_table()
117
+ # await add_student("Akshat Mehta", "akshat@example.com", 21, "A+")
118
+ # await add_student("Nikhil Sharma", "nikhil@example.com", 22, "B")
119
+ # await list_students()
120
+
121
+ # await update_student(1, new_age=52)
122
+ # await delete_student(2)
123
+ # print('-'*100)
124
+ # await list_students()
125
+
126
+ # if __name__ == "__main__":
127
+ # asyncio.run(main())
test/main.py ADDED
@@ -0,0 +1,445 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ FastAPI + PostgreSQL Student Management System
3
+ Complete async implementation with SQLAlchemy, authentication, and validation
4
+
5
+ Requirements:
6
+ pip install fastapi uvicorn sqlalchemy asyncpg psycopg2-binary python-jose[cryptography] passlib[bcrypt] python-multipart
7
+ """
8
+
9
+ from fastapi import FastAPI, HTTPException, Depends, status
10
+ from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
11
+ from fastapi.middleware.cors import CORSMiddleware
12
+ from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
13
+ from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
14
+ from sqlalchemy import select, String
15
+ from pydantic import BaseModel, EmailStr, Field, field_validator, ConfigDict
16
+ from typing import Optional, List
17
+ from datetime import datetime, timedelta
18
+ from jose import JWTError, jwt
19
+ from passlib.context import CryptContext
20
+ import os
21
+ from contextlib import asynccontextmanager
22
+ # ======================== CONFIGURATION ========================
23
+ DATABASE_URL = os.getenv(
24
+ "DATABASE_URL",
25
+ "postgresql+asyncpg://postgres:690869@172.26.157.164:5432/studentdb"
26
+ )
27
+ SECRET_KEY = os.getenv("SECRET_KEY", "production")
28
+ ALGORITHM = "HS256"
29
+ ACCESS_TOKEN_EXPIRE_MINUTES = 30
30
+
31
+ # ======================== DATABASE SETUP ========================
32
+ engine = create_async_engine(DATABASE_URL, echo=True)
33
+ async_session_maker = async_sessionmaker(engine, expire_on_commit=False)
34
+
35
+ class Base(DeclarativeBase):
36
+ pass
37
+
38
+ class Student(Base):
39
+ __tablename__ = "students"
40
+
41
+ id: Mapped[int] = mapped_column(primary_key=True, index=True)
42
+ name: Mapped[str] = mapped_column(String(100))
43
+ email: Mapped[str] = mapped_column(String(100), unique=True, index=True)
44
+ age: Mapped[int]
45
+ grade: Mapped[str] = mapped_column(String(5))
46
+ created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
47
+
48
+ class User(Base):
49
+ __tablename__ = "users"
50
+
51
+ id: Mapped[int] = mapped_column(primary_key=True, index=True)
52
+ username: Mapped[str] = mapped_column(String(50), unique=True, index=True)
53
+ hashed_password: Mapped[str] = mapped_column(String(255))
54
+
55
+ # ======================== PYDANTIC MODELS ========================
56
+ class StudentBase(BaseModel):
57
+ name: str = Field(..., min_length=2, max_length=100, description="Student full name")
58
+ email: EmailStr = Field(..., description="Student email address")
59
+ age: int = Field(..., ge=5, le=100, description="Student age (5-100)")
60
+ grade: str = Field(..., pattern="^[A-F][+-]?$", description="Grade (A-F with optional + or -)")
61
+
62
+ @field_validator('name')
63
+ def validate_name(cls, v):
64
+ if not v.strip():
65
+ raise ValueError('Name cannot be empty or just whitespace')
66
+ return v.strip()
67
+
68
+ @field_validator('grade')
69
+ def validate_grade(cls, v):
70
+ v = v.upper()
71
+ if v not in ['A+', 'A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D', 'D-', 'F']:
72
+ raise ValueError('Invalid grade format')
73
+ return v
74
+
75
+ class StudentCreate(StudentBase):
76
+ pass
77
+
78
+ class StudentUpdate(BaseModel):
79
+ name: Optional[str] = Field(None, min_length=2, max_length=100)
80
+ email: Optional[EmailStr] = None
81
+ age: Optional[int] = Field(None, ge=5, le=100)
82
+ grade: Optional[str] = Field(None, pattern="^[A-F][+-]?$")
83
+
84
+ @field_validator('grade')
85
+ def validate_grade(cls, v):
86
+ if v is not None:
87
+ v = v.upper()
88
+ if v not in ['A+', 'A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D', 'D-', 'F']:
89
+ raise ValueError('Invalid grade format')
90
+ return v
91
+
92
+ class StudentResponse(StudentBase):
93
+ id: int
94
+ created_at: datetime
95
+
96
+ model_config = ConfigDict(from_attributes=True)
97
+
98
+ class UserCreate(BaseModel):
99
+ username: str = Field(..., min_length=3, max_length=50)
100
+ password: str = Field(..., min_length=6, max_length=72)
101
+
102
+ @field_validator('password')
103
+ def validate_password(cls, v):
104
+ if len(v.encode('utf-8')) > 72:
105
+ raise ValueError('Password cannot exceed 72 bytes')
106
+ return v
107
+
108
+ class Token(BaseModel):
109
+ access_token: str
110
+ token_type: str
111
+
112
+ # ======================== SECURITY ========================
113
+ pwd_context = CryptContext(schemes=["argon2"], deprecated="auto")
114
+ security = HTTPBearer()
115
+
116
+ def verify_password(plain_password: str, hashed_password: str) -> bool:
117
+ # Truncate password to 72 bytes for bcrypt compatibility
118
+ password_bytes = plain_password.encode('utf-8')[:72]
119
+ plain_password_truncated = password_bytes.decode('utf-8', errors='ignore')
120
+ return pwd_context.verify(plain_password_truncated, hashed_password)
121
+
122
+ def get_password_hash(password: str) -> str:
123
+ # Truncate password to 72 bytes for bcrypt compatibility
124
+ password_bytes = password.encode('utf-8')[:72]
125
+ password_truncated = password_bytes.decode('utf-8', errors='ignore')
126
+ return pwd_context.hash(password_truncated)
127
+
128
+ def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
129
+ to_encode = data.copy()
130
+ expire = datetime.utcnow() + (expires_delta or timedelta(minutes=15))
131
+ to_encode.update({"exp": expire})
132
+ encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
133
+ return encoded_jwt
134
+
135
+ async def get_current_user(
136
+ credentials: HTTPAuthorizationCredentials = Depends(security),
137
+ db: AsyncSession = Depends(lambda: async_session_maker())
138
+ ):
139
+ credentials_exception = HTTPException(
140
+ status_code=status.HTTP_401_UNAUTHORIZED,
141
+ detail="Could not validate credentials",
142
+ headers={"WWW-Authenticate": "Bearer"},
143
+ )
144
+ try:
145
+ token = credentials.credentials
146
+ payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
147
+ username: str = payload.get("sub")
148
+ if username is None:
149
+ raise credentials_exception
150
+ except JWTError:
151
+ raise credentials_exception
152
+
153
+ result = await db.execute(select(User).filter(User.username == username))
154
+ user = result.scalar_one_or_none()
155
+ if user is None:
156
+ raise credentials_exception
157
+ return user
158
+
159
+ # ======================== DATABASE DEPENDENCY ========================
160
+ async def get_db():
161
+ async with async_session_maker() as session:
162
+ try:
163
+ yield session
164
+ await session.commit()
165
+ except Exception:
166
+ await session.rollback()
167
+ raise
168
+ finally:
169
+ await session.close()
170
+
171
+ # new on event alternative
172
+
173
+ @asynccontextmanager
174
+ async def lifespan(app: FastAPI):
175
+ print("🏗️ Server starting:", datetime.now())
176
+ print("🔧 Creating tables if they don't exist...")
177
+
178
+ async with engine.begin() as conn:
179
+ await conn.run_sync(Base.metadata.create_all) # Create tables
180
+
181
+ print("✅ Tables ready!")
182
+ yield
183
+ print("🧹 Server shutting down:", datetime.now())
184
+
185
+ # ======================== FASTAPI APP ========================
186
+ app = FastAPI(
187
+ title="Student Management API",
188
+ description="FastAPI + PostgreSQL with SQLAlchemy async",
189
+ version="1.0.0",
190
+ lifespan=lifespan
191
+
192
+ )
193
+
194
+ # CORS Configuration
195
+ app.add_middleware(
196
+ CORSMiddleware,
197
+ allow_origins=["*"], # In production, specify allowed origins
198
+ allow_credentials=True,
199
+ allow_methods=["*"],
200
+ allow_headers=["*"],
201
+ )
202
+
203
+
204
+ # ======================== AUTHENTICATION ROUTES ========================
205
+ @app.post("/auth/register", response_model=dict, tags=["Authentication"])
206
+ async def register(user: UserCreate, db: AsyncSession = Depends(get_db)):
207
+ """Register a new user"""
208
+ try:
209
+ result = await db.execute(select(User).filter(User.username == user.username))
210
+ existing_user = result.scalar_one_or_none()
211
+
212
+ if existing_user:
213
+ raise HTTPException(
214
+ status_code=status.HTTP_400_BAD_REQUEST,
215
+ detail="Username already registered"
216
+ )
217
+
218
+ new_user = User(
219
+ username=user.username,
220
+ hashed_password=get_password_hash(user.password)
221
+ )
222
+ db.add(new_user)
223
+ await db.commit()
224
+
225
+ return {"message": "User registered successfully", "username": user.username}
226
+ except HTTPException:
227
+ raise
228
+ except Exception as e:
229
+ raise HTTPException(
230
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
231
+ detail=f"Registration failed: {str(e)}"
232
+ )
233
+
234
+ @app.post("/auth/login", response_model=Token, tags=["Authentication"])
235
+ async def login(username: str, password: str, db: AsyncSession = Depends(get_db)):
236
+ """Login and get access token"""
237
+ try:
238
+ result = await db.execute(select(User).filter(User.username == username))
239
+ user = result.scalar_one_or_none()
240
+
241
+ if not user or not verify_password(password, user.hashed_password):
242
+ raise HTTPException(
243
+ status_code=status.HTTP_401_UNAUTHORIZED,
244
+ detail="Incorrect username or password",
245
+ headers={"WWW-Authenticate": "Bearer"},
246
+ )
247
+
248
+ access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
249
+ access_token = create_access_token(
250
+ data={"sub": user.username},
251
+ expires_delta=access_token_expires
252
+ )
253
+
254
+ return {"access_token": access_token, "token_type": "bearer"}
255
+ except HTTPException:
256
+ raise
257
+ except Exception as e:
258
+ raise HTTPException(
259
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
260
+ detail=f"Login failed: {str(e)}"
261
+ )
262
+
263
+ # ======================== STUDENT CRUD ROUTES ========================
264
+ @app.post("/students/", response_model=StudentResponse, status_code=status.HTTP_201_CREATED, tags=["Students"])
265
+ async def create_student(
266
+ student: StudentCreate,
267
+ db: AsyncSession = Depends(get_db),
268
+ current_user: User = Depends(get_current_user)
269
+ ):
270
+ """Create a new student (Protected)"""
271
+ try:
272
+ # Check if email already exists
273
+ result = await db.execute(select(Student).filter(Student.email == student.email))
274
+ existing_student = result.scalar_one_or_none()
275
+
276
+ if existing_student:
277
+ raise HTTPException(
278
+ status_code=status.HTTP_400_BAD_REQUEST,
279
+ detail=f"Student with email {student.email} already exists"
280
+ )
281
+
282
+ new_student = Student(**student.model_dump())
283
+ db.add(new_student)
284
+ await db.commit()
285
+ await db.refresh(new_student)
286
+
287
+ return new_student
288
+ except HTTPException:
289
+ raise
290
+ except Exception as e:
291
+ raise HTTPException(
292
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
293
+ detail=f"Failed to create student: {str(e)}"
294
+ )
295
+
296
+ @app.get("/students/", response_model=List[StudentResponse], tags=["Students"])
297
+ async def get_all_students(
298
+ skip: int = 0,
299
+ limit: int = 100,
300
+ db: AsyncSession = Depends(get_db),
301
+ current_user: User = Depends(get_current_user)
302
+ ):
303
+ """Get all students with pagination (Protected)"""
304
+ try:
305
+ result = await db.execute(
306
+ select(Student).offset(skip).limit(limit)
307
+ )
308
+ students = result.scalars().all()
309
+ return students
310
+ except Exception as e:
311
+ raise HTTPException(
312
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
313
+ detail=f"Failed to fetch students: {str(e)}"
314
+ )
315
+
316
+ @app.get("/students/{student_id}", response_model=StudentResponse, tags=["Students"])
317
+ async def get_student(
318
+ student_id: int,
319
+ db: AsyncSession = Depends(get_db),
320
+ current_user: User = Depends(get_current_user)
321
+ ):
322
+ """Get a specific student by ID (Protected)"""
323
+ try:
324
+ result = await db.execute(select(Student).filter(Student.id == student_id))
325
+ student = result.scalar_one_or_none()
326
+
327
+ if not student:
328
+ raise HTTPException(
329
+ status_code=status.HTTP_404_NOT_FOUND,
330
+ detail=f"Student with ID {student_id} not found"
331
+ )
332
+
333
+ return student
334
+ except HTTPException:
335
+ raise
336
+ except Exception as e:
337
+ raise HTTPException(
338
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
339
+ detail=f"Failed to fetch student: {str(e)}"
340
+ )
341
+
342
+ @app.put("/students/{student_id}", response_model=StudentResponse, tags=["Students"])
343
+ async def update_student(
344
+ student_id: int,
345
+ student_update: StudentUpdate,
346
+ db: AsyncSession = Depends(get_db),
347
+ current_user: User = Depends(get_current_user)
348
+ ):
349
+ """Update a student's information (Protected)"""
350
+ try:
351
+ result = await db.execute(select(Student).filter(Student.id == student_id))
352
+ student = result.scalar_one_or_none()
353
+
354
+ if not student:
355
+ raise HTTPException(
356
+ status_code=status.HTTP_404_NOT_FOUND,
357
+ detail=f"Student with ID {student_id} not found"
358
+ )
359
+
360
+ # Update only provided fields
361
+ update_data = student_update.model_dump(exclude_unset=True)
362
+
363
+ # Check email uniqueness if email is being updated
364
+ if "email" in update_data:
365
+ result = await db.execute(
366
+ select(Student).filter(
367
+ Student.email == update_data["email"],
368
+ Student.id != student_id
369
+ )
370
+ )
371
+ existing = result.scalar_one_or_none()
372
+ if existing:
373
+ raise HTTPException(
374
+ status_code=status.HTTP_400_BAD_REQUEST,
375
+ detail=f"Email {update_data['email']} is already in use"
376
+ )
377
+
378
+ for key, value in update_data.items():
379
+ setattr(student, key, value)
380
+
381
+ await db.commit()
382
+ await db.refresh(student)
383
+
384
+ return student
385
+ except HTTPException:
386
+ raise
387
+ except Exception as e:
388
+ raise HTTPException(
389
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
390
+ detail=f"Failed to update student: {str(e)}"
391
+ )
392
+
393
+ @app.patch("/students/{student_id}", response_model=StudentResponse, tags=["Students"])
394
+ async def partial_update_student(
395
+ student_id: int,
396
+ student_update: StudentUpdate,
397
+ db: AsyncSession = Depends(get_db),
398
+ current_user: User = Depends(get_current_user)
399
+ ):
400
+ """Partially update a student (same as PUT for this implementation) (Protected)"""
401
+ return await update_student(student_id, student_update, db, current_user)
402
+
403
+ @app.delete("/students/{student_id}", status_code=status.HTTP_204_NO_CONTENT, tags=["Students"])
404
+ async def delete_student(
405
+ student_id: int,
406
+ db: AsyncSession = Depends(get_db),
407
+ current_user: User = Depends(get_current_user)
408
+ ):
409
+ """Delete a student (Protected)"""
410
+ try:
411
+ result = await db.execute(select(Student).filter(Student.id == student_id))
412
+ student = result.scalar_one_or_none()
413
+
414
+ if not student:
415
+ raise HTTPException(
416
+ status_code=status.HTTP_404_NOT_FOUND,
417
+ detail=f"Student with ID {student_id} not found"
418
+ )
419
+
420
+ await db.delete(student)
421
+ await db.commit()
422
+
423
+ return None
424
+ except HTTPException:
425
+ raise
426
+ except Exception as e:
427
+ raise HTTPException(
428
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
429
+ detail=f"Failed to delete student: {str(e)}"
430
+ )
431
+
432
+ # ======================== HEALTH CHECK ========================
433
+ @app.get("/", tags=["Health"])
434
+ async def root():
435
+ """Health check endpoint"""
436
+ return {
437
+ "status": "healthy",
438
+ "message": "Student Management API is running",
439
+ "version": "1.0.0"
440
+ }
441
+
442
+ # ======================== RUN APPLICATION ========================
443
+ if __name__ == "__main__":
444
+ import uvicorn
445
+ uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
test/test.ipynb ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "d0e4e192",
7
+ "metadata": {},
8
+ "outputs": [],
9
+ "source": [
10
+ "import asyncio\n",
11
+ "from datetime import datetime\n",
12
+ "from sqlalchemy import String, Integer, DateTime\n",
13
+ "from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession\n",
14
+ "from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column\n",
15
+ "from sqlalchemy import select\n",
16
+ "\n",
17
+ "DATABASE_URL = \"postgresql+asyncpg://postgres:690869@localhost:5432/studentdb\"\n",
18
+ "\n",
19
+ "engine = create_async_engine(DATABASE_URL, echo=True)\n",
20
+ "async_session = async_sessionmaker(engine, expire_on_commit=False)\n",
21
+ "\n",
22
+ "# class Base(DeclarativeBase):\n",
23
+ "# pass\n",
24
+ "Base = DeclarativeBase()"
25
+ ]
26
+ },
27
+ {
28
+ "cell_type": "code",
29
+ "execution_count": 4,
30
+ "id": "f2813d66",
31
+ "metadata": {},
32
+ "outputs": [
33
+ {
34
+ "data": {
35
+ "text/plain": [
36
+ "<sqlalchemy.orm.decl_api.DeclarativeBase at 0x7df42272b620>"
37
+ ]
38
+ },
39
+ "execution_count": 4,
40
+ "metadata": {},
41
+ "output_type": "execute_result"
42
+ }
43
+ ],
44
+ "source": [
45
+ "Base\n"
46
+ ]
47
+ },
48
+ {
49
+ "cell_type": "code",
50
+ "execution_count": null,
51
+ "id": "52154570",
52
+ "metadata": {},
53
+ "outputs": [],
54
+ "source": []
55
+ }
56
+ ],
57
+ "metadata": {
58
+ "kernelspec": {
59
+ "display_name": "prep",
60
+ "language": "python",
61
+ "name": "python3"
62
+ },
63
+ "language_info": {
64
+ "codemirror_mode": {
65
+ "name": "ipython",
66
+ "version": 3
67
+ },
68
+ "file_extension": ".py",
69
+ "mimetype": "text/x-python",
70
+ "name": "python",
71
+ "nbconvert_exporter": "python",
72
+ "pygments_lexer": "ipython3",
73
+ "version": "3.13.9"
74
+ }
75
+ },
76
+ "nbformat": 4,
77
+ "nbformat_minor": 5
78
+ }
test/test.py ADDED
@@ -0,0 +1,445 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ FastAPI + PostgreSQL Student Management System
3
+ Complete async implementation with SQLAlchemy, authentication, and validation
4
+
5
+ Requirements:
6
+ pip install fastapi uvicorn sqlalchemy asyncpg psycopg2-binary python-jose[cryptography] passlib[bcrypt] python-multipart
7
+ """
8
+
9
+ from fastapi import FastAPI, HTTPException, Depends, status
10
+ from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
11
+ from fastapi.middleware.cors import CORSMiddleware
12
+ from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
13
+ from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
14
+ from sqlalchemy import select, String
15
+ from pydantic import BaseModel, EmailStr, Field, field_validator, ConfigDict
16
+ from typing import Optional, List
17
+ from datetime import datetime, timedelta
18
+ from jose import JWTError, jwt
19
+ from passlib.context import CryptContext
20
+ import os
21
+ from contextlib import asynccontextmanager
22
+ # ======================== CONFIGURATION ========================
23
+ DATABASE_URL = os.getenv(
24
+ "DATABASE_URL",
25
+ "postgresql+asyncpg://postgres:690869@172.26.157.164:5432/studentdb"
26
+ )
27
+ SECRET_KEY = os.getenv("SECRET_KEY", "production")
28
+ ALGORITHM = "HS256"
29
+ ACCESS_TOKEN_EXPIRE_MINUTES = 30
30
+
31
+ # ======================== DATABASE SETUP ========================
32
+ engine = create_async_engine(DATABASE_URL, echo=True)
33
+ async_session_maker = async_sessionmaker(engine, expire_on_commit=False)
34
+
35
+ class Base(DeclarativeBase):
36
+ pass
37
+
38
+ class Student(Base):
39
+ __tablename__ = "students"
40
+
41
+ id: Mapped[int] = mapped_column(primary_key=True, index=True)
42
+ name: Mapped[str] = mapped_column(String(100))
43
+ email: Mapped[str] = mapped_column(String(100), unique=True, index=True)
44
+ age: Mapped[int]
45
+ grade: Mapped[str] = mapped_column(String(5))
46
+ created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
47
+
48
+ class User(Base):
49
+ __tablename__ = "users"
50
+
51
+ id: Mapped[int] = mapped_column(primary_key=True, index=True)
52
+ username: Mapped[str] = mapped_column(String(50), unique=True, index=True)
53
+ hashed_password: Mapped[str] = mapped_column(String(255))
54
+
55
+ # ======================== PYDANTIC MODELS ========================
56
+ class StudentBase(BaseModel):
57
+ name: str = Field(..., min_length=2, max_length=100, description="Student full name")
58
+ email: EmailStr = Field(..., description="Student email address")
59
+ age: int = Field(..., ge=5, le=100, description="Student age (5-100)")
60
+ grade: str = Field(..., pattern="^[A-F][+-]?$", description="Grade (A-F with optional + or -)")
61
+
62
+ @field_validator('name')
63
+ def validate_name(cls, v):
64
+ if not v.strip():
65
+ raise ValueError('Name cannot be empty or just whitespace')
66
+ return v.strip()
67
+
68
+ @field_validator('grade')
69
+ def validate_grade(cls, v):
70
+ v = v.upper()
71
+ if v not in ['A+', 'A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D', 'D-', 'F']:
72
+ raise ValueError('Invalid grade format')
73
+ return v
74
+
75
+ class StudentCreate(StudentBase):
76
+ pass
77
+
78
+ class StudentUpdate(BaseModel):
79
+ name: Optional[str] = Field(None, min_length=2, max_length=100)
80
+ email: Optional[EmailStr] = None
81
+ age: Optional[int] = Field(None, ge=5, le=100)
82
+ grade: Optional[str] = Field(None, pattern="^[A-F][+-]?$")
83
+
84
+ @field_validator('grade')
85
+ def validate_grade(cls, v):
86
+ if v is not None:
87
+ v = v.upper()
88
+ if v not in ['A+', 'A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D', 'D-', 'F']:
89
+ raise ValueError('Invalid grade format')
90
+ return v
91
+
92
+ class StudentResponse(StudentBase):
93
+ id: int
94
+ created_at: datetime
95
+
96
+ model_config = ConfigDict(from_attributes=True)
97
+
98
+ class UserCreate(BaseModel):
99
+ username: str = Field(..., min_length=3, max_length=50)
100
+ password: str = Field(..., min_length=6, max_length=72)
101
+
102
+ @field_validator('password')
103
+ def validate_password(cls, v):
104
+ if len(v.encode('utf-8')) > 72:
105
+ raise ValueError('Password cannot exceed 72 bytes')
106
+ return v
107
+
108
+ class Token(BaseModel):
109
+ access_token: str
110
+ token_type: str
111
+
112
+ # ======================== SECURITY ========================
113
+ pwd_context = CryptContext(schemes=["argon2"], deprecated="auto")
114
+ security = HTTPBearer()
115
+
116
+ def verify_password(plain_password: str, hashed_password: str) -> bool:
117
+ # Truncate password to 72 bytes for bcrypt compatibility
118
+ password_bytes = plain_password.encode('utf-8')[:72]
119
+ plain_password_truncated = password_bytes.decode('utf-8', errors='ignore')
120
+ return pwd_context.verify(plain_password_truncated, hashed_password)
121
+
122
+ def get_password_hash(password: str) -> str:
123
+ # Truncate password to 72 bytes for bcrypt compatibility
124
+ password_bytes = password.encode('utf-8')[:72]
125
+ password_truncated = password_bytes.decode('utf-8', errors='ignore')
126
+ return pwd_context.hash(password_truncated)
127
+
128
+ def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
129
+ to_encode = data.copy()
130
+ expire = datetime.utcnow() + (expires_delta or timedelta(minutes=15))
131
+ to_encode.update({"exp": expire})
132
+ encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
133
+ return encoded_jwt
134
+
135
+ async def get_current_user(
136
+ credentials: HTTPAuthorizationCredentials = Depends(security),
137
+ db: AsyncSession = Depends(lambda: async_session_maker())
138
+ ):
139
+ credentials_exception = HTTPException(
140
+ status_code=status.HTTP_401_UNAUTHORIZED,
141
+ detail="Could not validate credentials",
142
+ headers={"WWW-Authenticate": "Bearer"},
143
+ )
144
+ try:
145
+ token = credentials.credentials
146
+ payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
147
+ username: str = payload.get("sub")
148
+ if username is None:
149
+ raise credentials_exception
150
+ except JWTError:
151
+ raise credentials_exception
152
+
153
+ result = await db.execute(select(User).filter(User.username == username))
154
+ user = result.scalar_one_or_none()
155
+ if user is None:
156
+ raise credentials_exception
157
+ return user
158
+
159
+ # ======================== DATABASE DEPENDENCY ========================
160
+ async def get_db():
161
+ async with async_session_maker() as session:
162
+ try:
163
+ yield session
164
+ await session.commit()
165
+ except Exception:
166
+ await session.rollback()
167
+ raise
168
+ finally:
169
+ await session.close()
170
+
171
+ # new on event alternative
172
+
173
+ @asynccontextmanager
174
+ async def lifespan(app: FastAPI):
175
+ print("🏗️ Server starting:", datetime.now())
176
+ print("🔧 Creating tables if they don't exist...")
177
+
178
+ async with engine.begin() as conn:
179
+ await conn.run_sync(Base.metadata.create_all) # Create tables
180
+
181
+ print("✅ Tables ready!")
182
+ yield
183
+ print("🧹 Server shutting down:", datetime.now())
184
+
185
+ # ======================== FASTAPI APP ========================
186
+ app = FastAPI(
187
+ title="Student Management API",
188
+ description="FastAPI + PostgreSQL with SQLAlchemy async",
189
+ version="1.0.0",
190
+ lifespan=lifespan
191
+
192
+ )
193
+
194
+ # CORS Configuration
195
+ app.add_middleware(
196
+ CORSMiddleware,
197
+ allow_origins=["*"], # In production, specify allowed origins
198
+ allow_credentials=True,
199
+ allow_methods=["*"],
200
+ allow_headers=["*"],
201
+ )
202
+
203
+
204
+ # ======================== AUTHENTICATION ROUTES ========================
205
+ @app.post("/auth/register", response_model=dict, tags=["Authentication"])
206
+ async def register(user: UserCreate, db: AsyncSession = Depends(get_db)):
207
+ """Register a new user"""
208
+ try:
209
+ result = await db.execute(select(User).filter(User.username == user.username))
210
+ existing_user = result.scalar_one_or_none()
211
+
212
+ if existing_user:
213
+ raise HTTPException(
214
+ status_code=status.HTTP_400_BAD_REQUEST,
215
+ detail="Username already registered"
216
+ )
217
+
218
+ new_user = User(
219
+ username=user.username,
220
+ hashed_password=get_password_hash(user.password)
221
+ )
222
+ db.add(new_user)
223
+ await db.commit()
224
+
225
+ return {"message": "User registered successfully", "username": user.username}
226
+ except HTTPException:
227
+ raise
228
+ except Exception as e:
229
+ raise HTTPException(
230
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
231
+ detail=f"Registration failed: {str(e)}"
232
+ )
233
+
234
+ @app.post("/auth/login", response_model=Token, tags=["Authentication"])
235
+ async def login(username: str, password: str, db: AsyncSession = Depends(get_db)):
236
+ """Login and get access token"""
237
+ try:
238
+ result = await db.execute(select(User).filter(User.username == username))
239
+ user = result.scalar_one_or_none()
240
+
241
+ if not user or not verify_password(password, user.hashed_password):
242
+ raise HTTPException(
243
+ status_code=status.HTTP_401_UNAUTHORIZED,
244
+ detail="Incorrect username or password",
245
+ headers={"WWW-Authenticate": "Bearer"},
246
+ )
247
+
248
+ access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
249
+ access_token = create_access_token(
250
+ data={"sub": user.username},
251
+ expires_delta=access_token_expires
252
+ )
253
+
254
+ return {"access_token": access_token, "token_type": "bearer"}
255
+ except HTTPException:
256
+ raise
257
+ except Exception as e:
258
+ raise HTTPException(
259
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
260
+ detail=f"Login failed: {str(e)}"
261
+ )
262
+
263
+ # ======================== STUDENT CRUD ROUTES ========================
264
+ @app.post("/students/", response_model=StudentResponse, status_code=status.HTTP_201_CREATED, tags=["Students"])
265
+ async def create_student(
266
+ student: StudentCreate,
267
+ db: AsyncSession = Depends(get_db),
268
+ current_user: User = Depends(get_current_user)
269
+ ):
270
+ """Create a new student (Protected)"""
271
+ try:
272
+ # Check if email already exists
273
+ result = await db.execute(select(Student).filter(Student.email == student.email))
274
+ existing_student = result.scalar_one_or_none()
275
+
276
+ if existing_student:
277
+ raise HTTPException(
278
+ status_code=status.HTTP_400_BAD_REQUEST,
279
+ detail=f"Student with email {student.email} already exists"
280
+ )
281
+
282
+ new_student = Student(**student.model_dump())
283
+ db.add(new_student)
284
+ await db.commit()
285
+ await db.refresh(new_student)
286
+
287
+ return new_student
288
+ except HTTPException:
289
+ raise
290
+ except Exception as e:
291
+ raise HTTPException(
292
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
293
+ detail=f"Failed to create student: {str(e)}"
294
+ )
295
+
296
+ @app.get("/students/", response_model=List[StudentResponse], tags=["Students"])
297
+ async def get_all_students(
298
+ skip: int = 0,
299
+ limit: int = 100,
300
+ db: AsyncSession = Depends(get_db),
301
+ current_user: User = Depends(get_current_user)
302
+ ):
303
+ """Get all students with pagination (Protected)"""
304
+ try:
305
+ result = await db.execute(
306
+ select(Student).offset(skip).limit(limit)
307
+ )
308
+ students = result.scalars().all()
309
+ return students
310
+ except Exception as e:
311
+ raise HTTPException(
312
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
313
+ detail=f"Failed to fetch students: {str(e)}"
314
+ )
315
+
316
+ @app.get("/students/{student_id}", response_model=StudentResponse, tags=["Students"])
317
+ async def get_student(
318
+ student_id: int,
319
+ db: AsyncSession = Depends(get_db),
320
+ current_user: User = Depends(get_current_user)
321
+ ):
322
+ """Get a specific student by ID (Protected)"""
323
+ try:
324
+ result = await db.execute(select(Student).filter(Student.id == student_id))
325
+ student = result.scalar_one_or_none()
326
+
327
+ if not student:
328
+ raise HTTPException(
329
+ status_code=status.HTTP_404_NOT_FOUND,
330
+ detail=f"Student with ID {student_id} not found"
331
+ )
332
+
333
+ return student
334
+ except HTTPException:
335
+ raise
336
+ except Exception as e:
337
+ raise HTTPException(
338
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
339
+ detail=f"Failed to fetch student: {str(e)}"
340
+ )
341
+
342
+ @app.put("/students/{student_id}", response_model=StudentResponse, tags=["Students"])
343
+ async def update_student(
344
+ student_id: int,
345
+ student_update: StudentUpdate,
346
+ db: AsyncSession = Depends(get_db),
347
+ current_user: User = Depends(get_current_user)
348
+ ):
349
+ """Update a student's information (Protected)"""
350
+ try:
351
+ result = await db.execute(select(Student).filter(Student.id == student_id))
352
+ student = result.scalar_one_or_none()
353
+
354
+ if not student:
355
+ raise HTTPException(
356
+ status_code=status.HTTP_404_NOT_FOUND,
357
+ detail=f"Student with ID {student_id} not found"
358
+ )
359
+
360
+ # Update only provided fields
361
+ update_data = student_update.model_dump(exclude_unset=True)
362
+
363
+ # Check email uniqueness if email is being updated
364
+ if "email" in update_data:
365
+ result = await db.execute(
366
+ select(Student).filter(
367
+ Student.email == update_data["email"],
368
+ Student.id != student_id
369
+ )
370
+ )
371
+ existing = result.scalar_one_or_none()
372
+ if existing:
373
+ raise HTTPException(
374
+ status_code=status.HTTP_400_BAD_REQUEST,
375
+ detail=f"Email {update_data['email']} is already in use"
376
+ )
377
+
378
+ for key, value in update_data.items():
379
+ setattr(student, key, value)
380
+
381
+ await db.commit()
382
+ await db.refresh(student)
383
+
384
+ return student
385
+ except HTTPException:
386
+ raise
387
+ except Exception as e:
388
+ raise HTTPException(
389
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
390
+ detail=f"Failed to update student: {str(e)}"
391
+ )
392
+
393
+ @app.patch("/students/{student_id}", response_model=StudentResponse, tags=["Students"])
394
+ async def partial_update_student(
395
+ student_id: int,
396
+ student_update: StudentUpdate,
397
+ db: AsyncSession = Depends(get_db),
398
+ current_user: User = Depends(get_current_user)
399
+ ):
400
+ """Partially update a student (same as PUT for this implementation) (Protected)"""
401
+ return await update_student(student_id, student_update, db, current_user)
402
+
403
+ @app.delete("/students/{student_id}", status_code=status.HTTP_204_NO_CONTENT, tags=["Students"])
404
+ async def delete_student(
405
+ student_id: int,
406
+ db: AsyncSession = Depends(get_db),
407
+ current_user: User = Depends(get_current_user)
408
+ ):
409
+ """Delete a student (Protected)"""
410
+ try:
411
+ result = await db.execute(select(Student).filter(Student.id == student_id))
412
+ student = result.scalar_one_or_none()
413
+
414
+ if not student:
415
+ raise HTTPException(
416
+ status_code=status.HTTP_404_NOT_FOUND,
417
+ detail=f"Student with ID {student_id} not found"
418
+ )
419
+
420
+ await db.delete(student)
421
+ await db.commit()
422
+
423
+ return None
424
+ except HTTPException:
425
+ raise
426
+ except Exception as e:
427
+ raise HTTPException(
428
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
429
+ detail=f"Failed to delete student: {str(e)}"
430
+ )
431
+
432
+ # ======================== HEALTH CHECK ========================
433
+ @app.get("/", tags=["Health"])
434
+ async def root():
435
+ """Health check endpoint"""
436
+ return {
437
+ "status": "healthy",
438
+ "message": "Student Management API is running",
439
+ "version": "1.0.0"
440
+ }
441
+
442
+ # ======================== RUN APPLICATION ========================
443
+ if __name__ == "__main__":
444
+ import uvicorn
445
+ uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)