Skip to content

Commit fb748f5

Browse files
committed
Initial Commit
1 parent 769c432 commit fb748f5

File tree

14 files changed

+1282
-0
lines changed

14 files changed

+1282
-0
lines changed

.github/workflows/deploy.yml

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
name: Publish Package to npm and pip
2+
3+
on:
4+
workflow_dispatch:
5+
push:
6+
branches:
7+
- main
8+
pull_request:
9+
branches:
10+
- main
11+
12+
jobs:
13+
publish:
14+
runs-on: ubuntu-latest
15+
concurrency:
16+
group: ${{ github.workflow }}-${{ github.ref }}
17+
cancel-in-progress: false
18+
steps:
19+
- name: Checkout
20+
uses: actions/checkout@v4
21+
- name: Install uv
22+
uses: astral-sh/setup-uv@v5
23+
- name: Install dependencies
24+
run: uv sync
25+
- name: Test
26+
run: |
27+
uv run ruff check src/ tests/
28+
uv run ruff format src/ tests/
29+
uv run pytest
30+
- name: Publish to pypi
31+
run: uv publish
32+
env:
33+
PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }}
34+
if: github.event_name == 'workflow_dispatch'

.gitignore

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
.coverage
2+
coverage.xml
3+
coverage*
4+
htmlcov
5+
.pytest_cache
6+
.ruff_cache
7+
.vscode
8+
.idea
9+
.env
10+
.env.local
11+
.env.development.local
12+
.env.test.local
13+
.env.production.local
14+
__pycache__

.python-version

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
3.13

README.md

Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
# FastAPI FS Router
2+
3+
A library for automatically loading routers in FastAPI applications based on file system structure.
4+
5+
English | [한국어](README_ko.md)
6+
7+
## Features
8+
9+
- 📁 Automatically loads routers based on the file system structure
10+
- 🔗 Maps directory structure directly to API paths
11+
- 🎯 Detects and registers APIRouter instances automatically
12+
- ⚙️ Supports custom prefixes for all routes
13+
- 🚀 Prevents duplicate router registration
14+
- 🛣️ Supports path parameters and route groups
15+
16+
## Installation
17+
18+
```bash
19+
pip install fastapi-fs-router
20+
```
21+
22+
## Usage
23+
24+
### Basic Usage
25+
26+
```python
27+
from fastapi import FastAPI
28+
from fastapi_fs_router import load_fs_router
29+
30+
app = FastAPI()
31+
32+
# Automatically load all routers from the routers directory
33+
load_fs_router(app, "routers")
34+
```
35+
36+
### Directory Structure Example
37+
38+
```
39+
routers/
40+
├── users.py # Maps to /users path
41+
├── items.py # Maps to /items path
42+
└── v1/
43+
└── admin/
44+
└── users.py # Maps to /v1/admin/users path
45+
```
46+
47+
### Router File Example
48+
49+
```python
50+
# routers/users.py
51+
from fastapi import APIRouter
52+
53+
router = APIRouter()
54+
55+
@router.get("/")
56+
def get_users():
57+
return {"users": []}
58+
59+
@router.get("/{user_id}")
60+
def get_user(user_id: int):
61+
return {"user_id": user_id}
62+
```
63+
64+
### Using Custom Prefix
65+
66+
```python
67+
from fastapi import FastAPI
68+
from fastapi_fs_router import load_fs_router
69+
70+
app = FastAPI()
71+
72+
# Add /api/v1 prefix to all routers
73+
load_fs_router(app, "routers", prefix="/api/v1")
74+
```
75+
76+
In this case, routers will be mapped as follows:
77+
- `routers/users.py``/api/v1/users`
78+
- `routers/v1/admin/users.py``/api/v1/v1/admin/users`
79+
- `routers/(empty)/admin/users.py``/api/admin/users`
80+
- `routers/hello_world/admin/hello_world.py``/hello-world/admin/hello-world`
81+
- `routers/{path_param}/admin.py``/{path_param}/admin`
82+
83+
### Path Transformation Rules
84+
85+
- Underscores (`_`) are converted to hyphens (`-`) except for path parameters
86+
- Square brackets are converted to curly braces (e.g., `[id]``{id}`)
87+
- Parentheses are ignored (e.g., `(empty)`)
88+
89+
## API Reference
90+
91+
### `load_fs_router(app, route_dir, *, prefix="")`
92+
93+
Loads file system-based routers into a FastAPI application.
94+
95+
**Parameters:**
96+
- `app` (FastAPI): FastAPI application instance
97+
- `route_dir` (Path | str): Directory path containing router files (default: "routers")
98+
- `prefix` (str): Prefix to add to all routers (default: "")
99+
100+
**Behavior:**
101+
1. Recursively traverses the specified directory
102+
2. Finds `APIRouter` instances in `.py` files
103+
3. Generates API paths based on directory structure
104+
4. Registers routers with the FastAPI app
105+
106+
## Development
107+
108+
### Install Dependencies
109+
110+
```bash
111+
# Install development dependencies
112+
uv sync
113+
```
114+
115+
### Run Tests
116+
117+
```bash
118+
# Run all tests
119+
uv run pytest
120+
```
121+
122+
### Code Quality Checks
123+
124+
```bash
125+
# Linting
126+
ruff check src/ tests/
127+
128+
# Formatting
129+
ruff format src/ tests/
130+
```
131+
132+
## License
133+
134+
This project is licensed under the Apache License 2.0. See the [LICENSE](LICENSE) file for details.
135+
136+
## Contributing
137+
138+
Bug reports, feature requests, and pull requests are welcome! Please create an issue first before contributing.
139+
140+
## Author
141+
142+
- **owjs3901** - *Initial work* - [owjs3901@gmail.com](mailto:owjs3901@gmail.com)

