runapi 0.1.3__tar.gz → 0.3.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {runapi-0.1.3 → runapi-0.3.0}/.gitignore +6 -0
- {runapi-0.1.3 → runapi-0.3.0}/PKG-INFO +142 -105
- {runapi-0.1.3 → runapi-0.3.0}/README.md +115 -89
- runapi-0.3.0/examples/basic/README.md +15 -0
- {runapi-0.1.3 → runapi-0.3.0}/pyproject.toml +46 -19
- runapi-0.3.0/release-notes/README.md +7 -0
- {runapi-0.1.3 → runapi-0.3.0}/runapi/__init__.py +31 -1
- runapi-0.3.0/runapi/_version.py +24 -0
- {runapi-0.1.3 → runapi-0.3.0}/runapi/auth.py +81 -22
- runapi-0.3.0/runapi/backends.py +156 -0
- runapi-0.3.0/runapi/cli/__init__.py +53 -0
- runapi-0.3.0/runapi/cli/_app.py +7 -0
- runapi-0.3.0/runapi/cli/_templates.py +28 -0
- runapi-0.3.0/runapi/cli/commands/__init__.py +1 -0
- runapi-0.3.0/runapi/cli/commands/db.py +69 -0
- runapi-0.3.0/runapi/cli/commands/generate.py +153 -0
- runapi-0.3.0/runapi/cli/commands/inspect.py +214 -0
- runapi-0.3.0/runapi/cli/commands/project.py +74 -0
- runapi-0.3.0/runapi/cli/commands/server.py +186 -0
- runapi-0.3.0/runapi/cli/templates/generate/crud_index.py.tmpl +19 -0
- runapi-0.3.0/runapi/cli/templates/generate/crud_item.py.tmpl +20 -0
- runapi-0.3.0/runapi/cli/templates/generate/crud_service_footer.py.tmpl +14 -0
- runapi-0.3.0/runapi/cli/templates/generate/main.py.tmpl +23 -0
- runapi-0.3.0/runapi/cli/templates/generate/middleware.py.tmpl +31 -0
- runapi-0.3.0/runapi/cli/templates/generate/repository.py.tmpl +72 -0
- runapi-0.3.0/runapi/cli/templates/generate/route.py.tmpl +38 -0
- runapi-0.3.0/runapi/cli/templates/generate/schema.py.tmpl +49 -0
- runapi-0.3.0/runapi/cli/templates/generate/service.py.tmpl +101 -0
- runapi-0.3.0/runapi/cli/templates/project/Dockerfile.tmpl +16 -0
- runapi-0.3.0/runapi/cli/templates/project/README.md.tmpl +56 -0
- runapi-0.3.0/runapi/cli/templates/project/dockerignore.tmpl +5 -0
- runapi-0.3.0/runapi/cli/templates/project/env.tmpl +23 -0
- runapi-0.3.0/runapi/cli/templates/project/gitignore.tmpl +26 -0
- runapi-0.3.0/runapi/cli/templates/project/main.py.tmpl +17 -0
- runapi-0.3.0/runapi/cli/templates/project/route_hello.py.tmpl +12 -0
- runapi-0.3.0/runapi/cli/templates/project/route_index.py.tmpl +14 -0
- runapi-0.3.0/runapi/config.py +188 -0
- {runapi-0.1.3 → runapi-0.3.0}/runapi/core.py +85 -78
- {runapi-0.1.3 → runapi-0.3.0}/runapi/errors.py +50 -19
- runapi-0.3.0/runapi/lifecycle.py +77 -0
- runapi-0.3.0/runapi/logging.py +98 -0
- {runapi-0.1.3 → runapi-0.3.0}/runapi/middleware.py +49 -54
- runapi-0.3.0/runapi/py.typed +0 -0
- {runapi-0.1.3 → runapi-0.3.0}/runapi/repository.py +5 -4
- runapi-0.3.0/runapi/routing.py +122 -0
- {runapi-0.1.3 → runapi-0.3.0}/runapi/schemas.py +6 -4
- {runapi-0.1.3 → runapi-0.3.0}/runapi/service.py +5 -4
- runapi-0.1.3/.github/ISSUE_TEMPLATE/bug_report.md +0 -27
- runapi-0.1.3/.github/ISSUE_TEMPLATE/documentation.md +0 -14
- runapi-0.1.3/.github/ISSUE_TEMPLATE/feature_request.md +0 -17
- runapi-0.1.3/.github/PULL_REQUEST_TEMPLATE.md +0 -24
- runapi-0.1.3/.github/workflows/publish.yml +0 -196
- runapi-0.1.3/CONTRIBUTING.md +0 -216
- runapi-0.1.3/MANIFEST.in +0 -18
- runapi-0.1.3/runapi/cli.py +0 -1085
- runapi-0.1.3/runapi/config.py +0 -143
- runapi-0.1.3/tests/final_test.py +0 -377
- runapi-0.1.3/tests/simple_test.py +0 -188
- runapi-0.1.3/tests/test_runapi.py +0 -1080
- runapi-0.1.3/tests/test_runapi_installation.py +0 -374
- {runapi-0.1.3 → runapi-0.3.0}/LICENSE +0 -0
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
2
|
Name: runapi
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.0
|
|
4
4
|
Summary: A Next.js-inspired file-based routing framework built on FastAPI
|
|
5
5
|
Project-URL: Homepage, https://github.com/Amanbig/runapi
|
|
6
6
|
Project-URL: Repository, https://github.com/Amanbig/runapi
|
|
7
|
-
Project-URL: Documentation, https://github.com/Amanbig/runapi
|
|
7
|
+
Project-URL: Documentation, https://github.com/Amanbig/runapi/tree/main/docs
|
|
8
8
|
Project-URL: Issues, https://github.com/Amanbig/runapi/issues
|
|
9
|
-
Project-URL: Changelog, https://github.com/Amanbig/runapi/
|
|
9
|
+
Project-URL: Changelog, https://github.com/Amanbig/runapi/tree/main/release-notes
|
|
10
10
|
Author-email: Amanpreet Singh <amanpreetsinghjhiwant7@gmail.com>
|
|
11
11
|
License: MIT License
|
|
12
12
|
|
|
@@ -38,56 +38,105 @@ Classifier: Intended Audience :: Developers
|
|
|
38
38
|
Classifier: License :: OSI Approved :: MIT License
|
|
39
39
|
Classifier: Operating System :: OS Independent
|
|
40
40
|
Classifier: Programming Language :: Python :: 3
|
|
41
|
-
Classifier: Programming Language :: Python :: 3.8
|
|
42
|
-
Classifier: Programming Language :: Python :: 3.9
|
|
43
41
|
Classifier: Programming Language :: Python :: 3.10
|
|
44
42
|
Classifier: Programming Language :: Python :: 3.11
|
|
45
43
|
Classifier: Programming Language :: Python :: 3.12
|
|
44
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
46
45
|
Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
|
|
47
46
|
Classifier: Topic :: Internet :: WWW/HTTP :: WSGI :: Application
|
|
48
47
|
Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
|
|
49
48
|
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
50
49
|
Classifier: Typing :: Typed
|
|
51
|
-
Requires-Python: >=3.
|
|
52
|
-
Requires-Dist: aiofiles>=23.
|
|
53
|
-
Requires-Dist:
|
|
54
|
-
Requires-Dist:
|
|
55
|
-
Requires-Dist: psutil>=
|
|
56
|
-
Requires-Dist:
|
|
57
|
-
Requires-Dist:
|
|
58
|
-
Requires-Dist:
|
|
59
|
-
Requires-Dist:
|
|
60
|
-
Requires-Dist:
|
|
50
|
+
Requires-Python: >=3.10
|
|
51
|
+
Requires-Dist: aiofiles>=23.2.1
|
|
52
|
+
Requires-Dist: bcrypt>=4.0.1
|
|
53
|
+
Requires-Dist: fastapi>=0.115.6
|
|
54
|
+
Requires-Dist: psutil>=6.0.0
|
|
55
|
+
Requires-Dist: pydantic-settings>=2.2
|
|
56
|
+
Requires-Dist: pyjwt>=2.10.1
|
|
57
|
+
Requires-Dist: python-multipart>=0.0.18
|
|
58
|
+
Requires-Dist: rich>=13.7.0
|
|
59
|
+
Requires-Dist: typer>=0.12.0
|
|
60
|
+
Requires-Dist: uvicorn>=0.30.0
|
|
61
|
+
Provides-Extra: db
|
|
62
|
+
Requires-Dist: aiosqlite>=0.19; extra == 'db'
|
|
63
|
+
Requires-Dist: alembic>=1.13; extra == 'db'
|
|
64
|
+
Requires-Dist: sqlalchemy[asyncio]>=2.0; extra == 'db'
|
|
61
65
|
Provides-Extra: dev
|
|
62
66
|
Requires-Dist: httpx>=0.24.0; extra == 'dev'
|
|
63
67
|
Requires-Dist: mypy>=1.0.0; extra == 'dev'
|
|
64
68
|
Requires-Dist: pytest>=7.0.0; extra == 'dev'
|
|
65
69
|
Requires-Dist: ruff>=0.1.0; extra == 'dev'
|
|
70
|
+
Provides-Extra: docs
|
|
71
|
+
Requires-Dist: mkdocs-material>=9.5; extra == 'docs'
|
|
72
|
+
Requires-Dist: mkdocs>=1.6; extra == 'docs'
|
|
66
73
|
Provides-Extra: lint
|
|
67
74
|
Requires-Dist: mypy>=1.0.0; extra == 'lint'
|
|
68
75
|
Requires-Dist: ruff>=0.1.0; extra == 'lint'
|
|
76
|
+
Provides-Extra: redis
|
|
77
|
+
Requires-Dist: redis>=5.0; extra == 'redis'
|
|
69
78
|
Provides-Extra: test
|
|
79
|
+
Requires-Dist: fakeredis>=2.20; extra == 'test'
|
|
70
80
|
Requires-Dist: httpx>=0.24.0; extra == 'test'
|
|
71
81
|
Requires-Dist: pytest-asyncio>=0.21.0; extra == 'test'
|
|
72
82
|
Requires-Dist: pytest-cov>=4.0.0; extra == 'test'
|
|
73
83
|
Requires-Dist: pytest>=7.0.0; extra == 'test'
|
|
84
|
+
Requires-Dist: redis>=5.0; extra == 'test'
|
|
74
85
|
Description-Content-Type: text/markdown
|
|
75
86
|
|
|
76
87
|
# Runapi 🚀
|
|
77
88
|
|
|
78
89
|
[](https://badge.fury.io/py/runapi)
|
|
79
|
-
[](https://www.python.org/downloads/)
|
|
80
91
|
[](https://opensource.org/licenses/MIT)
|
|
81
92
|
|
|
82
93
|
A Next.js-inspired file-based routing framework built on FastAPI for Python backend development. runapi makes building robust APIs as intuitive as creating files and folders.
|
|
83
94
|
|
|
84
|
-
## Why
|
|
95
|
+
## Why runapi?
|
|
96
|
+
|
|
97
|
+
- **Enhanced Developer Experience**: Inspired by Next.js, runapi provides an intuitive environment for backend development.
|
|
98
|
+
- **High Performance**: Built upon FastAPI, leveraging one of the most efficient Python web frameworks available.
|
|
99
|
+
- **Production-Ready Core**: Includes integrated security, middleware, and standardized error handling.
|
|
100
|
+
- **Strict Type Safety**: Comprehensive typing support with automated Pydantic validation.
|
|
101
|
+
- **Intuitive Routing**: Implements file-based routing where the directory structure defines the API surface.
|
|
102
|
+
|
|
103
|
+
## Comparative Analysis: FastAPI vs. runapi
|
|
104
|
+
|
|
105
|
+
runapi is an extension of the FastAPI framework, introducing standardized architectural patterns and conventions to streamline the development lifecycle.
|
|
106
|
+
|
|
107
|
+
| Feature | FastAPI | runapi |
|
|
108
|
+
| :--- | :--- | :--- |
|
|
109
|
+
| **Routing Mechanism** | Explicit registration via decorators | **Automated file-based routing** |
|
|
110
|
+
| **Architectural Pattern** | Unopinionated / Custom | **Opinionated (Service-Repository)** |
|
|
111
|
+
| **Initialization** | Manual configuration | **Automated discovery** and CLI-driven generation |
|
|
112
|
+
| **Boilerplate Requirements** | Higher in enterprise-scale applications | **Significantly reduced** through convention |
|
|
113
|
+
| **Abstraction Level** | Low-level / Direct access | High-level with underlying FastAPI access |
|
|
114
|
+
| **Primary Use Case** | Bespoke or highly specialized architectures | **Rapid application development** and team consistency |
|
|
115
|
+
|
|
116
|
+
### Architectural Trade-offs: Choosing runapi over Vanilla FastAPI
|
|
117
|
+
|
|
118
|
+
Adopting runapi instead of standard FastAPI involves a strategic exchange of granular control for architectural standardization and development speed.
|
|
119
|
+
|
|
120
|
+
| Feature | The runapi Advantage | The FastAPI Trade-off |
|
|
121
|
+
| :--- | :--- | :--- |
|
|
122
|
+
| **Development Speed vs. Granular Control** | **Accelerated Time-to-Market**: Automates route discovery and boilerplate generation, allowing developers to focus on business logic immediately. | **Reduced Configuration Control**: Developers relinquish explicit control over how and where individual routes are instantiated and registered within the application lifecycle. |
|
|
123
|
+
| **Standardization vs. Flexibility** | **Enforced Best Practices**: Implements a consistent Service-Repository pattern that ensures codebase maintainability and simplifies onboarding in team environments. | **Constrained Architectural Freedom**: The framework requires strict adherence to its directory structure (`routes/`, `services/`, etc.), which may conflict with highly customized or legacy architectural requirements. |
|
|
124
|
+
| **Abstraction vs. Transparency** | **High-Level Productivity**: Hides complex FastAPI and Pydantic configurations behind simplified interfaces (e.g., `CRUDService`, `BaseSchema`). | **Increased Debugging Complexity**: The additional abstraction layer can obscure the underlying FastAPI behavior, potentially complicating the diagnostic process for edge-case bugs or performance tuning. |
|
|
125
|
+
| **Ecosystem Integration** | **Seamless Defaults**: Provides pre-configured, production-ready middleware (CORS, JWT, Rate Limiting) that follows industry standards. | **Compatibility Considerations**: While built on FastAPI, some highly specialized third-party FastAPI plugins may require manual adaptation to integrate with runapi's automated lifecycle. |
|
|
126
|
+
|
|
127
|
+
### Strategic Implementation Criteria
|
|
128
|
+
|
|
129
|
+
#### Criteria for Selecting runapi
|
|
130
|
+
- Requirement for accelerated development cycles with minimal configuration overhead.
|
|
131
|
+
- Preference for **file-based routing** over manual route registration.
|
|
132
|
+
- Necessity for a **standardized architectural framework** (Services, Repositories, Schemas).
|
|
133
|
+
- Objective to minimize repetitive code for standard operations such as Authentication and CRUD.
|
|
134
|
+
|
|
135
|
+
#### Criteria for Selecting Plain FastAPI
|
|
136
|
+
- Requirement for absolute control over every aspect of the system architecture.
|
|
137
|
+
- Development of highly specialized or non-standard systems.
|
|
138
|
+
- Preference for explicit route registration and manual configuration over system conventions.
|
|
85
139
|
|
|
86
|
-
- 🚀 **Developer Experience**: Just like Next.js for React, runapi makes backend development intuitive
|
|
87
|
-
- ⚡ **Performance**: Built on FastAPI, one of the fastest Python frameworks
|
|
88
|
-
- 🛡️ **Production Ready**: Security, middleware, and error handling built-in
|
|
89
|
-
- 🎯 **Type Safe**: Full typing support with automatic validation
|
|
90
|
-
- 📁 **Intuitive**: File-based routing means your folder structure IS your API
|
|
91
140
|
|
|
92
141
|
## Features
|
|
93
142
|
|
|
@@ -112,7 +161,7 @@ pip install runapi
|
|
|
112
161
|
|
|
113
162
|
## Requirements
|
|
114
163
|
|
|
115
|
-
- Python 3.
|
|
164
|
+
- Python 3.10+
|
|
116
165
|
- FastAPI
|
|
117
166
|
- Uvicorn (for development server)
|
|
118
167
|
|
|
@@ -175,6 +224,7 @@ Routes are created by adding Python files in the `routes/` directory:
|
|
|
175
224
|
```python
|
|
176
225
|
from runapi import JSONResponse
|
|
177
226
|
|
|
227
|
+
|
|
178
228
|
async def get():
|
|
179
229
|
return JSONResponse({"message": "Hello runapi!"})
|
|
180
230
|
```
|
|
@@ -183,9 +233,11 @@ async def get():
|
|
|
183
233
|
```python
|
|
184
234
|
from runapi import JSONResponse, Request
|
|
185
235
|
|
|
236
|
+
|
|
186
237
|
async def get():
|
|
187
238
|
return JSONResponse({"users": []})
|
|
188
239
|
|
|
240
|
+
|
|
189
241
|
async def post(request: Request):
|
|
190
242
|
body = await request.json()
|
|
191
243
|
return JSONResponse({"created": body})
|
|
@@ -195,15 +247,18 @@ async def post(request: Request):
|
|
|
195
247
|
```python
|
|
196
248
|
from runapi import JSONResponse, Request
|
|
197
249
|
|
|
250
|
+
|
|
198
251
|
async def get(request: Request):
|
|
199
252
|
user_id = request.path_params["id"]
|
|
200
253
|
return JSONResponse({"user_id": user_id})
|
|
201
254
|
|
|
255
|
+
|
|
202
256
|
async def put(request: Request):
|
|
203
257
|
user_id = request.path_params["id"]
|
|
204
258
|
body = await request.json()
|
|
205
259
|
return JSONResponse({"user_id": user_id, "updated": body})
|
|
206
260
|
|
|
261
|
+
|
|
207
262
|
async def delete(request: Request):
|
|
208
263
|
user_id = request.path_params["id"]
|
|
209
264
|
return JSONResponse({"user_id": user_id, "deleted": True})
|
|
@@ -275,20 +330,24 @@ from runapi import BaseSchema, IDMixin, TimestampMixin
|
|
|
275
330
|
from pydantic import Field
|
|
276
331
|
from typing import Optional
|
|
277
332
|
|
|
333
|
+
|
|
278
334
|
# Base schema with ORM support and validation
|
|
279
335
|
class UserBase(BaseSchema):
|
|
280
336
|
email: str = Field(..., description="User email")
|
|
281
337
|
name: str = Field(..., min_length=1, max_length=100)
|
|
282
338
|
|
|
339
|
+
|
|
283
340
|
# Schema for creating (no ID, no timestamps)
|
|
284
341
|
class UserCreate(UserBase):
|
|
285
342
|
password: str = Field(..., min_length=8)
|
|
286
343
|
|
|
344
|
+
|
|
287
345
|
# Schema for updating (all fields optional)
|
|
288
346
|
class UserUpdate(BaseSchema):
|
|
289
347
|
email: Optional[str] = None
|
|
290
348
|
name: Optional[str] = None
|
|
291
349
|
|
|
350
|
+
|
|
292
351
|
# Schema for responses (includes ID and timestamps)
|
|
293
352
|
class UserResponse(UserBase, IDMixin, TimestampMixin):
|
|
294
353
|
pass
|
|
@@ -298,28 +357,23 @@ class UserResponse(UserBase, IDMixin, TimestampMixin):
|
|
|
298
357
|
|
|
299
358
|
```python
|
|
300
359
|
from runapi import (
|
|
301
|
-
BaseSchema,
|
|
302
|
-
IDMixin,
|
|
303
|
-
TimestampMixin,
|
|
304
|
-
MessageResponse,
|
|
305
|
-
PaginatedResponse,
|
|
306
|
-
PaginationParams,
|
|
360
|
+
BaseSchema, # Base with ORM mode, validation
|
|
361
|
+
IDMixin, # Adds 'id: int' field
|
|
362
|
+
TimestampMixin, # Adds 'created_at', 'updated_at'
|
|
363
|
+
MessageResponse, # Simple {"message": str, "success": bool}
|
|
364
|
+
PaginatedResponse, # Generic paginated list wrapper
|
|
365
|
+
PaginationParams, # Query params with offset/limit
|
|
307
366
|
)
|
|
308
367
|
|
|
309
368
|
# Pagination example
|
|
310
369
|
from runapi import PaginatedResponse, PaginationParams
|
|
311
370
|
|
|
371
|
+
|
|
312
372
|
async def get_users(params: PaginationParams):
|
|
313
|
-
users = await user_service.get_all(
|
|
314
|
-
skip=params.offset,
|
|
315
|
-
limit=params.limit
|
|
316
|
-
)
|
|
373
|
+
users = await user_service.get_all(skip=params.offset, limit=params.limit)
|
|
317
374
|
total = await user_service.count()
|
|
318
375
|
return PaginatedResponse.create(
|
|
319
|
-
items=users,
|
|
320
|
-
total=total,
|
|
321
|
-
page=params.page,
|
|
322
|
-
page_size=params.page_size
|
|
376
|
+
items=users, total=total, page=params.page, page_size=params.page_size
|
|
323
377
|
)
|
|
324
378
|
```
|
|
325
379
|
|
|
@@ -330,6 +384,7 @@ async def get_users(params: PaginationParams):
|
|
|
330
384
|
from runapi import JSONResponse, Request
|
|
331
385
|
from schemas.user import UserCreate, UserResponse
|
|
332
386
|
|
|
387
|
+
|
|
333
388
|
async def post(request: Request):
|
|
334
389
|
body = await request.json()
|
|
335
390
|
user_data = UserCreate(**body) # Validates input
|
|
@@ -352,6 +407,7 @@ runapi generate repository user
|
|
|
352
407
|
```python
|
|
353
408
|
from runapi import InMemoryRepository
|
|
354
409
|
|
|
410
|
+
|
|
355
411
|
class UserRepository(InMemoryRepository):
|
|
356
412
|
"""In-memory storage - great for development/testing."""
|
|
357
413
|
|
|
@@ -361,6 +417,7 @@ class UserRepository(InMemoryRepository):
|
|
|
361
417
|
async def find_active_users(self):
|
|
362
418
|
return await self.get_many_by(is_active=True)
|
|
363
419
|
|
|
420
|
+
|
|
364
421
|
# Usage
|
|
365
422
|
repo = UserRepository()
|
|
366
423
|
user = await repo.create({"name": "John", "email": "john@example.com"})
|
|
@@ -375,6 +432,7 @@ await repo.delete(1)
|
|
|
375
432
|
from runapi import TypedInMemoryRepository
|
|
376
433
|
from schemas.user import UserResponse
|
|
377
434
|
|
|
435
|
+
|
|
378
436
|
class UserRepository(TypedInMemoryRepository[UserResponse]):
|
|
379
437
|
def __init__(self):
|
|
380
438
|
super().__init__(UserResponse)
|
|
@@ -382,6 +440,7 @@ class UserRepository(TypedInMemoryRepository[UserResponse]):
|
|
|
382
440
|
async def find_by_email(self, email: str):
|
|
383
441
|
return await self.get_by(email=email)
|
|
384
442
|
|
|
443
|
+
|
|
385
444
|
# Returns UserResponse instances, not dicts
|
|
386
445
|
user = await repo.create({"name": "John", "email": "john@example.com"})
|
|
387
446
|
assert isinstance(user, UserResponse)
|
|
@@ -394,6 +453,7 @@ from runapi import SQLAlchemyRepository, SQLALCHEMY_AVAILABLE
|
|
|
394
453
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
395
454
|
|
|
396
455
|
if SQLALCHEMY_AVAILABLE:
|
|
456
|
+
|
|
397
457
|
class UserRepository(SQLAlchemyRepository[UserModel, int]):
|
|
398
458
|
def __init__(self, session: AsyncSession):
|
|
399
459
|
super().__init__(session, UserModel)
|
|
@@ -432,6 +492,7 @@ runapi generate service user
|
|
|
432
492
|
```python
|
|
433
493
|
from runapi import CRUDService, InMemoryRepository
|
|
434
494
|
|
|
495
|
+
|
|
435
496
|
class UserService(CRUDService):
|
|
436
497
|
"""Inherits all CRUD operations with error handling."""
|
|
437
498
|
|
|
@@ -445,6 +506,7 @@ class UserService(CRUDService):
|
|
|
445
506
|
async def deactivate(self, user_id: int):
|
|
446
507
|
return await self.update(user_id, {"is_active": False})
|
|
447
508
|
|
|
509
|
+
|
|
448
510
|
# Usage
|
|
449
511
|
user_repo = UserRepository()
|
|
450
512
|
user_service = UserService(user_repo, entity_name="User")
|
|
@@ -463,16 +525,16 @@ await user_service.delete(1) # Raises NotFoundError if missing
|
|
|
463
525
|
from runapi import ValidatedService
|
|
464
526
|
from schemas.user import UserCreate, UserUpdate
|
|
465
527
|
|
|
528
|
+
|
|
466
529
|
class UserService(ValidatedService):
|
|
467
530
|
create_schema = UserCreate # Auto-validates on create
|
|
468
531
|
update_schema = UserUpdate # Auto-validates on update
|
|
469
532
|
|
|
533
|
+
|
|
470
534
|
# Input is validated against schemas automatically
|
|
471
|
-
user = await user_service.create(
|
|
472
|
-
"name": "John",
|
|
473
|
-
|
|
474
|
-
"password": "secure123"
|
|
475
|
-
})
|
|
535
|
+
user = await user_service.create(
|
|
536
|
+
{"name": "John", "email": "john@example.com", "password": "secure123"}
|
|
537
|
+
)
|
|
476
538
|
```
|
|
477
539
|
|
|
478
540
|
### Complete Example: Routes + Service + Repository
|
|
@@ -481,19 +543,23 @@ user = await user_service.create({
|
|
|
481
543
|
# repositories/user.py
|
|
482
544
|
from runapi import InMemoryRepository
|
|
483
545
|
|
|
546
|
+
|
|
484
547
|
class UserRepository(InMemoryRepository):
|
|
485
548
|
async def find_by_email(self, email: str):
|
|
486
549
|
return await self.get_by(email=email)
|
|
487
550
|
|
|
551
|
+
|
|
488
552
|
# services/user.py
|
|
489
553
|
from runapi import CRUDService, ValidationError
|
|
490
554
|
|
|
555
|
+
|
|
491
556
|
class UserService(CRUDService):
|
|
492
557
|
async def register(self, data: dict):
|
|
493
558
|
if await self.repository.get_by(email=data["email"]):
|
|
494
559
|
raise ValidationError("Email exists")
|
|
495
560
|
return await self.create(data)
|
|
496
561
|
|
|
562
|
+
|
|
497
563
|
# routes/api/users.py
|
|
498
564
|
from runapi import JSONResponse, Request
|
|
499
565
|
from repositories.user import UserRepository
|
|
@@ -502,10 +568,12 @@ from services.user import UserService
|
|
|
502
568
|
user_repo = UserRepository()
|
|
503
569
|
user_service = UserService(user_repo, "User")
|
|
504
570
|
|
|
571
|
+
|
|
505
572
|
async def get():
|
|
506
573
|
users = await user_service.get_all()
|
|
507
574
|
return JSONResponse(users)
|
|
508
575
|
|
|
576
|
+
|
|
509
577
|
async def post(request: Request):
|
|
510
578
|
body = await request.json()
|
|
511
579
|
user = await user_service.register(body)
|
|
@@ -518,8 +586,8 @@ async def post(request: Request):
|
|
|
518
586
|
from runapi import validate_input, require_exists, log_operation
|
|
519
587
|
from schemas.user import UserCreate
|
|
520
588
|
|
|
521
|
-
class UserService(CRUDService):
|
|
522
589
|
|
|
590
|
+
class UserService(CRUDService):
|
|
523
591
|
@validate_input(UserCreate)
|
|
524
592
|
async def create(self, data: dict):
|
|
525
593
|
return await self.repository.create(data)
|
|
@@ -602,8 +670,7 @@ app = create_runapi_app()
|
|
|
602
670
|
|
|
603
671
|
# Protect specific routes
|
|
604
672
|
app.add_auth_middleware(
|
|
605
|
-
protected_paths=["/api/protected"],
|
|
606
|
-
excluded_paths=["/api/auth/login", "/docs"]
|
|
673
|
+
protected_paths=["/api/protected"], excluded_paths=["/api/auth/login", "/docs"]
|
|
607
674
|
)
|
|
608
675
|
```
|
|
609
676
|
|
|
@@ -613,17 +680,18 @@ app.add_auth_middleware(
|
|
|
613
680
|
```python
|
|
614
681
|
from runapi import JSONResponse, Request, create_token_response, verify_password
|
|
615
682
|
|
|
683
|
+
|
|
616
684
|
async def post(request: Request):
|
|
617
685
|
body = await request.json()
|
|
618
686
|
username = body.get("username")
|
|
619
687
|
password = body.get("password")
|
|
620
|
-
|
|
688
|
+
|
|
621
689
|
# Verify credentials (implement your logic)
|
|
622
690
|
if verify_credentials(username, password):
|
|
623
691
|
user_data = {"sub": "user_id", "username": username}
|
|
624
692
|
tokens = create_token_response(user_data)
|
|
625
693
|
return JSONResponse(tokens.dict())
|
|
626
|
-
|
|
694
|
+
|
|
627
695
|
return JSONResponse({"error": "Invalid credentials"}, status_code=401)
|
|
628
696
|
```
|
|
629
697
|
|
|
@@ -633,11 +701,9 @@ async def post(request: Request):
|
|
|
633
701
|
```python
|
|
634
702
|
from runapi import JSONResponse, get_current_user, Depends
|
|
635
703
|
|
|
704
|
+
|
|
636
705
|
async def get(current_user: dict = Depends(get_current_user())):
|
|
637
|
-
return JSONResponse({
|
|
638
|
-
"message": "This is protected!",
|
|
639
|
-
"user": current_user
|
|
640
|
-
})
|
|
706
|
+
return JSONResponse({"message": "This is protected!", "user": current_user})
|
|
641
707
|
```
|
|
642
708
|
|
|
643
709
|
## Middleware
|
|
@@ -651,7 +717,7 @@ app = create_runapi_app()
|
|
|
651
717
|
|
|
652
718
|
# Built-in middleware (automatically configured via .env)
|
|
653
719
|
# - CORS
|
|
654
|
-
# - Rate limiting
|
|
720
|
+
# - Rate limiting
|
|
655
721
|
# - Security headers
|
|
656
722
|
# - Request logging
|
|
657
723
|
# - Compression
|
|
@@ -659,6 +725,7 @@ app = create_runapi_app()
|
|
|
659
725
|
# Add custom middleware
|
|
660
726
|
from runapi import RunApiMiddleware
|
|
661
727
|
|
|
728
|
+
|
|
662
729
|
class CustomMiddleware(RunApiMiddleware):
|
|
663
730
|
async def dispatch(self, request, call_next):
|
|
664
731
|
# Pre-processing
|
|
@@ -666,6 +733,7 @@ class CustomMiddleware(RunApiMiddleware):
|
|
|
666
733
|
# Post-processing
|
|
667
734
|
return response
|
|
668
735
|
|
|
736
|
+
|
|
669
737
|
app.add_middleware(CustomMiddleware)
|
|
670
738
|
```
|
|
671
739
|
|
|
@@ -676,14 +744,15 @@ runapi provides comprehensive error handling:
|
|
|
676
744
|
```python
|
|
677
745
|
from runapi import ValidationError, NotFoundError, raise_not_found
|
|
678
746
|
|
|
747
|
+
|
|
679
748
|
async def get_user(user_id: str):
|
|
680
749
|
if not user_id:
|
|
681
750
|
raise ValidationError("User ID is required")
|
|
682
|
-
|
|
751
|
+
|
|
683
752
|
user = find_user(user_id)
|
|
684
753
|
if not user:
|
|
685
754
|
raise_not_found("User not found")
|
|
686
|
-
|
|
755
|
+
|
|
687
756
|
return user
|
|
688
757
|
```
|
|
689
758
|
|
|
@@ -743,20 +812,18 @@ from runapi import create_runapi_app, get_config
|
|
|
743
812
|
config = get_config()
|
|
744
813
|
|
|
745
814
|
# Create app with custom settings
|
|
746
|
-
app = create_runapi_app(
|
|
747
|
-
title="My API",
|
|
748
|
-
description="Built with runapi",
|
|
749
|
-
version="1.0.0"
|
|
750
|
-
)
|
|
815
|
+
app = create_runapi_app(title="My API", description="Built with runapi", version="1.0.0")
|
|
751
816
|
|
|
752
817
|
# Add custom middleware
|
|
753
818
|
app.add_auth_middleware()
|
|
754
819
|
|
|
820
|
+
|
|
755
821
|
# Add custom startup/shutdown events
|
|
756
822
|
@app.get_app().on_event("startup")
|
|
757
823
|
async def startup():
|
|
758
824
|
print("Starting up!")
|
|
759
825
|
|
|
826
|
+
|
|
760
827
|
# Get underlying FastAPI app
|
|
761
828
|
fastapi_app = app.get_app()
|
|
762
829
|
```
|
|
@@ -771,6 +838,7 @@ from runapi import get_config
|
|
|
771
838
|
config = get_config()
|
|
772
839
|
engine = create_engine(config.database_url)
|
|
773
840
|
|
|
841
|
+
|
|
774
842
|
# Use in routes
|
|
775
843
|
async def get_users():
|
|
776
844
|
# Your database logic here
|
|
@@ -783,10 +851,12 @@ async def get_users():
|
|
|
783
851
|
from fastapi import BackgroundTasks
|
|
784
852
|
from runapi import JSONResponse
|
|
785
853
|
|
|
854
|
+
|
|
786
855
|
async def send_email(email: str):
|
|
787
856
|
# Send email logic
|
|
788
857
|
pass
|
|
789
858
|
|
|
859
|
+
|
|
790
860
|
async def post(request: Request, background_tasks: BackgroundTasks):
|
|
791
861
|
body = await request.json()
|
|
792
862
|
background_tasks.add_task(send_email, body["email"])
|
|
@@ -807,6 +877,7 @@ runapi supports dynamic route parameters:
|
|
|
807
877
|
from fastapi import UploadFile, File
|
|
808
878
|
from runapi import JSONResponse
|
|
809
879
|
|
|
880
|
+
|
|
810
881
|
async def post(file: UploadFile = File(...)):
|
|
811
882
|
contents = await file.read()
|
|
812
883
|
# Process file
|
|
@@ -821,6 +892,7 @@ from main import app
|
|
|
821
892
|
|
|
822
893
|
client = TestClient(app.get_app())
|
|
823
894
|
|
|
895
|
+
|
|
824
896
|
def test_read_main():
|
|
825
897
|
response = client.get("/")
|
|
826
898
|
assert response.status_code == 200
|
|
@@ -833,7 +905,7 @@ def test_read_main():
|
|
|
833
905
|
|
|
834
906
|
**Dockerfile**
|
|
835
907
|
```dockerfile
|
|
836
|
-
FROM python:3.
|
|
908
|
+
FROM python:3.12-slim
|
|
837
909
|
|
|
838
910
|
WORKDIR /app
|
|
839
911
|
COPY requirements.txt .
|
|
@@ -863,6 +935,7 @@ from runapi import get_app
|
|
|
863
935
|
|
|
864
936
|
app = get_app()
|
|
865
937
|
|
|
938
|
+
|
|
866
939
|
@app.websocket("/ws/chat")
|
|
867
940
|
async def websocket_endpoint(websocket: WebSocket):
|
|
868
941
|
await websocket.accept()
|
|
@@ -993,19 +1066,20 @@ async def patch(): # PATCH request
|
|
|
993
1066
|
```python
|
|
994
1067
|
from runapi import Request, JSONResponse
|
|
995
1068
|
|
|
1069
|
+
|
|
996
1070
|
async def post(request: Request):
|
|
997
1071
|
# Get JSON body
|
|
998
1072
|
body = await request.json()
|
|
999
|
-
|
|
1073
|
+
|
|
1000
1074
|
# Get path parameters
|
|
1001
1075
|
user_id = request.path_params.get("id")
|
|
1002
|
-
|
|
1076
|
+
|
|
1003
1077
|
# Get query parameters
|
|
1004
1078
|
limit = request.query_params.get("limit", 10)
|
|
1005
|
-
|
|
1079
|
+
|
|
1006
1080
|
# Get headers
|
|
1007
1081
|
auth_header = request.headers.get("authorization")
|
|
1008
|
-
|
|
1082
|
+
|
|
1009
1083
|
return JSONResponse({"status": "success"})
|
|
1010
1084
|
```
|
|
1011
1085
|
|
|
@@ -1140,44 +1214,7 @@ Please include:
|
|
|
1140
1214
|
|
|
1141
1215
|
## Changelog
|
|
1142
1216
|
|
|
1143
|
-
|
|
1144
|
-
- **New Feature**: Schema layer with auto-discovery from `schemas/` directory
|
|
1145
|
-
- **New Feature**: `BaseSchema`, `IDMixin`, `TimestampMixin` for consistent model definitions
|
|
1146
|
-
- **New Feature**: `PaginatedResponse` and `PaginationParams` for pagination support
|
|
1147
|
-
- **New Feature**: Repository pattern with `BaseRepository`, `InMemoryRepository`, `TypedInMemoryRepository`
|
|
1148
|
-
- **New Feature**: Optional `SQLAlchemyRepository` for async database support
|
|
1149
|
-
- **New Feature**: Service layer with `CRUDService`, `ValidatedService`
|
|
1150
|
-
- **New Feature**: Service decorators: `@validate_input`, `@require_exists`, `@log_operation`
|
|
1151
|
-
- **New Feature**: `ServiceFactory` and `RepositoryFactory` for dependency injection
|
|
1152
|
-
- **CLI**: Added `runapi generate schema <name>` command
|
|
1153
|
-
- **CLI**: Added `runapi generate repository <name>` command
|
|
1154
|
-
- **CLI**: Added `runapi generate service <name>` command
|
|
1155
|
-
- **CLI**: Added `runapi schemas` command to list all schemas
|
|
1156
|
-
- **CLI**: Updated `runapi init` to create schemas/, repositories/, services/ directories
|
|
1157
|
-
- **Tests**: Added 20 comprehensive tests covering all new features
|
|
1158
|
-
|
|
1159
|
-
### v0.1.2
|
|
1160
|
-
- **New Feature**: Added `runapi start` command for production deployments (no-reload, multi-worker support)
|
|
1161
|
-
- **Performance**: Optimized startup time by ignoring irrelevant directories during route discovery
|
|
1162
|
-
- **Performance**: Replaced O(N) rate limiting with O(1) Fixed Window Counter algorithm
|
|
1163
|
-
- **Performance**: Implemented streaming compression using `GZipMiddleware` for lower TTFB and memory usage
|
|
1164
|
-
- **Security**: Refactored authentication to use standard `python-jose` library instead of manual implementation
|
|
1165
|
-
- **CLI**: Optimized `runapi dev` startup speed and `runapi routes` robustness
|
|
1166
|
-
|
|
1167
|
-
### v0.1.1
|
|
1168
|
-
- **Bug Fix**: Fixed `runapi dev` command failing to import main module
|
|
1169
|
-
- **Enhancement**: Improved CLI error handling and validation
|
|
1170
|
-
- **Enhancement**: Better Python path management for uvicorn integration
|
|
1171
|
-
- **Enhancement**: Added pre-validation of main.py before server startup
|
|
1172
|
-
|
|
1173
|
-
### v0.1.0
|
|
1174
|
-
- Initial release
|
|
1175
|
-
- File-based routing system
|
|
1176
|
-
- JWT authentication
|
|
1177
|
-
- Middleware stack
|
|
1178
|
-
- CLI tools
|
|
1179
|
-
- Configuration management
|
|
1180
|
-
- Error handling system
|
|
1217
|
+
Per-version notes live in [`release-notes/`](release-notes/) and on the [GitHub Releases](https://github.com/Amanbig/runapi/releases) page. Latest: [`RELEASE_NOTES.md`](RELEASE_NOTES.md).
|
|
1181
1218
|
|
|
1182
1219
|
## License
|
|
1183
1220
|
|
|
@@ -1195,7 +1232,7 @@ This project is licensed under the MIT License - see the LICENSE file for detail
|
|
|
1195
1232
|
- Built on top of [FastAPI](https://fastapi.tiangolo.com/) by Sebastián Ramirez
|
|
1196
1233
|
- Inspired by [Next.js](https://nextjs.org/) file-based routing by Vercel
|
|
1197
1234
|
- Uses [Typer](https://typer.tiangolo.com/) for CLI by Sebastián Ramirez
|
|
1198
|
-
- Password hashing with [
|
|
1235
|
+
- Password hashing with [bcrypt](https://pypi.org/project/bcrypt/)
|
|
1199
1236
|
- Testing with [pytest](https://pytest.org/) and [httpx](https://www.python-httpx.org/)
|
|
1200
1237
|
|
|
1201
1238
|
## Related Projects
|
|
@@ -1220,6 +1257,6 @@ If runapi has been helpful to your project:
|
|
|
1220
1257
|
|
|
1221
1258
|
**runapi** - Making Python backend development as intuitive as frontend development! 🚀
|
|
1222
1259
|
|
|
1223
|
-
[Get Started](https://github.com/Amanbig/runapi) | [Documentation](https://github.com/Amanbig/runapi) | [Examples](https://github.com/Amanbig/runapi/tree/main/
|
|
1260
|
+
[Get Started](https://github.com/Amanbig/runapi) | [Documentation](https://github.com/Amanbig/runapi/tree/main/docs) | [Examples](https://github.com/Amanbig/runapi/tree/main/examples)
|
|
1224
1261
|
|
|
1225
1262
|
</div>
|