runapi 0.1.0__py3-none-any.whl
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/__init__.py +174 -0
- runapi/auth.py +359 -0
- runapi/cli.py +576 -0
- runapi/config.py +141 -0
- runapi/core.py +219 -0
- runapi/errors.py +338 -0
- runapi/middleware.py +383 -0
- runapi-0.1.0.dist-info/METADATA +797 -0
- runapi-0.1.0.dist-info/RECORD +12 -0
- runapi-0.1.0.dist-info/WHEEL +4 -0
- runapi-0.1.0.dist-info/entry_points.txt +2 -0
- runapi-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,797 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: runapi
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A Next.js-inspired file-based routing framework built on FastAPI
|
|
5
|
+
Project-URL: Homepage, https://github.com/Amanbig/runapi
|
|
6
|
+
Project-URL: Repository, https://github.com/Amanbig/runapi
|
|
7
|
+
Project-URL: Documentation, https://github.com/Amanbig/runapi#readme
|
|
8
|
+
Project-URL: Issues, https://github.com/Amanbig/runapi/issues
|
|
9
|
+
Project-URL: Changelog, https://github.com/Amanbig/runapi/releases
|
|
10
|
+
Author-email: Amanpreet Singh <amanpreetsinghjhiwant7@gmail.com>
|
|
11
|
+
License: MIT License
|
|
12
|
+
|
|
13
|
+
Copyright (c) 2024 Amanpreet Singh
|
|
14
|
+
|
|
15
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
16
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
17
|
+
in the Software without restriction, including without limitation the rights
|
|
18
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
19
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
20
|
+
furnished to do so, subject to the following conditions:
|
|
21
|
+
|
|
22
|
+
The above copyright notice and this permission notice shall be included in all
|
|
23
|
+
copies or substantial portions of the Software.
|
|
24
|
+
|
|
25
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
26
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
27
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
28
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
29
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
30
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
31
|
+
SOFTWARE.
|
|
32
|
+
License-File: LICENSE
|
|
33
|
+
Keywords: api,async,backend,fastapi,file-based-routing,framework,nextjs,web
|
|
34
|
+
Classifier: Development Status :: 3 - Alpha
|
|
35
|
+
Classifier: Environment :: Web Environment
|
|
36
|
+
Classifier: Framework :: FastAPI
|
|
37
|
+
Classifier: Intended Audience :: Developers
|
|
38
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
39
|
+
Classifier: Operating System :: OS Independent
|
|
40
|
+
Classifier: Programming Language :: Python :: 3
|
|
41
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
42
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
43
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
44
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
45
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
46
|
+
Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
|
|
47
|
+
Classifier: Topic :: Internet :: WWW/HTTP :: WSGI :: Application
|
|
48
|
+
Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
|
|
49
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
50
|
+
Classifier: Typing :: Typed
|
|
51
|
+
Requires-Python: >=3.8
|
|
52
|
+
Requires-Dist: aiofiles>=23.0.0
|
|
53
|
+
Requires-Dist: fastapi>=0.103.0
|
|
54
|
+
Requires-Dist: passlib[bcrypt]>=1.7.4
|
|
55
|
+
Requires-Dist: psutil>=5.9.0
|
|
56
|
+
Requires-Dist: python-jose[cryptography]>=3.3.0
|
|
57
|
+
Requires-Dist: python-multipart>=0.0.6
|
|
58
|
+
Requires-Dist: rich>=13.0.0
|
|
59
|
+
Requires-Dist: typer>=0.9.0
|
|
60
|
+
Requires-Dist: uvicorn>=0.23.0
|
|
61
|
+
Provides-Extra: dev
|
|
62
|
+
Requires-Dist: black>=23.0.0; extra == 'dev'
|
|
63
|
+
Requires-Dist: httpx>=0.24.0; extra == 'dev'
|
|
64
|
+
Requires-Dist: isort>=5.12.0; extra == 'dev'
|
|
65
|
+
Requires-Dist: mypy>=1.0.0; extra == 'dev'
|
|
66
|
+
Requires-Dist: pytest>=7.0.0; extra == 'dev'
|
|
67
|
+
Provides-Extra: test
|
|
68
|
+
Requires-Dist: httpx>=0.24.0; extra == 'test'
|
|
69
|
+
Requires-Dist: pytest-asyncio>=0.21.0; extra == 'test'
|
|
70
|
+
Requires-Dist: pytest-cov>=4.0.0; extra == 'test'
|
|
71
|
+
Requires-Dist: pytest>=7.0.0; extra == 'test'
|
|
72
|
+
Description-Content-Type: text/markdown
|
|
73
|
+
|
|
74
|
+
# Runapi π
|
|
75
|
+
|
|
76
|
+
[](https://badge.fury.io/py/runapi)
|
|
77
|
+
[](https://www.python.org/downloads/)
|
|
78
|
+
[](https://opensource.org/licenses/MIT)
|
|
79
|
+
|
|
80
|
+
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.
|
|
81
|
+
|
|
82
|
+
## Why Runapi?
|
|
83
|
+
|
|
84
|
+
- π **Developer Experience**: Just like Next.js for React, runapi makes backend development intuitive
|
|
85
|
+
- β‘ **Performance**: Built on FastAPI, one of the fastest Python frameworks
|
|
86
|
+
- π‘οΈ **Production Ready**: Security, middleware, and error handling built-in
|
|
87
|
+
- π― **Type Safe**: Full typing support with automatic validation
|
|
88
|
+
- π **Intuitive**: File-based routing means your folder structure IS your API
|
|
89
|
+
|
|
90
|
+
## Features
|
|
91
|
+
|
|
92
|
+
- π **File-based routing** - Create API routes by simply adding Python files
|
|
93
|
+
- β‘ **FastAPI integration** - Built on top of FastAPI for high performance
|
|
94
|
+
- π **Authentication system** - JWT-based auth with middleware support
|
|
95
|
+
- π‘οΈ **Middleware stack** - Built-in middleware for CORS, rate limiting, security headers
|
|
96
|
+
- βοΈ **Configuration management** - Environment-based configuration with `.env` support
|
|
97
|
+
- π¨ **Error handling** - Comprehensive error handling with custom exceptions
|
|
98
|
+
- π§ **CLI tools** - Command-line interface for project management
|
|
99
|
+
- π **Auto-documentation** - Automatic API documentation via FastAPI
|
|
100
|
+
- π― **Type hints** - Full typing support with Pydantic integration
|
|
101
|
+
|
|
102
|
+
## Installation
|
|
103
|
+
|
|
104
|
+
```bash
|
|
105
|
+
pip install runapi
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
## Requirements
|
|
109
|
+
|
|
110
|
+
- Python 3.8+
|
|
111
|
+
- FastAPI
|
|
112
|
+
- Uvicorn (for development server)
|
|
113
|
+
|
|
114
|
+
## Table of Contents
|
|
115
|
+
|
|
116
|
+
- [Quick Start](#quick-start)
|
|
117
|
+
- [Configuration](#configuration)
|
|
118
|
+
- [Authentication](#authentication)
|
|
119
|
+
- [Middleware](#middleware)
|
|
120
|
+
- [Error Handling](#error-handling)
|
|
121
|
+
- [CLI Commands](#cli-commands)
|
|
122
|
+
- [Advanced Usage](#advanced-usage)
|
|
123
|
+
- [Testing](#testing)
|
|
124
|
+
- [Deployment](#production-deployment)
|
|
125
|
+
- [API Reference](#api-reference)
|
|
126
|
+
- [Examples](#examples)
|
|
127
|
+
- [Contributing](#contributing)
|
|
128
|
+
|
|
129
|
+
## Quick Start
|
|
130
|
+
|
|
131
|
+
### 1. Create a new project
|
|
132
|
+
|
|
133
|
+
```bash
|
|
134
|
+
runapi init my-api
|
|
135
|
+
cd my-api
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
### 2. Project Structure
|
|
139
|
+
|
|
140
|
+
```
|
|
141
|
+
my-api/
|
|
142
|
+
βββ routes/ # API routes (file-based routing)
|
|
143
|
+
β βββ index.py # GET /
|
|
144
|
+
β βββ api/
|
|
145
|
+
β βββ users.py # GET, POST /api/users
|
|
146
|
+
β βββ users/
|
|
147
|
+
β βββ [id].py # GET, PUT, DELETE /api/users/{id}
|
|
148
|
+
βββ static/ # Static files
|
|
149
|
+
βββ uploads/ # File uploads directory
|
|
150
|
+
βββ main.py # Application entry point
|
|
151
|
+
βββ .env # Configuration file
|
|
152
|
+
βββ README.md
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
### 3. Create routes
|
|
156
|
+
|
|
157
|
+
Routes are created by adding Python files in the `routes/` directory:
|
|
158
|
+
|
|
159
|
+
**routes/index.py** (GET /)
|
|
160
|
+
```python
|
|
161
|
+
from runapi import JSONResponse
|
|
162
|
+
|
|
163
|
+
async def get():
|
|
164
|
+
return JSONResponse({"message": "Hello runapi!"})
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
**routes/api/users.py** (GET,POST /api/users)
|
|
168
|
+
```python
|
|
169
|
+
from runapi import JSONResponse, Request
|
|
170
|
+
|
|
171
|
+
async def get():
|
|
172
|
+
return JSONResponse({"users": []})
|
|
173
|
+
|
|
174
|
+
async def post(request: Request):
|
|
175
|
+
body = await request.json()
|
|
176
|
+
return JSONResponse({"created": body})
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
**routes/api/users/[id].py** (GET,PUT,DELETE /api/users/{id})
|
|
180
|
+
```python
|
|
181
|
+
from runapi import JSONResponse, Request
|
|
182
|
+
|
|
183
|
+
async def get(request: Request):
|
|
184
|
+
user_id = request.path_params["id"]
|
|
185
|
+
return JSONResponse({"user_id": user_id})
|
|
186
|
+
|
|
187
|
+
async def put(request: Request):
|
|
188
|
+
user_id = request.path_params["id"]
|
|
189
|
+
body = await request.json()
|
|
190
|
+
return JSONResponse({"user_id": user_id, "updated": body})
|
|
191
|
+
|
|
192
|
+
async def delete(request: Request):
|
|
193
|
+
user_id = request.path_params["id"]
|
|
194
|
+
return JSONResponse({"user_id": user_id, "deleted": True})
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
### 4. Run development server
|
|
198
|
+
|
|
199
|
+
```bash
|
|
200
|
+
runapi dev
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
Visit `http://localhost:8000` to see your API!
|
|
204
|
+
|
|
205
|
+
## API Documentation
|
|
206
|
+
|
|
207
|
+
Once your server is running, you can access:
|
|
208
|
+
|
|
209
|
+
- **Interactive API Documentation**: `http://localhost:8000/docs` (Swagger UI)
|
|
210
|
+
- **Alternative Documentation**: `http://localhost:8000/redoc` (ReDoc)
|
|
211
|
+
- **OpenAPI JSON Schema**: `http://localhost:8000/openapi.json`
|
|
212
|
+
|
|
213
|
+
## Configuration
|
|
214
|
+
|
|
215
|
+
runapi uses environment variables for configuration. Create a `.env` file:
|
|
216
|
+
|
|
217
|
+
```env
|
|
218
|
+
# Server Settings
|
|
219
|
+
DEBUG=true
|
|
220
|
+
HOST=127.0.0.1
|
|
221
|
+
PORT=8000
|
|
222
|
+
|
|
223
|
+
# Security
|
|
224
|
+
SECRET_KEY=your-secret-key-here
|
|
225
|
+
|
|
226
|
+
# CORS
|
|
227
|
+
CORS_ORIGINS=http://localhost:3000,http://localhost:8080
|
|
228
|
+
CORS_CREDENTIALS=true
|
|
229
|
+
|
|
230
|
+
# Rate Limiting
|
|
231
|
+
RATE_LIMIT_ENABLED=true
|
|
232
|
+
RATE_LIMIT_CALLS=100
|
|
233
|
+
RATE_LIMIT_PERIOD=60
|
|
234
|
+
|
|
235
|
+
# Database (example)
|
|
236
|
+
DATABASE_URL=sqlite:///./app.db
|
|
237
|
+
|
|
238
|
+
# Logging
|
|
239
|
+
LOG_LEVEL=INFO
|
|
240
|
+
|
|
241
|
+
# Static Files
|
|
242
|
+
STATIC_FILES_ENABLED=true
|
|
243
|
+
STATIC_FILES_PATH=static
|
|
244
|
+
STATIC_FILES_URL=/static
|
|
245
|
+
|
|
246
|
+
# JWT Settings
|
|
247
|
+
JWT_ALGORITHM=HS256
|
|
248
|
+
JWT_EXPIRY=3600
|
|
249
|
+
JWT_REFRESH_EXPIRY=86400
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
### Configuration Reference
|
|
253
|
+
|
|
254
|
+
| Variable | Type | Default | Description |
|
|
255
|
+
|----------|------|---------|-------------|
|
|
256
|
+
| `DEBUG` | boolean | `true` | Enable debug mode |
|
|
257
|
+
| `HOST` | string | `127.0.0.1` | Server host |
|
|
258
|
+
| `PORT` | integer | `8000` | Server port |
|
|
259
|
+
| `SECRET_KEY` | string | `dev-secret-key...` | Secret key for JWT |
|
|
260
|
+
| `CORS_ORIGINS` | string | `*` | Comma-separated allowed origins |
|
|
261
|
+
| `CORS_CREDENTIALS` | boolean | `true` | Allow credentials in CORS |
|
|
262
|
+
| `RATE_LIMIT_ENABLED` | boolean | `false` | Enable rate limiting |
|
|
263
|
+
| `RATE_LIMIT_CALLS` | integer | `100` | Requests per period |
|
|
264
|
+
| `RATE_LIMIT_PERIOD` | integer | `60` | Rate limit period in seconds |
|
|
265
|
+
| `LOG_LEVEL` | string | `INFO` | Logging level |
|
|
266
|
+
| `DATABASE_URL` | string | `None` | Database connection URL |
|
|
267
|
+
|
|
268
|
+
## Authentication
|
|
269
|
+
|
|
270
|
+
runapi includes built-in JWT authentication:
|
|
271
|
+
|
|
272
|
+
### Enable Authentication Middleware
|
|
273
|
+
|
|
274
|
+
**main.py**
|
|
275
|
+
```python
|
|
276
|
+
from runapi import create_runapi_app
|
|
277
|
+
|
|
278
|
+
app = create_runapi_app()
|
|
279
|
+
|
|
280
|
+
# Protect specific routes
|
|
281
|
+
app.add_auth_middleware(
|
|
282
|
+
protected_paths=["/api/protected"],
|
|
283
|
+
excluded_paths=["/api/auth/login", "/docs"]
|
|
284
|
+
)
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
### Create Login Route
|
|
288
|
+
|
|
289
|
+
**routes/api/auth/login.py**
|
|
290
|
+
```python
|
|
291
|
+
from runapi import JSONResponse, Request, create_token_response, verify_password
|
|
292
|
+
|
|
293
|
+
async def post(request: Request):
|
|
294
|
+
body = await request.json()
|
|
295
|
+
username = body.get("username")
|
|
296
|
+
password = body.get("password")
|
|
297
|
+
|
|
298
|
+
# Verify credentials (implement your logic)
|
|
299
|
+
if verify_credentials(username, password):
|
|
300
|
+
user_data = {"sub": "user_id", "username": username}
|
|
301
|
+
tokens = create_token_response(user_data)
|
|
302
|
+
return JSONResponse(tokens.dict())
|
|
303
|
+
|
|
304
|
+
return JSONResponse({"error": "Invalid credentials"}, status_code=401)
|
|
305
|
+
```
|
|
306
|
+
|
|
307
|
+
### Protected Routes
|
|
308
|
+
|
|
309
|
+
**routes/api/protected.py**
|
|
310
|
+
```python
|
|
311
|
+
from runapi import JSONResponse, get_current_user, Depends
|
|
312
|
+
|
|
313
|
+
async def get(current_user: dict = Depends(get_current_user())):
|
|
314
|
+
return JSONResponse({
|
|
315
|
+
"message": "This is protected!",
|
|
316
|
+
"user": current_user
|
|
317
|
+
})
|
|
318
|
+
```
|
|
319
|
+
|
|
320
|
+
## Middleware
|
|
321
|
+
|
|
322
|
+
runapi includes several built-in middleware:
|
|
323
|
+
|
|
324
|
+
```python
|
|
325
|
+
from runapi import create_runapi_app
|
|
326
|
+
|
|
327
|
+
app = create_runapi_app()
|
|
328
|
+
|
|
329
|
+
# Built-in middleware (automatically configured via .env)
|
|
330
|
+
# - CORS
|
|
331
|
+
# - Rate limiting
|
|
332
|
+
# - Security headers
|
|
333
|
+
# - Request logging
|
|
334
|
+
# - Compression
|
|
335
|
+
|
|
336
|
+
# Add custom middleware
|
|
337
|
+
from runapi import RunApiMiddleware
|
|
338
|
+
|
|
339
|
+
class CustomMiddleware(RunApiMiddleware):
|
|
340
|
+
async def dispatch(self, request, call_next):
|
|
341
|
+
# Pre-processing
|
|
342
|
+
response = await call_next(request)
|
|
343
|
+
# Post-processing
|
|
344
|
+
return response
|
|
345
|
+
|
|
346
|
+
app.add_middleware(CustomMiddleware)
|
|
347
|
+
```
|
|
348
|
+
|
|
349
|
+
## Error Handling
|
|
350
|
+
|
|
351
|
+
runapi provides comprehensive error handling:
|
|
352
|
+
|
|
353
|
+
```python
|
|
354
|
+
from runapi import ValidationError, NotFoundError, raise_not_found
|
|
355
|
+
|
|
356
|
+
async def get_user(user_id: str):
|
|
357
|
+
if not user_id:
|
|
358
|
+
raise ValidationError("User ID is required")
|
|
359
|
+
|
|
360
|
+
user = find_user(user_id)
|
|
361
|
+
if not user:
|
|
362
|
+
raise_not_found("User not found")
|
|
363
|
+
|
|
364
|
+
return user
|
|
365
|
+
```
|
|
366
|
+
|
|
367
|
+
## CLI Commands
|
|
368
|
+
|
|
369
|
+
runapi includes a powerful CLI for development:
|
|
370
|
+
|
|
371
|
+
```bash
|
|
372
|
+
# Create new project
|
|
373
|
+
runapi init my-project
|
|
374
|
+
|
|
375
|
+
# Run development server
|
|
376
|
+
runapi dev
|
|
377
|
+
|
|
378
|
+
# Generate boilerplate code
|
|
379
|
+
runapi generate route users
|
|
380
|
+
runapi generate middleware auth
|
|
381
|
+
runapi generate main
|
|
382
|
+
|
|
383
|
+
# List all routes
|
|
384
|
+
runapi routes
|
|
385
|
+
|
|
386
|
+
# Show project info
|
|
387
|
+
runapi info
|
|
388
|
+
```
|
|
389
|
+
|
|
390
|
+
## Advanced Usage
|
|
391
|
+
|
|
392
|
+
### Custom Application Setup
|
|
393
|
+
|
|
394
|
+
**main.py**
|
|
395
|
+
```python
|
|
396
|
+
from runapi import create_runapi_app, get_config
|
|
397
|
+
|
|
398
|
+
# Load custom configuration
|
|
399
|
+
config = get_config()
|
|
400
|
+
|
|
401
|
+
# Create app with custom settings
|
|
402
|
+
app = create_runapi_app(
|
|
403
|
+
title="My API",
|
|
404
|
+
description="Built with runapi",
|
|
405
|
+
version="1.0.0"
|
|
406
|
+
)
|
|
407
|
+
|
|
408
|
+
# Add custom middleware
|
|
409
|
+
app.add_auth_middleware()
|
|
410
|
+
|
|
411
|
+
# Add custom startup/shutdown events
|
|
412
|
+
@app.get_app().on_event("startup")
|
|
413
|
+
async def startup():
|
|
414
|
+
print("Starting up!")
|
|
415
|
+
|
|
416
|
+
# Get underlying FastAPI app
|
|
417
|
+
fastapi_app = app.get_app()
|
|
418
|
+
```
|
|
419
|
+
|
|
420
|
+
### Database Integration
|
|
421
|
+
|
|
422
|
+
```python
|
|
423
|
+
# Using SQLAlchemy (example)
|
|
424
|
+
from sqlalchemy import create_engine
|
|
425
|
+
from runapi import get_config
|
|
426
|
+
|
|
427
|
+
config = get_config()
|
|
428
|
+
engine = create_engine(config.database_url)
|
|
429
|
+
|
|
430
|
+
# Use in routes
|
|
431
|
+
async def get_users():
|
|
432
|
+
# Your database logic here
|
|
433
|
+
pass
|
|
434
|
+
```
|
|
435
|
+
|
|
436
|
+
### Background Tasks
|
|
437
|
+
|
|
438
|
+
```python
|
|
439
|
+
from fastapi import BackgroundTasks
|
|
440
|
+
from runapi import JSONResponse
|
|
441
|
+
|
|
442
|
+
async def send_email(email: str):
|
|
443
|
+
# Send email logic
|
|
444
|
+
pass
|
|
445
|
+
|
|
446
|
+
async def post(request: Request, background_tasks: BackgroundTasks):
|
|
447
|
+
body = await request.json()
|
|
448
|
+
background_tasks.add_task(send_email, body["email"])
|
|
449
|
+
return JSONResponse({"message": "Email queued"})
|
|
450
|
+
```
|
|
451
|
+
|
|
452
|
+
## Dynamic Routes
|
|
453
|
+
|
|
454
|
+
runapi supports dynamic route parameters:
|
|
455
|
+
|
|
456
|
+
- `routes/users/[id].py` β `/users/{id}`
|
|
457
|
+
- `routes/posts/[slug].py` β `/posts/{slug}`
|
|
458
|
+
- `routes/api/[...path].py` β `/api/{path:path}` (catch-all)
|
|
459
|
+
|
|
460
|
+
## File Uploads
|
|
461
|
+
|
|
462
|
+
```python
|
|
463
|
+
from fastapi import UploadFile, File
|
|
464
|
+
from runapi import JSONResponse
|
|
465
|
+
|
|
466
|
+
async def post(file: UploadFile = File(...)):
|
|
467
|
+
contents = await file.read()
|
|
468
|
+
# Process file
|
|
469
|
+
return JSONResponse({"filename": file.filename})
|
|
470
|
+
```
|
|
471
|
+
|
|
472
|
+
## Testing
|
|
473
|
+
|
|
474
|
+
```python
|
|
475
|
+
from fastapi.testclient import TestClient
|
|
476
|
+
from main import app
|
|
477
|
+
|
|
478
|
+
client = TestClient(app.get_app())
|
|
479
|
+
|
|
480
|
+
def test_read_main():
|
|
481
|
+
response = client.get("/")
|
|
482
|
+
assert response.status_code == 200
|
|
483
|
+
assert response.json()["message"] == "Hello runapi!"
|
|
484
|
+
```
|
|
485
|
+
|
|
486
|
+
## Production Deployment
|
|
487
|
+
|
|
488
|
+
### Using Docker
|
|
489
|
+
|
|
490
|
+
**Dockerfile**
|
|
491
|
+
```dockerfile
|
|
492
|
+
FROM python:3.9-slim
|
|
493
|
+
|
|
494
|
+
WORKDIR /app
|
|
495
|
+
COPY requirements.txt .
|
|
496
|
+
RUN pip install -r requirements.txt
|
|
497
|
+
|
|
498
|
+
COPY . .
|
|
499
|
+
EXPOSE 8000
|
|
500
|
+
|
|
501
|
+
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
|
|
502
|
+
```
|
|
503
|
+
|
|
504
|
+
### Using Gunicorn
|
|
505
|
+
|
|
506
|
+
```bash
|
|
507
|
+
pip install gunicorn
|
|
508
|
+
gunicorn main:app -w 4 -k uvicorn.workers.UvicornWorker
|
|
509
|
+
```
|
|
510
|
+
|
|
511
|
+
## WebSockets
|
|
512
|
+
|
|
513
|
+
runapi supports WebSocket connections through FastAPI:
|
|
514
|
+
|
|
515
|
+
```python
|
|
516
|
+
# routes/ws/chat.py
|
|
517
|
+
from fastapi import WebSocket
|
|
518
|
+
from runapi import get_app
|
|
519
|
+
|
|
520
|
+
app = get_app()
|
|
521
|
+
|
|
522
|
+
@app.websocket("/ws/chat")
|
|
523
|
+
async def websocket_endpoint(websocket: WebSocket):
|
|
524
|
+
await websocket.accept()
|
|
525
|
+
while True:
|
|
526
|
+
data = await websocket.receive_text()
|
|
527
|
+
await websocket.send_text(f"Message: {data}")
|
|
528
|
+
```
|
|
529
|
+
|
|
530
|
+
## API Reference
|
|
531
|
+
|
|
532
|
+
### Core Functions
|
|
533
|
+
|
|
534
|
+
#### `create_runapi_app(**kwargs)`
|
|
535
|
+
Creates a runapi application instance.
|
|
536
|
+
|
|
537
|
+
**Parameters:**
|
|
538
|
+
- `title` (str): API title
|
|
539
|
+
- `description` (str): API description
|
|
540
|
+
- `version` (str): API version
|
|
541
|
+
- `config` (runapiConfig): Custom configuration
|
|
542
|
+
|
|
543
|
+
**Returns:** runapiApp instance
|
|
544
|
+
|
|
545
|
+
#### `get_config()`
|
|
546
|
+
Returns the global configuration instance.
|
|
547
|
+
|
|
548
|
+
#### `load_config(env_file: str = None)`
|
|
549
|
+
Loads configuration from environment file.
|
|
550
|
+
|
|
551
|
+
### Authentication Functions
|
|
552
|
+
|
|
553
|
+
#### `create_access_token(data: dict, expires_delta: timedelta = None)`
|
|
554
|
+
Creates a JWT access token.
|
|
555
|
+
|
|
556
|
+
#### `verify_token(token: str)`
|
|
557
|
+
Verifies and decodes a JWT token.
|
|
558
|
+
|
|
559
|
+
#### `hash_password(password: str)`
|
|
560
|
+
Hashes a password using bcrypt.
|
|
561
|
+
|
|
562
|
+
#### `verify_password(plain_password: str, hashed_password: str)`
|
|
563
|
+
Verifies a password against its hash.
|
|
564
|
+
|
|
565
|
+
### Error Functions
|
|
566
|
+
|
|
567
|
+
#### `raise_validation_error(message: str, details: dict = None)`
|
|
568
|
+
Raises a validation error (400).
|
|
569
|
+
|
|
570
|
+
#### `raise_not_found(message: str = "Resource not found")`
|
|
571
|
+
Raises a not found error (404).
|
|
572
|
+
|
|
573
|
+
#### `raise_auth_error(message: str = "Authentication required")`
|
|
574
|
+
Raises an authentication error (401).
|
|
575
|
+
|
|
576
|
+
## Route Conventions
|
|
577
|
+
|
|
578
|
+
### File Naming
|
|
579
|
+
|
|
580
|
+
- `index.py` β Root path `/`
|
|
581
|
+
- `users.py` β `/users`
|
|
582
|
+
- `[id].py` β `/{id}` (dynamic parameter)
|
|
583
|
+
- `[...slug].py` β `/{slug:path}` (catch-all)
|
|
584
|
+
|
|
585
|
+
### HTTP Methods
|
|
586
|
+
|
|
587
|
+
Export async functions named after HTTP methods:
|
|
588
|
+
|
|
589
|
+
```python
|
|
590
|
+
async def get(): # GET request
|
|
591
|
+
async def post(): # POST request
|
|
592
|
+
async def put(): # PUT request
|
|
593
|
+
async def delete(): # DELETE request
|
|
594
|
+
async def patch(): # PATCH request
|
|
595
|
+
```
|
|
596
|
+
|
|
597
|
+
### Request Handling
|
|
598
|
+
|
|
599
|
+
```python
|
|
600
|
+
from runapi import Request, JSONResponse
|
|
601
|
+
|
|
602
|
+
async def post(request: Request):
|
|
603
|
+
# Get JSON body
|
|
604
|
+
body = await request.json()
|
|
605
|
+
|
|
606
|
+
# Get path parameters
|
|
607
|
+
user_id = request.path_params.get("id")
|
|
608
|
+
|
|
609
|
+
# Get query parameters
|
|
610
|
+
limit = request.query_params.get("limit", 10)
|
|
611
|
+
|
|
612
|
+
# Get headers
|
|
613
|
+
auth_header = request.headers.get("authorization")
|
|
614
|
+
|
|
615
|
+
return JSONResponse({"status": "success"})
|
|
616
|
+
```
|
|
617
|
+
|
|
618
|
+
## Troubleshooting
|
|
619
|
+
|
|
620
|
+
### Common Issues
|
|
621
|
+
|
|
622
|
+
**Import Error: No module named 'runapi'**
|
|
623
|
+
```bash
|
|
624
|
+
pip install runapi
|
|
625
|
+
```
|
|
626
|
+
|
|
627
|
+
**Routes not loading**
|
|
628
|
+
- Ensure `routes/` directory exists in your project root
|
|
629
|
+
- Check that route files have proper async function exports
|
|
630
|
+
- Verify file naming conventions
|
|
631
|
+
|
|
632
|
+
**Authentication not working**
|
|
633
|
+
- Set a proper `SECRET_KEY` in production
|
|
634
|
+
- Check that protected paths are correctly configured
|
|
635
|
+
- Verify JWT token format and expiration
|
|
636
|
+
|
|
637
|
+
**CORS Issues**
|
|
638
|
+
- Configure `CORS_ORIGINS` in your `.env` file
|
|
639
|
+
- Set `CORS_CREDENTIALS=true` if needed
|
|
640
|
+
- Check that your frontend origin is included
|
|
641
|
+
|
|
642
|
+
### Debug Mode
|
|
643
|
+
|
|
644
|
+
Enable debug mode for detailed error messages:
|
|
645
|
+
|
|
646
|
+
```env
|
|
647
|
+
DEBUG=true
|
|
648
|
+
LOG_LEVEL=DEBUG
|
|
649
|
+
```
|
|
650
|
+
|
|
651
|
+
## Performance Tips
|
|
652
|
+
|
|
653
|
+
1. **Use async/await**: All route functions should be async
|
|
654
|
+
2. **Enable compression**: Built-in gzip compression for responses
|
|
655
|
+
3. **Configure rate limiting**: Protect against abuse
|
|
656
|
+
4. **Use proper HTTP status codes**: For better client handling
|
|
657
|
+
5. **Implement caching**: For frequently accessed data
|
|
658
|
+
|
|
659
|
+
## Security Best Practices
|
|
660
|
+
|
|
661
|
+
1. **Change default secret key** in production
|
|
662
|
+
2. **Use HTTPS** in production
|
|
663
|
+
3. **Configure CORS** properly
|
|
664
|
+
4. **Implement rate limiting**
|
|
665
|
+
5. **Validate all inputs**
|
|
666
|
+
6. **Use environment variables** for sensitive data
|
|
667
|
+
|
|
668
|
+
## Examples
|
|
669
|
+
|
|
670
|
+
Check out the `/example` directory for a complete example application demonstrating:
|
|
671
|
+
|
|
672
|
+
- File-based routing
|
|
673
|
+
- Authentication with JWT
|
|
674
|
+
- Protected routes
|
|
675
|
+
- Error handling
|
|
676
|
+
- Middleware usage
|
|
677
|
+
- Configuration management
|
|
678
|
+
|
|
679
|
+
Run the example:
|
|
680
|
+
|
|
681
|
+
```bash
|
|
682
|
+
cd example
|
|
683
|
+
runapi dev
|
|
684
|
+
```
|
|
685
|
+
|
|
686
|
+
## Roadmap
|
|
687
|
+
|
|
688
|
+
- [ ] Database integration helpers (SQLAlchemy, MongoDB)
|
|
689
|
+
- [ ] Built-in caching mechanisms (Redis, in-memory)
|
|
690
|
+
- [ ] WebSocket routing support
|
|
691
|
+
- [ ] Background task queue integration
|
|
692
|
+
- [ ] Plugin system
|
|
693
|
+
- [ ] More authentication providers (OAuth, LDAP)
|
|
694
|
+
- [ ] Performance monitoring and metrics
|
|
695
|
+
- [ ] GraphQL support
|
|
696
|
+
|
|
697
|
+
## Contributing
|
|
698
|
+
|
|
699
|
+
We welcome contributions! Here's how to get started:
|
|
700
|
+
|
|
701
|
+
### Development Setup
|
|
702
|
+
|
|
703
|
+
1. Clone the repository:
|
|
704
|
+
```bash
|
|
705
|
+
git clone https://github.com/Amanbig/runapi.git
|
|
706
|
+
cd runapi
|
|
707
|
+
```
|
|
708
|
+
|
|
709
|
+
2. Create a virtual environment:
|
|
710
|
+
```bash
|
|
711
|
+
python -m venv venv
|
|
712
|
+
source venv/bin/activate # On Windows: venv\Scripts\activate
|
|
713
|
+
```
|
|
714
|
+
|
|
715
|
+
3. Install development dependencies:
|
|
716
|
+
```bash
|
|
717
|
+
pip install -e .
|
|
718
|
+
pip install pytest httpx
|
|
719
|
+
```
|
|
720
|
+
|
|
721
|
+
4. Run tests:
|
|
722
|
+
```bash
|
|
723
|
+
python -m pytest tests/
|
|
724
|
+
```
|
|
725
|
+
|
|
726
|
+
### Guidelines
|
|
727
|
+
|
|
728
|
+
- Follow PEP 8 style guidelines
|
|
729
|
+
- Add tests for new features
|
|
730
|
+
- Update documentation
|
|
731
|
+
- Create detailed commit messages
|
|
732
|
+
- Open an issue before major changes
|
|
733
|
+
|
|
734
|
+
### Reporting Issues
|
|
735
|
+
|
|
736
|
+
Please include:
|
|
737
|
+
- Python version
|
|
738
|
+
- runapi version
|
|
739
|
+
- Minimal code example
|
|
740
|
+
- Full error traceback
|
|
741
|
+
- Expected vs actual behavior
|
|
742
|
+
|
|
743
|
+
## Changelog
|
|
744
|
+
|
|
745
|
+
### v0.1.0 (Latest)
|
|
746
|
+
- Initial release
|
|
747
|
+
- File-based routing system
|
|
748
|
+
- JWT authentication
|
|
749
|
+
- Middleware stack
|
|
750
|
+
- CLI tools
|
|
751
|
+
- Configuration management
|
|
752
|
+
- Error handling system
|
|
753
|
+
|
|
754
|
+
## License
|
|
755
|
+
|
|
756
|
+
This project is licensed under the MIT License - see the LICENSE file for details.
|
|
757
|
+
|
|
758
|
+
## Community
|
|
759
|
+
|
|
760
|
+
- π [Documentation](https://github.com/Amanbig/runapi)
|
|
761
|
+
- π [Issue Tracker](https://github.com/Amanbig/runapi/issues)
|
|
762
|
+
- π¬ [Discussions](https://github.com/Amanbig/runapi/discussions)
|
|
763
|
+
- π§ [Email](mailto:amanpreetsinghjhiwant7@gmail.com)
|
|
764
|
+
|
|
765
|
+
## Acknowledgments
|
|
766
|
+
|
|
767
|
+
- Built on top of [FastAPI](https://fastapi.tiangolo.com/) by SebastiΓ‘n Ramirez
|
|
768
|
+
- Inspired by [Next.js](https://nextjs.org/) file-based routing by Vercel
|
|
769
|
+
- Uses [Typer](https://typer.tiangolo.com/) for CLI by SebastiΓ‘n Ramirez
|
|
770
|
+
- Password hashing with [Passlib](https://passlib.readthedocs.io/)
|
|
771
|
+
- Testing with [pytest](https://pytest.org/) and [httpx](https://www.python-httpx.org/)
|
|
772
|
+
|
|
773
|
+
## Related Projects
|
|
774
|
+
|
|
775
|
+
- [FastAPI](https://fastapi.tiangolo.com/) - Modern, fast web framework for Python
|
|
776
|
+
- [Starlette](https://www.starlette.io/) - Lightweight ASGI framework
|
|
777
|
+
- [Pydantic](https://pydantic-docs.helpmanual.io/) - Data validation using Python type hints
|
|
778
|
+
- [Next.js](https://nextjs.org/) - React framework (inspiration)
|
|
779
|
+
|
|
780
|
+
## Support
|
|
781
|
+
|
|
782
|
+
If runapi has been helpful to your project:
|
|
783
|
+
|
|
784
|
+
- β Star the repo on GitHub
|
|
785
|
+
- π Report bugs and request features
|
|
786
|
+
- π Contribute to documentation
|
|
787
|
+
- π° [Sponsor the project](https://github.com/sponsors/Amanbig)
|
|
788
|
+
|
|
789
|
+
---
|
|
790
|
+
|
|
791
|
+
<div align="center">
|
|
792
|
+
|
|
793
|
+
**runapi** - Making Python backend development as intuitive as frontend development! π
|
|
794
|
+
|
|
795
|
+
[Get Started](https://github.com/Amanbig/runapi) | [Documentation](https://github.com/Amanbig/runapi) | [Examples](https://github.com/Amanbig/runapi/tree/main/example)
|
|
796
|
+
|
|
797
|
+
</div>
|