README_ko.md

Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
# FastAPI FS Router
2+
3+
FastAPI 애플리케이션에서 파일 시스템 기반으로 라우터를 자동으로 로드하는 라이브러리입니다.
4+
5+
[English](README.md) | 한국어
6+
7+
## 기능
8+
9+
- 📁 파일 시스템 구조를 기반으로 한 자동 라우터 로딩
10+
- 🔗 디렉토리 구조가 API 경로로 자동 매핑
11+
- 🎯 APIRouter 인스턴스를 자동으로 감지하고 등록
12+
- ⚙️ 커스텀 프리픽스 지원
13+
- 🚀 중복 라우터 방지
14+
- 🛣️ 패스 파라미터와 라우트 그룹 지원
15+
16+
## 설치
17+
18+
```bash
19+
pip install fastapi-fs-router
20+
```
21+
22+
## 사용법
23+
24+
### 기본 사용법
25+
26+
```python
27+
from fastapi import FastAPI
28+
from fastapi_fs_router import load_fs_router
29+
30+
app = FastAPI()
31+
32+
# routers 디렉토리에서 모든 라우터를 자동으로 로드
33+
load_fs_router(app, "routers")
34+
```
35+
36+
### 디렉토리 구조 예시
37+
38+
```
39+
routers/
40+
├── users.py # /users 경로로 매핑
41+
├── items.py # /items 경로로 매핑
42+
└── v1/
43+
└── admin/
44+
└── users.py # /v1/admin/users 경로로 매핑
45+
```
46+
47+
### 라우터 파일 예시
48+
49+
```python
50+
# routers/users.py
51+
from fastapi import APIRouter
52+
53+
router = APIRouter()
54+
55+
@router.get("/")
56+
def get_users():
57+
return {"users": []}
58+
59+
@router.get("/{user_id}")
60+
def get_user(user_id: int):
61+
return {"user_id": user_id}
62+
```
63+
64+
### 커스텀 프리픽스 사용
65+
66+
```python
67+
from fastapi import FastAPI
68+
from fastapi_fs_router import load_fs_router
69+
70+
app = FastAPI()
71+
72+
# 모든 라우터에 /api/v1 프리픽스 추가
73+
load_fs_router(app, "routers", prefix="/api/v1")
74+
```
75+
76+
이 경우 라우터들은 다음과 같이 매핑됩니다:
77+
- `routers/users.py``/api/v1/users`
78+
- `routers/v1/admin/users.py``/api/v1/v1/admin/users`
79+
- `routers/(empty)/admin/users.py``/api/admin/users`
80+
- `routers/hello_world/admin/hello_world.py``/hello-world/admin/hello-world`
81+
- `routers/{path_param}/admin.py``/{path_param}/admin`
82+
83+
### 경로 변환 규칙
84+
85+
- 패스파라미터를 제외한 언더스코어(`_`)는 하이픈(`-`)으로 변환됩니다
86+
- 대괄호로 감싸진 부분은 중괄호로 변환됩니다 (예: `[id]``{id}`)
87+
- 괄호로 감싸진 부분은 무시됩니다 (예: `(empty)`)
88+
89+
## API 참조
90+
91+
### `load_fs_router(app, route_dir, *, prefix="")`
92+
93+
FastAPI 애플리케이션에 파일 시스템 기반 라우터를 로드합니다.
94+
95+
**매개변수:**
96+
- `app` (FastAPI): FastAPI 애플리케이션 인스턴스
97+
- `route_dir` (Path | str): 라우터 파일들이 있는 디렉토리 경로 (기본값: "routers")
98+
- `prefix` (str): 모든 라우터에 추가할 프리픽스 (기본값: "")
99+
100+
**동작:**
101+
1. 지정된 디렉토리를 재귀적으로 탐색
102+
2. `.py` 파일에서 `APIRouter` 인스턴스를 찾음
103+
3. 디렉토리 구조를 기반으로 API 경로 생성
104+
4. FastAPI 앱에 라우터 등록
105+
106+
## 개발
107+
108+
### 의존성 설치
109+
110+
```bash
111+
# 개발 의존성 설치
112+
uv sync
113+
```
114+
115+
### 테스트 실행
116+
117+
```bash
118+
# 모든 테스트 실행
119+
uv run pytest
120+
```
121+
122+
### 코드 품질 검사
123+
124+
```bash
125+
# 린팅
126+
ruff check src/ tests/
127+
128+
# 포맷팅
129+
ruff format src/ tests/
130+
```
131+
132+
## 라이선스
133+
134+
이 프로젝트는 아파치 라이선스 2.0 하에 배포됩니다. 자세한 내용은 [LICENSE](LICENSE) 파일을 참조하세요.
135+
136+
## 기여
137+
138+
버그 리포트, 기능 요청, 풀 리퀘스트를 환영합니다! 기여하기 전에 이슈를 먼저 생성해 주세요.
139+
140+
## 작성자
141+
142+
- **owjs3901** - *초기 작업* - [owjs3901@gmail.com](mailto:owjs3901@gmail.com)

0 commit comments

Comments
 (0)