Skip to content

Chore(#4): FastAPI 초기 개발 환경 구축 및 Docker 설정 - #5

Merged
pearseona merged 7 commits into
developfrom
feat/4-fastapi-setup
Jul 10, 2026
Merged

Chore(#4): FastAPI 초기 개발 환경 구축 및 Docker 설정#5
pearseona merged 7 commits into
developfrom
feat/4-fastapi-setup

Conversation

@pearseona

@pearseona pearseona commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

📝 개요

AI 및 URL 연산 백엔드 서버의 기반이 되는 FastAPI 글로벌 공통 개발 환경을 구축하고 패키지 의존성 관리 및 메인 엔드포인트 구조를 초기 설정합니다

추가로 향후 클라우드 배포 인프라의 확장을 고려하여 Docker 및 Docker Compose 기반의 개발 환경을 구축하고 README 문서를 상세화합니다.

🔗 관련 이슈

🎯 주요 변경 사항

1. FastAPI 초기 환경 및 메인 진입점 구축

  • 필수 패키지 명세(fastapi, uvicorn, pydantic-settings 등) 작성 및 가상환경 세팅 완료
  • 애플리케이션 초기화 및 글로벌 라우터 등록
  • 환경 변수 관리를 위한 Pydantic Settings 클래스 구현 (.env 연동 기반 마련)

2. 아키텍처 구조화 및 스프링 연동 규격화

  • 메인 백엔드(Spring Boot) 서버와 JSON 응답 규격을 일치시키기 위한 Generic 기반 공통 응답 DTO 정의
  • 향후 고도화할 URL 추적 및 AI 분석 로직의 엔드포인트 초안(Stub Code) 작성

3. 인프라 고도화 및 README 문서 추가 작성 (이슈 외 추가 작업 항목)

  • Docker, docker-compose.yml 생성
  • 학습 데이터 data_science/ 하위로 모음
  • README에 로컬 개발 환경 가이드 작성

📸 사진

image

✅ PR 체크리스트

  • 관련 이슈를 연결했습니다.
  • 구현 범위와 변경 이유를 설명했습니다.
  • 로컬 테스트(uvicorn 구동 또는 테스트 코드)를 통과했습니다.
  • API 변경 사항이 있다면 Swagger / API 명세에 반영했습니다.
  • 민감 정보(API Key, 시크릿 키 등)가 코드·로그·테스트 데이터에 포함되지 않았습니다.
  • 프론트엔드 또는 메인 백엔드(Spring)에 영향을 주는 응답 스키마 또는 Enum 변경이 있다면 팀에 공유했습니다.
  • 병합(Merge) 전 작업 브랜치를 삭제하지 않았습니다.

Summary by CodeRabbit

  • New Features

    • Added a FastAPI service with a health-check endpoint.
    • Added an analysis API endpoint with standardized success and error responses.
    • Added environment-based configuration, including API settings and external service credentials.
    • Added Docker and Docker Compose support with development hot reload.
  • Documentation

    • Added setup instructions, project structure guidance, environment configuration steps, and Swagger UI verification details.
  • Chores

    • Updated issue request templates and excluded local environment files from version control.

@pearseona pearseona self-assigned this Jul 10, 2026
@coderabbitai

coderabbitai Bot commented Jul 10, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Adds a configurable FastAPI application with a generic response model, /api/v1/analyze placeholder endpoint, root health endpoint, Docker-based local runtime, setup documentation, environment-file ignoring, and updated issue-template defaults.

Changes

FastAPI service foundation

Layer / File(s) Summary
Runtime configuration and container setup
app/core/config.py, requirements.txt, Dockerfile, docker-compose.yml, README.md, .gitignore
Adds environment-backed settings, dependencies, Docker and Compose execution, local setup documentation, and .env exclusion.
API contract and analysis routing
app/dto/response.py, app/router/analyze.py
Defines typed success/error responses and adds the /analyze POST endpoint with a fixed analysis result.
Application entrypoint and health endpoint
app/main.py
Initializes FastAPI from settings, mounts the analysis router, and provides a root health response.

Repository workflow metadata

Layer / File(s) Summary
Feature request template defaults
.github/ISSUE_TEMPLATE/feature_request.md
Updates the template name and clears previous default title, label, and assignee values while retaining the request prompts.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant FastAPIApp
  participant AnalyzeRouter
  participant ApiResponse
  Client->>FastAPIApp: POST /api/v1/analyze
  FastAPIApp->>AnalyzeRouter: Forward request payload
  AnalyzeRouter->>ApiResponse: Create success response
  ApiResponse-->>Client: Return analysis result
Loading

Possibly related issues

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: initial FastAPI development setup with Docker configuration.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/4-fastapi-setup

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (2)
requirements.txt (1)

1-5: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Make dependency resolution reproducible.

Lower bounds alone allow every image build to install a different dependency set. Commit a lock/constraints file, or pin versions that are tested together with Python 3.11 and update them deliberately.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@requirements.txt` around lines 1 - 5, Make dependency resolution reproducible
for the listed runtime packages by adding a committed lock or constraints file,
or replacing lower-bound-only requirements with exact versions tested together
on Python 3.11; ensure future dependency updates are deliberate and keep the
primary requirements aligned with the chosen pins.
app/router/analyze.py (1)

1-21: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider typing the request payload instead of raw dict.

app/dto/ is intended to standardize the Spring-backend contract, but payload: dict and ApiResponse[dict] leave both request and response schemas undocumented in Swagger and unvalidated by FastAPI. A dedicated request DTO would fit the same pattern as ApiResponse.

♻️ Example refactor
# app/dto/request.py
from pydantic import BaseModel

class AnalyzeRequest(BaseModel):
    message: str
    url: str | None = None
-from fastapi import APIRouter
-from app.dto.response import ApiResponse
+from fastapi import APIRouter
+from app.dto.response import ApiResponse
+from app.dto.request import AnalyzeRequest

 router = APIRouter(prefix="/analyze", tags=["Analyze"])

 `@router.post`("", response_model=ApiResponse[dict])
-async def analyze_smishing(payload: dict):
+async def analyze_smishing(payload: AnalyzeRequest):
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@app/router/analyze.py` around lines 1 - 21, Replace the untyped payload and
response dictionary in analyze_smishing with dedicated Pydantic DTOs under
app.dto, defining AnalyzeRequest with the required message and optional url
fields and a response model for the analysis result. Update the endpoint
annotation and ApiResponse generic to use these DTOs so FastAPI validates
requests and documents the Spring contract in Swagger.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In @.gitignore:
- Around line 4-5: Prevent local environment files from entering Docker images
by adding a .dockerignore file that excludes .env, and ensure the required
environment value is supplied at container runtime rather than copied during the
build.

In `@app/core/config.py`:
- Line 7: Replace the placeholder default in VIRUSTOTAL_API_KEY with a required
setting or an optional None value, then validate it at the VirusTotal
integration boundary before making outbound requests and fail clearly when it is
missing.

In `@Dockerfile`:
- Line 1: Add a dedicated non-root user in the Dockerfile, ensure the
application files and required directories are owned or accessible by that user,
then add a USER directive immediately before the existing CMD so Uvicorn runs
without root privileges.

---

Nitpick comments:
In `@app/router/analyze.py`:
- Around line 1-21: Replace the untyped payload and response dictionary in
analyze_smishing with dedicated Pydantic DTOs under app.dto, defining
AnalyzeRequest with the required message and optional url fields and a response
model for the analysis result. Update the endpoint annotation and ApiResponse
generic to use these DTOs so FastAPI validates requests and documents the Spring
contract in Swagger.

In `@requirements.txt`:
- Around line 1-5: Make dependency resolution reproducible for the listed
runtime packages by adding a committed lock or constraints file, or replacing
lower-bound-only requirements with exact versions tested together on Python
3.11; ensure future dependency updates are deliberate and keep the primary
requirements aligned with the chosen pins.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 73239c66-88c4-4ac6-bf50-16dca768a527

📥 Commits

Reviewing files that changed from the base of the PR and between 956a982 and 8d97499.

⛔ Files ignored due to path filters (14)
  • data_science/Data/CallData/metadata_clean.csv is excluded by !**/*.csv
  • data_science/Data/SMSData/phishing_total_dataset_2705.csv is excluded by !**/*.csv
  • data_science/SMSModel/feature_importance.png is excluded by !**/*.png
  • data_science/SMSModel/feature_scores_full.csv is excluded by !**/*.csv
  • data_science/SMSModel/phishing_model_artifact.pkl is excluded by !**/*.pkl
  • data_science/SMSModel/phishing_vectorizer.pkl is excluded by !**/*.pkl
  • data_science/SMSModel/risk_distribution_fig1.png is excluded by !**/*.png
  • data_science/SMSModel/risk_distribution_fig2.png is excluded by !**/*.png
  • data_science/VoiceModel/feature_importance.png is excluded by !**/*.png
  • data_science/VoiceModel/feature_scores_full.csv is excluded by !**/*.csv
  • data_science/VoiceModel/risk_distribution_fig1.png is excluded by !**/*.png
  • data_science/VoiceModel/risk_distribution_fig2.png is excluded by !**/*.png
  • data_science/VoiceModel/voice_model_artifact.pkl is excluded by !**/*.pkl
  • data_science/VoiceModel/voice_vectorizer.pkl is excluded by !**/*.pkl
📒 Files selected for processing (16)
  • .github/ISSUE_TEMPLATE/feature_request.md
  • .gitignore
  • Dockerfile
  • README.md
  • app/core/config.py
  • app/dto/response.py
  • app/main.py
  • app/router/analyze.py
  • data_science/Data/CallData/CallDataMd.md
  • data_science/Data/SMSData/SMSDataMd.md
  • data_science/SMSModel/SMSDataModel.ipynb
  • data_science/SMSModel/train_sms.py
  • data_science/VoiceModel/VoiceDataModel.ipynb
  • data_science/VoiceModel/train_voice.py
  • docker-compose.yml
  • requirements.txt

Comment thread .gitignore
Comment on lines +4 to +5
.claude/settings.local.json
.env No newline at end of file

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Also exclude .env from the Docker build context.

.gitignore does not affect docker build; with COPY . ., a developer’s local .env can be baked into the image. Add a .dockerignore containing .env and pass the key at runtime instead.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.gitignore around lines 4 - 5, Prevent local environment files from entering
Docker images by adding a .dockerignore file that excludes .env, and ensure the
required environment value is supplied at container runtime rather than copied
during the build.

Comment thread app/core/config.py
PROJECT_NAME: str = "SafeFam-AI"
VERSION: str = "1.0.0"
API_V1_STR: str = "/api/v1"
VIRUSTOTAL_API_KEY: str = "default_key_here"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Do not use a fake API-key default.

A missing .env currently produces a non-empty credential, masking deployment misconfiguration and allowing future outbound calls to proceed with an invalid key. Make this setting required, or use None and validate it at the VirusTotal integration boundary.

🔐 Proposed fix
-    VIRUSTOTAL_API_KEY: str = "default_key_here"
+    VIRUSTOTAL_API_KEY: str | None = None
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
VIRUSTOTAL_API_KEY: str = "default_key_here"
VIRUSTOTAL_API_KEY: str | None = None
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@app/core/config.py` at line 7, Replace the placeholder default in
VIRUSTOTAL_API_KEY with a required setting or an optional None value, then
validate it at the VirusTotal integration boundary before making outbound
requests and fail clearly when it is missing.

Comment thread Dockerfile
@@ -0,0 +1,17 @@
FROM python:3.11-slim

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Run the application as a non-root user.

The container currently launches Uvicorn as root. Add a dedicated user and switch to it before CMD.

🛡️ Proposed fix
 FROM python:3.11-slim
+
+RUN groupadd --system app && useradd --system --gid app app
 ...
 EXPOSE 8000
+
+USER app
+
 CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]

Also applies to: 16-17

🧰 Tools
🪛 Trivy (0.69.3)

[error] 1-1: Image user should not be 'root'

Specify at least 1 USER command in Dockerfile with non-root user as argument

Rule: DS-0002

Learn more

(IaC/Dockerfile)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@Dockerfile` at line 1, Add a dedicated non-root user in the Dockerfile,
ensure the application files and required directories are owned or accessible by
that user, then add a USER directive immediately before the existing CMD so
Uvicorn runs without root privileges.

Source: Linters/SAST tools

@pearseona
pearseona merged commit 0326d68 into develop Jul 10, 2026
1 check passed
@pearseona pearseona changed the title [Feat] FastAPI 초기 개발 환경 구축 및 Docker 설정 Feat: FastAPI 초기 개발 환경 구축 및 Docker 설정 Jul 10, 2026
@pearseona pearseona changed the title Feat: FastAPI 초기 개발 환경 구축 및 Docker 설정 Chore: FastAPI 초기 개발 환경 구축 및 Docker 설정 Jul 12, 2026
@pearseona pearseona added the chore Changes to the build process, configuration, or dependencies label Jul 14, 2026
@pearseona pearseona changed the title Chore: FastAPI 초기 개발 환경 구축 및 Docker 설정 Chore(#4): FastAPI 초기 개발 환경 구축 및 Docker 설정 Jul 15, 2026
@coderabbitai coderabbitai Bot mentioned this pull request Jul 17, 2026
Merged
7 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

chore Changes to the build process, configuration, or dependencies

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant