-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate_fastapi_app.py
More file actions
416 lines (345 loc) · 13.8 KB
/
Copy pathcreate_fastapi_app.py
File metadata and controls
416 lines (345 loc) · 13.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
import os
import sys
import subprocess
import platform
# ─────────────────────────────────────────────
# Colors for terminal output
# ─────────────────────────────────────────────
GREEN = "\033[92m"
YELLOW = "\033[93m"
RED = "\033[91m"
BLUE = "\033[94m"
RESET = "\033[0m"
def success(msg): print(f"{GREEN}✅ {msg}{RESET}")
def info(msg): print(f"{BLUE}ℹ️ {msg}{RESET}")
def warning(msg): print(f"{YELLOW}⚠️ {msg}{RESET}")
def error(msg): print(f"{RED}❌ {msg}{RESET}")
# ─────────────────────────────────────────────
# Get project name from user
# ─────────────────────────────────────────────
def get_project_name():
if len(sys.argv) > 1:
return sys.argv[1]
name = input(f"{BLUE}Enter your project name: {RESET}").strip()
if not name:
error("Project name cannot be empty!")
sys.exit(1)
return name
# ─────────────────────────────────────────────
# Create folder structure
# ─────────────────────────────────────────────
def create_structure(base):
folders = [
"app",
"app/models",
"app/routers",
"app/schemas",
"app/services",
"app/dependencies",
"alembic",
]
for folder in folders:
os.makedirs(os.path.join(base, folder), exist_ok=True)
success("Folder structure created")
# ─────────────────────────────────────────────
# File contents
# ─────────────────────────────────────────────
FILES = {
# ── main.py ──────────────────────────────
"main.py": '''\
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.database import engine, Base
# Create all tables on startup (like php artisan migrate)
Base.metadata.create_all(bind=engine)
app = FastAPI(
title="FastAPI App",
description="Built with FastAPI + SQLAlchemy + PostgreSQL",
version="1.0.0",
)
# CORS Middleware (like Laravel CORS middleware)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Change this in production!
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# ── Register Routers here (like Laravel route files) ──
# from app.routers import users
# app.include_router(users.router)
@app.get("/")
def root():
return {"message": "🚀 FastAPI is running!"}
@app.get("/health")
def health():
return {"status": "ok"}
''',
# ── app/__init__.py ───────────────────────
"app/__init__.py": "",
# ── app/database.py ───────────────────────
"app/database.py": '''\
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, DeclarativeBase
from dotenv import load_dotenv
import os
# Load .env file (like Laravel\'s config())
load_dotenv()
DATABASE_URL = os.getenv("DATABASE_URL")
# Create engine (like Laravel DB connection)
engine = create_engine(DATABASE_URL)
# Session factory (like Laravel DB facade)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
# Base class for all models (like Laravel\'s Model class)
class Base(DeclarativeBase):
pass
# DB session dependency — used in every route that needs DB
# (like Laravel\'s automatic DB injection)
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
''',
# ── app/models/__init__.py ────────────────
"app/models/__init__.py": "",
# ── app/models/user.py ────────────────────
"app/models/user.py": '''\
from sqlalchemy import Column, Integer, String, Boolean, DateTime
from sqlalchemy.sql import func
from app.database import Base
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, nullable=False)
email = Column(String, unique=True, nullable=False, index=True)
password = Column(String, nullable=False)
is_active = Column(Boolean, default=True)
created_at = Column(DateTime(timezone=True), server_default=func.now())
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
''',
# ── app/schemas/__init__.py ───────────────
"app/schemas/__init__.py": "",
# ── app/schemas/user.py ───────────────────
"app/schemas/user.py": '''\
from pydantic import BaseModel, EmailStr, Field
from typing import Optional
from datetime import datetime
# Like Laravel FormRequest — used for incoming data validation
class UserCreate(BaseModel):
name: str = Field(..., min_length=2, max_length=100)
email: EmailStr
password: str = Field(..., min_length=8)
class UserUpdate(BaseModel):
name: Optional[str] = None
email: Optional[EmailStr] = None
# Like Laravel API Resource — shapes the response
class UserResponse(BaseModel):
id: int
name: str
email: EmailStr
is_active: bool
created_at: datetime
class Config:
from_attributes = True # Allows ORM model → Pydantic conversion
''',
# ── app/routers/__init__.py ───────────────
"app/routers/__init__.py": "",
# ── app/routers/users.py ──────────────────
"app/routers/users.py": '''\
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.database import get_db
from app.schemas.user import UserCreate, UserResponse
from app.models.user import User
# Like Laravel\'s Route::prefix(\'users\') group
router = APIRouter(prefix="/users", tags=["Users"])
# GET /users — like index() in Laravel ResourceController
@router.get("/", response_model=list[UserResponse])
def get_users(db: Session = Depends(get_db)):
return db.query(User).all()
# GET /users/{id} — like show() in Laravel ResourceController
@router.get("/{user_id}", response_model=UserResponse)
def get_user(user_id: int, db: Session = Depends(get_db)):
user = db.query(User).filter(User.id == user_id).first()
if not user:
raise HTTPException(status_code=404, detail="User not found")
return user
''',
# ── app/services/__init__.py ──────────────
"app/services/__init__.py": "",
# ── app/dependencies/__init__.py ──────────
"app/dependencies/__init__.py": "",
# ── app/dependencies/auth.py ──────────────
"app/dependencies/auth.py": '''\
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt
from sqlalchemy.orm import Session
from app.database import get_db
from app.models.user import User
from dotenv import load_dotenv
import os
load_dotenv()
SECRET_KEY = os.getenv("SECRET_KEY")
ALGORITHM = os.getenv("ALGORITHM", "HS256")
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/login")
# Like Laravel\'s auth()->user() — gets current authenticated user
def get_current_user(
token: str = Depends(oauth2_scheme),
db: Session = Depends(get_db)
):
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
user_id: int = payload.get("sub")
if user_id is None:
raise credentials_exception
except JWTError:
raise credentials_exception
user = db.query(User).filter(User.id == user_id).first()
if user is None:
raise credentials_exception
return user
''',
# ── .env ──────────────────────────────────
".env": '''\
# Database (like Laravel DB_* variables combined into one URL)
DATABASE_URL=postgresql://postgres:YourPassword@localhost:5432/your_db_name
# JWT Auth (like Laravel JWT_SECRET)
SECRET_KEY=change-this-to-a-super-secret-key-in-production
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30
''',
# ── .gitignore ────────────────────────────
".gitignore": '''\
# Virtual environment (like vendor/)
venv/
env/
.env
# Python cache
__pycache__/
*.pyc
*.pyo
*.pyd
# PyCharm
.idea/
# VS Code
.vscode/
# Alembic
alembic/versions/*.py
# OS
.DS_Store
Thumbs.db
''',
# ── requirements.txt ──────────────────────
"requirements.txt": '''\
fastapi
uvicorn
sqlalchemy
alembic
psycopg2-binary
pydantic[email]
pydantic-settings
python-dotenv
passlib[bcrypt]
python-jose[cryptography]
python-multipart
''',
# ── README.md ─────────────────────────────
"README.md": '''\
# FastAPI Boilerplate
A production-ready FastAPI project structure.
## Setup
```bash
# 1. Create & activate virtual environment
python -m venv venv
venv\\Scripts\\activate # Windows
source venv/bin/activate # Mac/Linux
# 2. Install dependencies
pip install -r requirements.txt
# 3. Setup .env file
# Edit .env and add your database credentials
# 4. Run the server
uvicorn main:app --reload
```
## API Docs
- Swagger UI → http://127.0.0.1:8000/docs
- ReDoc → http://127.0.0.1:8000/redoc
## Project Structure
```
├── main.py # Entry point (like public/index.php)
├── requirements.txt # Dependencies (like composer.json)
├── .env # Environment variables
└── app/
├── database.py # DB connection (like config/database.php)
├── models/ # SQLAlchemy models (like app/Models)
├── routers/ # API routes (like routes/api.php)
├── schemas/ # Pydantic schemas (like FormRequests + Resources)
├── services/ # Business logic (like app/Services)
└── dependencies/ # Auth & middleware (like app/Http/Middleware)
```
''',
}
# ─────────────────────────────────────────────
# Write all files
# ─────────────────────────────────────────────
def create_files(base):
for path, content in FILES.items():
full_path = os.path.join(base, path)
os.makedirs(os.path.dirname(full_path), exist_ok=True)
with open(full_path, "w", encoding="utf-8") as f:
f.write(content)
success("All files created")
# ─────────────────────────────────────────────
# Create virtual environment
# ─────────────────────────────────────────────
def create_venv(base):
info("Creating virtual environment...")
subprocess.run([sys.executable, "-m", "venv", os.path.join(base, "venv")], check=True)
success("Virtual environment created")
# ─────────────────────────────────────────────
# Install packages
# ─────────────────────────────────────────────
def install_packages(base):
info("Installing packages (this may take a minute)...")
is_windows = platform.system() == "Windows"
pip = os.path.join(base, "venv", "Scripts" if is_windows else "bin", "pip")
req = os.path.join(base, "requirements.txt")
subprocess.run([pip, "install", "-r", req], check=True)
success("All packages installed")
# ─────────────────────────────────────────────
# Main
# ─────────────────────────────────────────────
def main():
print(f"\n{BLUE}🚀 FastAPI Project Generator{RESET}")
print("=" * 40)
project_name = get_project_name()
base = os.path.join(os.getcwd(), project_name)
if os.path.exists(base):
error(f"Folder '{project_name}' already exists!")
sys.exit(1)
os.makedirs(base)
info(f"Creating project: {project_name}")
create_structure(base)
create_files(base)
create_venv(base)
install_packages(base)
print(f"\n{GREEN}{'=' * 40}")
print(f" 🎉 Project '{project_name}' is ready!")
print(f"{'=' * 40}{RESET}")
print(f"\n{YELLOW}Next steps:")
print(f" 1. cd {project_name}")
print(f" 2. Edit .env → add your database credentials")
is_windows = platform.system() == "Windows"
activate = r"venv\Scripts\activate" if is_windows else "source venv/bin/activate"
print(f" 3. {activate}")
print(f" 4. uvicorn main:app --reload")
print(f" 5. Open http://127.0.0.1:8000/docs{RESET}\n")
if __name__ == "__main__":
main()