runapi 0.3.0__tar.gz → 0.3.5__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.
Files changed (60) hide show
  1. {runapi-0.3.0 → runapi-0.3.5}/PKG-INFO +16 -1
  2. runapi-0.3.5/examples/basic-crud/README.md +36 -0
  3. runapi-0.3.5/examples/postgres-todo/README.md +44 -0
  4. {runapi-0.3.0 → runapi-0.3.5}/pyproject.toml +18 -0
  5. {runapi-0.3.0 → runapi-0.3.5}/runapi/__init__.py +7 -1
  6. {runapi-0.3.0 → runapi-0.3.5}/runapi/_version.py +2 -2
  7. {runapi-0.3.0 → runapi-0.3.5}/runapi/cli/commands/db.py +38 -5
  8. {runapi-0.3.0 → runapi-0.3.5}/runapi/cli/commands/inspect.py +10 -1
  9. {runapi-0.3.0 → runapi-0.3.5}/runapi/cli/commands/project.py +53 -0
  10. runapi-0.3.5/runapi/cli/templates/db/alembic.ini.tmpl +5 -0
  11. runapi-0.3.5/runapi/cli/templates/db/db.py.tmpl +5 -0
  12. runapi-0.3.5/runapi/cli/templates/db/docker-compose.yml.tmpl +19 -0
  13. runapi-0.3.5/runapi/cli/templates/db/env.py.tmpl +61 -0
  14. runapi-0.3.5/runapi/cli/templates/db/main.py.tmpl +15 -0
  15. runapi-0.3.5/runapi/cli/templates/db/models_init.py.tmpl +3 -0
  16. runapi-0.3.5/runapi/cli/templates/db/models_item.py.tmpl +11 -0
  17. runapi-0.3.5/runapi/cli/templates/db/route_items.py.tmpl +25 -0
  18. runapi-0.3.5/runapi/cli/templates/db/script.py.mako.tmpl +24 -0
  19. {runapi-0.3.0 → runapi-0.3.5}/runapi/cli/templates/project/gitignore.tmpl +4 -0
  20. {runapi-0.3.0 → runapi-0.3.5}/runapi/config.py +26 -0
  21. {runapi-0.3.0 → runapi-0.3.5}/runapi/core.py +32 -3
  22. runapi-0.3.5/runapi/database.py +157 -0
  23. {runapi-0.3.0 → runapi-0.3.5}/runapi/routing.py +23 -0
  24. {runapi-0.3.0 → runapi-0.3.5}/runapi/schemas.py +1 -1
  25. {runapi-0.3.0 → runapi-0.3.5}/.gitignore +0 -0
  26. {runapi-0.3.0 → runapi-0.3.5}/LICENSE +0 -0
  27. {runapi-0.3.0 → runapi-0.3.5}/README.md +0 -0
  28. {runapi-0.3.0 → runapi-0.3.5}/examples/basic/README.md +0 -0
  29. {runapi-0.3.0 → runapi-0.3.5}/release-notes/README.md +0 -0
  30. {runapi-0.3.0 → runapi-0.3.5}/runapi/auth.py +0 -0
  31. {runapi-0.3.0 → runapi-0.3.5}/runapi/backends.py +0 -0
  32. {runapi-0.3.0 → runapi-0.3.5}/runapi/cli/__init__.py +0 -0
  33. {runapi-0.3.0 → runapi-0.3.5}/runapi/cli/_app.py +0 -0
  34. {runapi-0.3.0 → runapi-0.3.5}/runapi/cli/_templates.py +0 -0
  35. {runapi-0.3.0 → runapi-0.3.5}/runapi/cli/commands/__init__.py +0 -0
  36. {runapi-0.3.0 → runapi-0.3.5}/runapi/cli/commands/generate.py +0 -0
  37. {runapi-0.3.0 → runapi-0.3.5}/runapi/cli/commands/server.py +0 -0
  38. {runapi-0.3.0 → runapi-0.3.5}/runapi/cli/templates/generate/crud_index.py.tmpl +0 -0
  39. {runapi-0.3.0 → runapi-0.3.5}/runapi/cli/templates/generate/crud_item.py.tmpl +0 -0
  40. {runapi-0.3.0 → runapi-0.3.5}/runapi/cli/templates/generate/crud_service_footer.py.tmpl +0 -0
  41. {runapi-0.3.0 → runapi-0.3.5}/runapi/cli/templates/generate/main.py.tmpl +0 -0
  42. {runapi-0.3.0 → runapi-0.3.5}/runapi/cli/templates/generate/middleware.py.tmpl +0 -0
  43. {runapi-0.3.0 → runapi-0.3.5}/runapi/cli/templates/generate/repository.py.tmpl +0 -0
  44. {runapi-0.3.0 → runapi-0.3.5}/runapi/cli/templates/generate/route.py.tmpl +0 -0
  45. {runapi-0.3.0 → runapi-0.3.5}/runapi/cli/templates/generate/schema.py.tmpl +0 -0
  46. {runapi-0.3.0 → runapi-0.3.5}/runapi/cli/templates/generate/service.py.tmpl +0 -0
  47. {runapi-0.3.0 → runapi-0.3.5}/runapi/cli/templates/project/Dockerfile.tmpl +0 -0
  48. {runapi-0.3.0 → runapi-0.3.5}/runapi/cli/templates/project/README.md.tmpl +0 -0
  49. {runapi-0.3.0 → runapi-0.3.5}/runapi/cli/templates/project/dockerignore.tmpl +0 -0
  50. {runapi-0.3.0 → runapi-0.3.5}/runapi/cli/templates/project/env.tmpl +0 -0
  51. {runapi-0.3.0 → runapi-0.3.5}/runapi/cli/templates/project/main.py.tmpl +0 -0
  52. {runapi-0.3.0 → runapi-0.3.5}/runapi/cli/templates/project/route_hello.py.tmpl +0 -0
  53. {runapi-0.3.0 → runapi-0.3.5}/runapi/cli/templates/project/route_index.py.tmpl +0 -0
  54. {runapi-0.3.0 → runapi-0.3.5}/runapi/errors.py +0 -0
  55. {runapi-0.3.0 → runapi-0.3.5}/runapi/lifecycle.py +0 -0
  56. {runapi-0.3.0 → runapi-0.3.5}/runapi/logging.py +0 -0
  57. {runapi-0.3.0 → runapi-0.3.5}/runapi/middleware.py +0 -0
  58. {runapi-0.3.0 → runapi-0.3.5}/runapi/py.typed +0 -0
  59. {runapi-0.3.0 → runapi-0.3.5}/runapi/repository.py +0 -0
  60. {runapi-0.3.0 → runapi-0.3.5}/runapi/service.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: runapi
3
- Version: 0.3.0
3
+ Version: 0.3.5
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
@@ -73,15 +73,30 @@ Requires-Dist: mkdocs>=1.6; extra == 'docs'
73
73
  Provides-Extra: lint
74
74
  Requires-Dist: mypy>=1.0.0; extra == 'lint'
75
75
  Requires-Dist: ruff>=0.1.0; extra == 'lint'
76
+ Provides-Extra: mysql
77
+ Requires-Dist: aiomysql>=0.2; extra == 'mysql'
78
+ Requires-Dist: alembic>=1.13; extra == 'mysql'
79
+ Requires-Dist: sqlalchemy[asyncio]>=2.0; extra == 'mysql'
80
+ Provides-Extra: postgres
81
+ Requires-Dist: alembic>=1.13; extra == 'postgres'
82
+ Requires-Dist: asyncpg>=0.29; extra == 'postgres'
83
+ Requires-Dist: sqlalchemy[asyncio]>=2.0; extra == 'postgres'
76
84
  Provides-Extra: redis
77
85
  Requires-Dist: redis>=5.0; extra == 'redis'
86
+ Provides-Extra: sqlite
87
+ Requires-Dist: aiosqlite>=0.19; extra == 'sqlite'
88
+ Requires-Dist: alembic>=1.13; extra == 'sqlite'
89
+ Requires-Dist: sqlalchemy[asyncio]>=2.0; extra == 'sqlite'
78
90
  Provides-Extra: test
91
+ Requires-Dist: aiosqlite>=0.19; extra == 'test'
92
+ Requires-Dist: alembic>=1.13; extra == 'test'
79
93
  Requires-Dist: fakeredis>=2.20; extra == 'test'
80
94
  Requires-Dist: httpx>=0.24.0; extra == 'test'
81
95
  Requires-Dist: pytest-asyncio>=0.21.0; extra == 'test'
82
96
  Requires-Dist: pytest-cov>=4.0.0; extra == 'test'
83
97
  Requires-Dist: pytest>=7.0.0; extra == 'test'
84
98
  Requires-Dist: redis>=5.0; extra == 'test'
99
+ Requires-Dist: sqlalchemy[asyncio]>=2.0; extra == 'test'
85
100
  Description-Content-Type: text/markdown
86
101
 
87
102
  # Runapi 🚀
@@ -0,0 +1,36 @@
1
+ # CRUD example: a todo API
2
+
3
+ A small REST API showing file-based routing, validation, a service layer and a repository.
4
+
5
+ ```bash
6
+ pip install runapi
7
+ cp .env.example .env # then set SECRET_KEY
8
+ runapi dev
9
+ ```
10
+
11
+ | Request | File |
12
+ |---------|------|
13
+ | `GET /todos`, `POST /todos` | `routes/todos/index.py` |
14
+ | `GET /todos/{id}`, `PUT /todos/{id}`, `DELETE /todos/{id}` | `routes/todos/[id].py` |
15
+
16
+ ```bash
17
+ curl -X POST localhost:8000/todos -H 'content-type: application/json' -d '{"title": "write docs"}'
18
+ curl localhost:8000/todos
19
+ curl -X PUT localhost:8000/todos/1 -H 'content-type: application/json' -d '{"done": true}'
20
+ curl 'localhost:8000/todos?done=true'
21
+ curl -X DELETE localhost:8000/todos/1
22
+ ```
23
+
24
+ Interactive docs: http://localhost:8000/docs
25
+
26
+ ## How it fits together
27
+
28
+ ```
29
+ route (HTTP) -> service (rules) -> repository (storage)
30
+ ```
31
+
32
+ Data is stored in memory and resets on restart. To keep data, replace
33
+ `InMemoryRepository` with a database repository: see the
34
+ [database docs](https://github.com/Amanbig/runapi/blob/main/docs/database.md).
35
+
36
+ Want the same thing generated for your own resource? Run `runapi generate crud <name>`.
@@ -0,0 +1,44 @@
1
+ # PostgreSQL example: todo API with SQLAlchemy and Alembic
2
+
3
+ An async CRUD API backed by PostgreSQL, with schema migrations. The same code runs on SQLite:
4
+ only `DATABASE_URL` changes.
5
+
6
+ ```bash
7
+ pip install -r requirements.txt # runapi[postgres]
8
+ cp .env.example .env # set SECRET_KEY
9
+ docker compose up -d db # PostgreSQL 16 on localhost:5432
10
+ runapi db upgrade # apply migrations/ (creates the todos table)
11
+ runapi dev
12
+ ```
13
+
14
+ No Docker? Use SQLite instead: `pip install "runapi[sqlite]"` and set
15
+ `DATABASE_URL=sqlite+aiosqlite:///./app.db` in `.env`.
16
+
17
+ ```bash
18
+ curl -X POST localhost:8000/todos -H 'content-type: application/json' -d '{"title": "ship it"}'
19
+ curl localhost:8000/todos
20
+ curl -X PUT localhost:8000/todos/1 -H 'content-type: application/json' -d '{"done": true}'
21
+ curl localhost:8000/ready # {"status":"ready","checks":{"database":true}}
22
+ ```
23
+
24
+ ## How it fits together
25
+
26
+ | File | Role |
27
+ |------|------|
28
+ | `db.py` | `database = Database()` reads `DATABASE_URL` |
29
+ | `main.py` | `runapi_app.use_database(database)`: connect on startup, dispose on shutdown, adds a `/ready` check |
30
+ | `models/todo.py` | SQLAlchemy model on `runapi.Base` |
31
+ | `routes/todos/*.py` | handlers get a session with `Depends(database.get_session)`; it commits when the request finishes and rolls back on errors |
32
+ | `migrations/` | Alembic (async). `env.py` reads `DATABASE_URL` and `Base.metadata` |
33
+
34
+ ## Changing the model
35
+
36
+ ```bash
37
+ # edit models/todo.py, then:
38
+ runapi db migrate -m "add due date" # autogenerate a migration, review it!
39
+ runapi db upgrade
40
+ runapi db downgrade # undo one step
41
+ ```
42
+
43
+ Autogenerated migrations should always be reviewed. Generate them against the database you deploy
44
+ to (PostgreSQL), since SQLite renders some defaults differently.
@@ -67,6 +67,21 @@ db = [
67
67
  "alembic>=1.13",
68
68
  "aiosqlite>=0.19",
69
69
  ]
70
+ sqlite = [
71
+ "sqlalchemy[asyncio]>=2.0",
72
+ "alembic>=1.13",
73
+ "aiosqlite>=0.19",
74
+ ]
75
+ postgres = [
76
+ "sqlalchemy[asyncio]>=2.0",
77
+ "alembic>=1.13",
78
+ "asyncpg>=0.29",
79
+ ]
80
+ mysql = [
81
+ "sqlalchemy[asyncio]>=2.0",
82
+ "alembic>=1.13",
83
+ "aiomysql>=0.2",
84
+ ]
70
85
  dev = [
71
86
  "pytest>=7.0.0",
72
87
  "httpx>=0.24.0",
@@ -80,6 +95,9 @@ test = [
80
95
  "pytest-cov>=4.0.0",
81
96
  "redis>=5.0",
82
97
  "fakeredis>=2.20",
98
+ "sqlalchemy[asyncio]>=2.0",
99
+ "alembic>=1.13",
100
+ "aiosqlite>=0.19",
83
101
  ]
84
102
  docs = [
85
103
  "mkdocs>=1.6",
@@ -50,6 +50,9 @@ from .backends import (
50
50
  from .config import RunApiConfig, get_config, load_config
51
51
  from .core import RunApiApp, create_app, create_runapi_app
52
52
 
53
+ # Conditional SQLAlchemy import
54
+ from .database import DATABASE_AVAILABLE, Base, Database, check_driver
55
+
53
56
  # Error handling
54
57
  from .errors import (
55
58
  AuthenticationError,
@@ -132,7 +135,6 @@ from .schemas import (
132
135
  ErrorResponse as SchemaErrorResponse,
133
136
  )
134
137
 
135
- # Conditional SQLAlchemy import
136
138
  if SQLALCHEMY_AVAILABLE:
137
139
  from .repository import SQLAlchemyRepository
138
140
  else:
@@ -257,6 +259,10 @@ __all__ = [
257
259
  "InMemoryRepository",
258
260
  "TypedInMemoryRepository",
259
261
  "SQLAlchemyRepository",
262
+ "Database",
263
+ "Base",
264
+ "check_driver",
265
+ "DATABASE_AVAILABLE",
260
266
  "RepositoryFactory",
261
267
  "create_repository",
262
268
  "SQLALCHEMY_AVAILABLE",
@@ -18,7 +18,7 @@ version_tuple: tuple[int | str, ...]
18
18
  commit_id: str | None
19
19
  __commit_id__: str | None
20
20
 
21
- __version__ = version = '0.3.0'
22
- __version_tuple__ = version_tuple = (0, 3, 0)
21
+ __version__ = version = '0.3.5'
22
+ __version_tuple__ = version_tuple = (0, 3, 5)
23
23
 
24
24
  __commit_id__ = commit_id = None
@@ -7,6 +7,7 @@ from pathlib import Path
7
7
  import typer
8
8
 
9
9
  from .._app import app, console
10
+ from .._templates import render
10
11
 
11
12
 
12
13
  @app.command()
@@ -30,7 +31,9 @@ def build(
30
31
  console.print(f"✅ [green]Built {tag}[/green] (run: docker run -p 8000:8000 {tag})")
31
32
 
32
33
 
33
- db_app = typer.Typer(help="Database migrations (Alembic). Install with: pip install runapi\\[db]")
34
+ db_app = typer.Typer(
35
+ help="Database migrations (Alembic). Install with: pip install runapi\\[sqlite] or runapi\\[postgres]"
36
+ )
34
37
  app.add_typer(db_app, name="db")
35
38
 
36
39
 
@@ -38,17 +41,47 @@ def _alembic(*args: str):
38
41
  try:
39
42
  import alembic # noqa: F401
40
43
  except ImportError:
41
- console.print("[red]❌ Alembic is not installed. Run: pip install runapi\\[db]")
44
+ console.print(
45
+ "[red]❌ Alembic is not installed. Run: pip install runapi\\[sqlite] (or runapi\\[postgres])"
46
+ )
42
47
  raise typer.Exit(code=1) from None
43
48
  result = subprocess.run([sys.executable, "-m", "alembic", *args])
44
49
  if result.returncode != 0:
45
50
  raise typer.Exit(code=result.returncode)
46
51
 
47
52
 
53
+ def write_migrations_scaffold(root: Path) -> None:
54
+ """Create ``alembic.ini`` and ``migrations/`` (async env reading DATABASE_URL) in ``root``."""
55
+ files = {
56
+ root / "alembic.ini": "db/alembic.ini",
57
+ root / "migrations" / "env.py": "db/env.py",
58
+ root / "migrations" / "script.py.mako": "db/script.py.mako",
59
+ }
60
+ for target, template in files.items():
61
+ target.parent.mkdir(parents=True, exist_ok=True)
62
+ target.write_text(render(template), encoding="utf-8")
63
+ (root / "migrations" / "versions").mkdir(exist_ok=True)
64
+ (root / "migrations" / "versions" / ".gitkeep").touch()
65
+
66
+
48
67
  @db_app.command("init")
49
- def db_init(directory: str = typer.Option("migrations", help="Migrations directory")):
50
- """Initialise Alembic migrations (async-ready template)."""
51
- _alembic("init", "-t", "async", directory)
68
+ def db_init():
69
+ """Set up Alembic migrations (async, reads DATABASE_URL, models from `models/`)."""
70
+ root = Path.cwd()
71
+ if (root / "alembic.ini").exists() or (root / "migrations").exists():
72
+ console.print("[red]❌ alembic.ini or migrations/ already exists")
73
+ raise typer.Exit(code=1)
74
+ write_migrations_scaffold(root)
75
+ models = root / "models"
76
+ if not models.exists():
77
+ models.mkdir()
78
+ (models / "__init__.py").write_text(
79
+ '"""Import each model module here so Alembic can see it (see runapi.Base)."""\n',
80
+ encoding="utf-8",
81
+ )
82
+ console.print("✅ [green]Created alembic.ini and migrations/")
83
+ console.print("Next: define models on `runapi.Base` in models/, then")
84
+ console.print(" runapi db migrate -m 'create tables' && runapi db upgrade")
52
85
 
53
86
 
54
87
  @db_app.command("migrate")
@@ -138,7 +138,7 @@ def doctor():
138
138
  console.print(f"✅ {label}")
139
139
  else:
140
140
  problems += 1
141
- console.print(f"❌ {label}" + (f" - [yellow]{hint}[/yellow]" if hint else ""))
141
+ console.print(f"❌ {label}" + (f" - [yellow]{escape(hint)}[/yellow]" if hint else ""))
142
142
 
143
143
  check(sys.version_info >= (3, 10), f"Python {sys.version.split()[0]}", "requires Python 3.10+")
144
144
  check(True, f"runapi {__version__}")
@@ -153,6 +153,15 @@ def doctor():
153
153
  if not result["errors"]:
154
154
  check(True, f"Configuration ({config.environment})")
155
155
 
156
+ if config.database_url:
157
+ from ...database import check_driver
158
+
159
+ try:
160
+ check_driver(config.database_url)
161
+ check(True, "Database driver installed")
162
+ except ImportError as exc:
163
+ check(False, "Database driver", str(exc))
164
+
156
165
  if problems:
157
166
  console.print(f"\n[red]{problems} problem(s) found[/red]")
158
167
  raise typer.Exit(code=1)
@@ -11,6 +11,43 @@ from .._app import app, console
11
11
  from .._templates import render
12
12
 
13
13
  _PACKAGES = ["routes", "schemas", "repositories", "services"]
14
+ DB_CHOICES = ("none", "sqlite", "postgres")
15
+ _DATABASE_URLS = {
16
+ "sqlite": "sqlite+aiosqlite:///./app.db",
17
+ "postgres": "postgresql+asyncpg://app:app@localhost:5432/app",
18
+ }
19
+
20
+
21
+ def _scaffold_database(project_path: Path, db: str) -> None:
22
+ """Add models, a session object, migrations and (for PostgreSQL) a compose file."""
23
+ from .db import write_migrations_scaffold
24
+
25
+ (project_path / "models").mkdir()
26
+ (project_path / "models" / "__init__.py").write_text(
27
+ render("db/models_init.py"), encoding="utf-8"
28
+ )
29
+ (project_path / "models" / "item.py").write_text(render("db/models_item.py"), encoding="utf-8")
30
+ (project_path / "db.py").write_text(render("db/db.py"), encoding="utf-8")
31
+ (project_path / "main.py").write_text(render("db/main.py"), encoding="utf-8")
32
+ (project_path / "routes" / "api" / "items.py").write_text(
33
+ render("db/route_items.py"), encoding="utf-8"
34
+ )
35
+ write_migrations_scaffold(project_path)
36
+
37
+ env_path = project_path / ".env"
38
+ env_path.write_text(
39
+ env_path.read_text(encoding="utf-8") + f"\n# Database\nDATABASE_URL={_DATABASE_URLS[db]}\n",
40
+ encoding="utf-8",
41
+ )
42
+ version = __version__.split("+")[0].split(".dev")[0]
43
+ (project_path / "requirements.txt").write_text(f"runapi[{db}]>={version}\n", encoding="utf-8")
44
+ if db == "postgres":
45
+ (project_path / "docker-compose.yml").write_text(
46
+ render("db/docker-compose.yml"), encoding="utf-8"
47
+ )
48
+ (project_path / ".env.example").write_text(
49
+ f"SECRET_KEY=change-me\nDATABASE_URL={_DATABASE_URLS[db]}\n", encoding="utf-8"
50
+ )
14
51
 
15
52
 
16
53
  @app.command()
@@ -18,10 +55,17 @@ def init(
18
55
  name: str = typer.Argument(..., help="Project name"),
19
56
  template: str = typer.Option("basic", "--template", "-t", help="Project template"),
20
57
  docker: bool = typer.Option(False, "--docker", help="Also generate a Dockerfile"),
58
+ db: str = typer.Option(
59
+ "none", "--db", help="Database to set up: none, sqlite or postgres", show_default=True
60
+ ),
21
61
  ):
22
62
  """Initialize a new RunApi project."""
23
63
  project_path = Path(name)
24
64
 
65
+ if db not in DB_CHOICES:
66
+ console.print(f"[red]❌ --db must be one of: {', '.join(DB_CHOICES)}")
67
+ raise typer.Exit(code=1)
68
+
25
69
  if project_path.exists():
26
70
  console.print(f"[red]❌ Directory '{name}' already exists")
27
71
  raise typer.Exit(code=1)
@@ -51,6 +95,9 @@ def init(
51
95
  content = render(template_name, project_name=name, secret_key=secrets.token_hex(32))
52
96
  (project_path / target).write_text(content, encoding="utf-8")
53
97
 
98
+ if db != "none":
99
+ _scaffold_database(project_path, db)
100
+
54
101
  if docker:
55
102
  requirements = project_path / "requirements.txt"
56
103
  if not requirements.exists():
@@ -71,4 +118,10 @@ def init(
71
118
 
72
119
  console.print("\n🚀 To get started:")
73
120
  console.print(f" cd {name}")
121
+ if db != "none":
122
+ console.print(f" pip install -r requirements.txt # installs runapi[{db}]")
123
+ if db == "postgres":
124
+ console.print(" docker compose up -d db # start PostgreSQL")
125
+ console.print(" runapi db migrate -m 'create items'")
126
+ console.print(" runapi db upgrade")
74
127
  console.print(" runapi dev")
@@ -0,0 +1,5 @@
1
+ # Alembic configuration (generated by `runapi db init`)
2
+ # The database URL comes from DATABASE_URL (see migrations/env.py), not from this file.
3
+ [alembic]
4
+ script_location = migrations
5
+ prepend_sys_path = .
@@ -0,0 +1,5 @@
1
+ """The shared database object. Import `database` wherever you need a session."""
2
+
3
+ from runapi import Database
4
+
5
+ database = Database() # reads DATABASE_URL
@@ -0,0 +1,19 @@
1
+ services:
2
+ db:
3
+ image: postgres:16-alpine
4
+ environment:
5
+ POSTGRES_USER: app
6
+ POSTGRES_PASSWORD: app
7
+ POSTGRES_DB: app
8
+ ports:
9
+ - "5432:5432"
10
+ volumes:
11
+ - pgdata:/var/lib/postgresql/data
12
+ healthcheck:
13
+ test: ["CMD-SHELL", "pg_isready -U app -d app"]
14
+ interval: 5s
15
+ timeout: 3s
16
+ retries: 10
17
+
18
+ volumes:
19
+ pgdata:
@@ -0,0 +1,61 @@
1
+ """Alembic environment: async engine, URL from DATABASE_URL, models from `Base.metadata`."""
2
+
3
+ import asyncio
4
+
5
+ from alembic import context
6
+ from sqlalchemy.ext.asyncio import create_async_engine
7
+
8
+ from runapi import Base
9
+ from runapi.config import load_config
10
+
11
+ import models # noqa: F401 (importing the package registers every model on Base.metadata)
12
+
13
+ config = context.config
14
+ target_metadata = Base.metadata
15
+
16
+
17
+ def _database_url() -> str:
18
+ url = load_config().database_url
19
+ if not url:
20
+ raise SystemExit(
21
+ "DATABASE_URL is not set, e.g. sqlite+aiosqlite:///./app.db "
22
+ "or postgresql+asyncpg://user:password@localhost:5432/mydb"
23
+ )
24
+ return url
25
+
26
+
27
+ def run_migrations_offline() -> None:
28
+ """Emit SQL to stdout instead of connecting (`alembic upgrade head --sql`)."""
29
+ context.configure(
30
+ url=_database_url(),
31
+ target_metadata=target_metadata,
32
+ literal_binds=True,
33
+ compare_type=True,
34
+ render_as_batch=True,
35
+ )
36
+ with context.begin_transaction():
37
+ context.run_migrations()
38
+
39
+
40
+ def _run_sync_migrations(connection) -> None:
41
+ context.configure(
42
+ connection=connection,
43
+ target_metadata=target_metadata,
44
+ compare_type=True,
45
+ render_as_batch=True, # lets SQLite alter tables; harmless on PostgreSQL
46
+ )
47
+ with context.begin_transaction():
48
+ context.run_migrations()
49
+
50
+
51
+ async def run_migrations_online() -> None:
52
+ engine = create_async_engine(_database_url())
53
+ async with engine.connect() as connection:
54
+ await connection.run_sync(_run_sync_migrations)
55
+ await engine.dispose()
56
+
57
+
58
+ if context.is_offline_mode():
59
+ run_migrations_offline()
60
+ else:
61
+ asyncio.run(run_migrations_online())
@@ -0,0 +1,15 @@
1
+ """RunApi Application Entry Point"""
2
+ from db import database
3
+ from runapi import create_runapi_app
4
+
5
+ runapi_app = create_runapi_app(
6
+ title="My RunApi API",
7
+ description="Built with RunApi framework",
8
+ version="1.0.0"
9
+ )
10
+ runapi_app.use_database(database) # connect on startup, dispose on shutdown, /ready check
11
+
12
+ app = runapi_app.get_app()
13
+
14
+ if __name__ == "__main__":
15
+ runapi_app.run()
@@ -0,0 +1,3 @@
1
+ """Your SQLAlchemy models. Import each model module here so Alembic can see it."""
2
+
3
+ from models.item import Item # noqa: F401
@@ -0,0 +1,11 @@
1
+ from sqlalchemy import String
2
+ from sqlalchemy.orm import Mapped, mapped_column
3
+
4
+ from runapi import Base
5
+
6
+
7
+ class Item(Base):
8
+ __tablename__ = "items"
9
+
10
+ id: Mapped[int] = mapped_column(primary_key=True)
11
+ name: Mapped[str] = mapped_column(String(100))
@@ -0,0 +1,25 @@
1
+ """GET /api/items, POST /api/items: a tiny example using the database session."""
2
+
3
+ from fastapi import Depends
4
+ from pydantic import BaseModel, Field
5
+ from sqlalchemy import select
6
+ from sqlalchemy.ext.asyncio import AsyncSession
7
+
8
+ from db import database
9
+ from models.item import Item
10
+
11
+
12
+ class ItemCreate(BaseModel):
13
+ name: str = Field(..., min_length=1, max_length=100)
14
+
15
+
16
+ async def get(session: AsyncSession = Depends(database.get_session)):
17
+ result = await session.execute(select(Item).order_by(Item.id))
18
+ return [{"id": item.id, "name": item.name} for item in result.scalars()]
19
+
20
+
21
+ async def post(body: ItemCreate, session: AsyncSession = Depends(database.get_session)):
22
+ item = Item(name=body.name)
23
+ session.add(item)
24
+ await session.flush() # assigns item.id; the session commits when the request ends
25
+ return {"id": item.id, "name": item.name}
@@ -0,0 +1,24 @@
1
+ """${message}
2
+
3
+ Revision ID: ${up_revision}
4
+ Revises: ${down_revision | comma,n}
5
+ Create Date: ${create_date}
6
+ """
7
+ from typing import Sequence, Union
8
+
9
+ from alembic import op
10
+ import sqlalchemy as sa
11
+ ${imports if imports else ""}
12
+
13
+ revision: str = ${repr(up_revision)}
14
+ down_revision: Union[str, None] = ${repr(down_revision)}
15
+ branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
16
+ depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
17
+
18
+
19
+ def upgrade() -> None:
20
+ ${upgrades if upgrades else "pass"}
21
+
22
+
23
+ def downgrade() -> None:
24
+ ${downgrades if downgrades else "pass"}
@@ -24,3 +24,7 @@ uploads/
24
24
  # OS
25
25
  .DS_Store
26
26
  Thumbs.db
27
+
28
+ # Local SQLite databases
29
+ *.db
30
+ *.sqlite3
@@ -63,6 +63,7 @@ class RunApiConfig(BaseSettings):
63
63
  log_level: str = "INFO"
64
64
  log_format: str = "%(asctime)s - %(name)s - %(levelname)s - [%(request_id)s] %(message)s"
65
65
  log_json: Optional[bool] = None # defaults to True in production
66
+ log_requests: Optional[bool] = None # log every request/response; defaults to DEBUG
66
67
 
67
68
  # Static files
68
69
  static_files_enabled: bool = True
@@ -115,6 +116,8 @@ class RunApiConfig(BaseSettings):
115
116
  object.__setattr__(self, "debug", not production)
116
117
  if self.log_json is None:
117
118
  object.__setattr__(self, "log_json", production)
119
+ if self.log_requests is None:
120
+ object.__setattr__(self, "log_requests", bool(self.debug))
118
121
  if self.strict_routes is None:
119
122
  object.__setattr__(self, "strict_routes", production)
120
123
  return self
@@ -147,6 +150,28 @@ class RunApiConfig(BaseSettings):
147
150
  """Check if running in production mode (``ENVIRONMENT=production``)."""
148
151
  return self.environment == "production"
149
152
 
153
+ def _check_database_url(self, errors: List[str], warnings: List[str]) -> None:
154
+ url = self.database_url
155
+ if not url:
156
+ return
157
+ example = "e.g. postgresql+asyncpg://user:password@localhost:5432/mydb"
158
+ if "://" not in url:
159
+ errors.append(f"DATABASE_URL is not a valid URL (expected dialect://..., {example})")
160
+ return
161
+ scheme = url.split("://", 1)[0].lower()
162
+ dialect, _, driver = scheme.partition("+")
163
+ if dialect == "postgres":
164
+ warnings.append(
165
+ "DATABASE_URL uses 'postgres://', which SQLAlchemy does not accept; "
166
+ "use 'postgresql+asyncpg://'"
167
+ )
168
+ elif dialect in {"postgresql", "mysql", "sqlite"} and not driver:
169
+ async_driver = {"postgresql": "asyncpg", "mysql": "aiomysql", "sqlite": "aiosqlite"}
170
+ warnings.append(
171
+ f"DATABASE_URL has no async driver; async SQLAlchemy needs "
172
+ f"'{dialect}+{async_driver[dialect]}://'"
173
+ )
174
+
150
175
  def validate_settings(self) -> Dict[str, List[str]]:
151
176
  """Check the configuration for risky settings.
152
177
 
@@ -162,6 +187,7 @@ class RunApiConfig(BaseSettings):
162
187
  warnings.append("SECRET_KEY is shorter than 32 characters")
163
188
  if "*" in self.cors_origins and self.cors_credentials:
164
189
  errors.append("CORS_ORIGINS='*' cannot be combined with CORS_CREDENTIALS=true")
190
+ self._check_database_url(errors, warnings)
165
191
  if self.is_production():
166
192
  if self.debug:
167
193
  errors.append("DEBUG is enabled in production")
@@ -19,7 +19,15 @@ from .middleware import (
19
19
  RunApiMiddleware,
20
20
  SecurityHeadersMiddleware,
21
21
  )
22
- from .routing import RouteFile, build_router, discover_routes, load_module
22
+ from .routing import (
23
+ HTTP_METHODS,
24
+ RouteFile,
25
+ build_router,
26
+ discover_routes,
27
+ has_handlers,
28
+ load_module,
29
+ misnamed_handlers,
30
+ )
23
31
  from .schemas import SchemaRegistry, load_schemas
24
32
 
25
33
 
@@ -30,6 +38,7 @@ class RunApiApp:
30
38
  self.config = config or get_config()
31
39
  self.middleware_stack: List[Type[RunApiMiddleware]] = []
32
40
  self.route_errors: List[str] = []
41
+ self.route_warnings: List[str] = []
33
42
  self.lifecycle = Lifecycle(user_lifespan=fastapi_kwargs.pop("lifespan", None))
34
43
  self.app = self._create_fastapi_app(**fastapi_kwargs)
35
44
 
@@ -82,6 +91,12 @@ class RunApiApp:
82
91
  self.lifecycle.shutdown_hooks.append(func)
83
92
  return func
84
93
 
94
+ def use_database(self, database: Any) -> None:
95
+ """Connect ``database`` on startup, dispose it on shutdown and add a readiness check."""
96
+ self.on_startup(database.connect)
97
+ self.on_shutdown(database.disconnect)
98
+ self.add_readiness_check("database", database.ping)
99
+
85
100
  def add_readiness_check(self, name: str, check: Callable[[], Any]) -> None:
86
101
  """Register a readiness check. It must return truthy (or not raise) when healthy."""
87
102
  self.lifecycle.readiness_checks[name] = check
@@ -145,7 +160,7 @@ class RunApiApp:
145
160
  self.app.add_middleware(SecurityHeadersMiddleware)
146
161
 
147
162
  # Request logging middleware
148
- if self.config.debug:
163
+ if self.config.log_requests:
149
164
  self.app.add_middleware(RequestLoggingMiddleware, logger=self.logger)
150
165
 
151
166
  # Compression middleware
@@ -184,9 +199,23 @@ class RunApiApp:
184
199
  for route in discover_routes(routes_path):
185
200
  self._register_route(route)
186
201
 
202
+ def _warn_no_handlers(self, route: RouteFile, suspects: List[str]):
203
+ message = (
204
+ f"Route file {route.file} defines no handlers, so {route.full_path} will return 404. "
205
+ f"Define functions named exactly: {', '.join(HTTP_METHODS[:5])} (lower-case), "
206
+ "or `websocket`, or export a `router`."
207
+ )
208
+ if suspects:
209
+ message += f" Did you mean to rename {', '.join(suspects)}?"
210
+ self.route_warnings.append(message)
211
+ self.logger.warning(message)
212
+
187
213
  def _register_route(self, route: RouteFile):
188
214
  try:
189
- router = build_router(load_module(route), route.path)
215
+ module = load_module(route)
216
+ router = build_router(module, route.path)
217
+ if not has_handlers(router):
218
+ self._warn_no_handlers(route, misnamed_handlers(module))
190
219
  self.app.include_router(router, prefix=route.prefix)
191
220
  self.logger.debug(f"Loaded route: {route.file} with prefix: {route.prefix}")
192
221
  except Exception as e:
@@ -0,0 +1,157 @@
1
+ """Async database support: engine/session management driven by ``DATABASE_URL``.
2
+
3
+ Requires SQLAlchemy (``pip install "runapi[sqlite]"`` or ``"runapi[postgres]"``). Typical use::
4
+
5
+ # db.py
6
+ from runapi import Database
7
+ database = Database() # reads DATABASE_URL
8
+
9
+ # main.py
10
+ runapi_app.use_database(database) # connect on startup, dispose on shutdown, /ready check
11
+
12
+ # routes/items.py
13
+ from fastapi import Depends
14
+ from sqlalchemy.ext.asyncio import AsyncSession
15
+ from db import database
16
+
17
+ async def get(session: AsyncSession = Depends(database.get_session)):
18
+ ...
19
+ """
20
+
21
+ import importlib.util
22
+ from contextlib import asynccontextmanager
23
+ from typing import Any, AsyncIterator, Optional
24
+
25
+ from .config import RunApiConfig, get_config
26
+ from .errors import ConfigurationError
27
+
28
+ try:
29
+ from sqlalchemy import text
30
+ from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, async_sessionmaker
31
+ from sqlalchemy.ext.asyncio import create_async_engine as _create_async_engine
32
+ from sqlalchemy.orm import DeclarativeBase
33
+ from sqlalchemy.pool import StaticPool
34
+
35
+ DATABASE_AVAILABLE = True
36
+
37
+ class Base(DeclarativeBase):
38
+ """Declarative base for your models. Alembic autogenerate reads ``Base.metadata``."""
39
+
40
+ except ImportError: # pragma: no cover - exercised only without SQLAlchemy installed
41
+ DATABASE_AVAILABLE = False
42
+ Base = None # type: ignore[assignment,misc]
43
+
44
+ # async driver URL scheme -> (importable module, pip extra that installs it)
45
+ DRIVERS = {
46
+ "postgresql+asyncpg": ("asyncpg", "postgres"),
47
+ "sqlite+aiosqlite": ("aiosqlite", "sqlite"),
48
+ "mysql+aiomysql": ("aiomysql", "mysql"),
49
+ }
50
+
51
+
52
+ def check_driver(url: str) -> None:
53
+ """Raise ``ImportError`` with an install hint if SQLAlchemy or the URL's driver is missing."""
54
+ if importlib.util.find_spec("sqlalchemy") is None:
55
+ raise ImportError(
56
+ 'SQLAlchemy is not installed. Install with: pip install "runapi[sqlite]" '
57
+ 'or "runapi[postgres]"'
58
+ )
59
+ scheme = url.split("://", 1)[0].lower()
60
+ if scheme in DRIVERS:
61
+ module, extra = DRIVERS[scheme]
62
+ if importlib.util.find_spec(module) is None:
63
+ raise ImportError(
64
+ f"The '{module}' driver needed by DATABASE_URL ({scheme}) is not installed. "
65
+ f'Install with: pip install "runapi[{extra}]"'
66
+ )
67
+
68
+
69
+ def _is_memory_sqlite(url: str) -> bool:
70
+ return url.startswith("sqlite") and (":memory:" in url or "mode=memory" in url)
71
+
72
+
73
+ class Database:
74
+ """Owns the async engine and hands out sessions.
75
+
76
+ Sessions commit when the ``async with``/request finishes normally and roll back if an
77
+ exception escapes, so route handlers do not need to manage transactions.
78
+ """
79
+
80
+ def __init__(
81
+ self,
82
+ url: Optional[str] = None,
83
+ *,
84
+ echo: Optional[bool] = None,
85
+ config: Optional[RunApiConfig] = None,
86
+ **engine_kwargs: Any,
87
+ ):
88
+ config = config or get_config()
89
+ resolved = url or config.database_url
90
+ if not resolved:
91
+ raise ConfigurationError(
92
+ "DATABASE_URL is not set, e.g. sqlite+aiosqlite:///./app.db "
93
+ "or postgresql+asyncpg://user:password@localhost:5432/mydb"
94
+ )
95
+ self.url: str = resolved
96
+ check_driver(self.url)
97
+ self.echo = config.database_echo if echo is None else echo
98
+ self._engine_kwargs = engine_kwargs
99
+ self._engine: Optional[AsyncEngine] = None
100
+ self._sessionmaker: Optional[async_sessionmaker[AsyncSession]] = None
101
+
102
+ @property
103
+ def engine(self) -> "AsyncEngine":
104
+ if self._engine is None:
105
+ raise RuntimeError("Database is not connected; call `await database.connect()`")
106
+ return self._engine
107
+
108
+ async def connect(self) -> None:
109
+ """Create the engine (idempotent). Called automatically by ``use_database``."""
110
+ if self._engine is not None:
111
+ return
112
+ kwargs = dict(self._engine_kwargs)
113
+ if _is_memory_sqlite(self.url):
114
+ # every new connection would otherwise get its own empty in-memory database
115
+ kwargs.setdefault("poolclass", StaticPool)
116
+ kwargs.setdefault("connect_args", {"check_same_thread": False})
117
+ self._engine = _create_async_engine(self.url, echo=self.echo, **kwargs)
118
+ self._sessionmaker = async_sessionmaker(self._engine, expire_on_commit=False)
119
+
120
+ async def disconnect(self) -> None:
121
+ """Close all pooled connections."""
122
+ if self._engine is not None:
123
+ await self._engine.dispose()
124
+ self._engine = None
125
+ self._sessionmaker = None
126
+
127
+ async def ping(self) -> bool:
128
+ """Readiness check: can we run ``SELECT 1``?"""
129
+ async with self.engine.connect() as connection:
130
+ await connection.execute(text("SELECT 1"))
131
+ return True
132
+
133
+ @asynccontextmanager
134
+ async def session(self) -> AsyncIterator["AsyncSession"]:
135
+ """A session that commits on success and rolls back on error."""
136
+ if self._sessionmaker is None:
137
+ await self.connect()
138
+ assert self._sessionmaker is not None
139
+ async with self._sessionmaker() as session:
140
+ try:
141
+ yield session
142
+ await session.commit()
143
+ except BaseException:
144
+ await session.rollback()
145
+ raise
146
+
147
+ async def get_session(self) -> AsyncIterator["AsyncSession"]:
148
+ """FastAPI dependency: ``session: AsyncSession = Depends(database.get_session)``."""
149
+ async with self.session() as session:
150
+ yield session
151
+
152
+ async def create_all(self) -> None:
153
+ """Create tables from ``Base.metadata``. For quick starts and tests; use migrations
154
+ (``runapi db migrate``) for real projects."""
155
+ await self.connect()
156
+ async with self.engine.begin() as connection:
157
+ await connection.run_sync(Base.metadata.create_all)
@@ -120,3 +120,26 @@ def build_router(module: ModuleType, path: str) -> APIRouter:
120
120
  if callable(getattr(module, "websocket", None)):
121
121
  router.add_api_websocket_route(path, module.websocket)
122
122
  return router
123
+
124
+
125
+ def has_handlers(router: APIRouter) -> bool:
126
+ """True if the router ended up with at least one route."""
127
+ return bool(router.routes)
128
+
129
+
130
+ def misnamed_handlers(module: ModuleType) -> List[str]:
131
+ """Names that look like HTTP handlers but are not exactly ``get``/``post``/...
132
+
133
+ For example ``GET``, ``Get`` or ``get_users``: a common beginner mistake that
134
+ otherwise silently produces an empty route file.
135
+ """
136
+ suspects = []
137
+ for name, value in vars(module).items():
138
+ if name.startswith("_") or not callable(value) or name in HTTP_METHODS:
139
+ continue
140
+ if getattr(value, "__module__", None) != module.__name__:
141
+ continue # imported, not defined here
142
+ lowered = name.lower()
143
+ if lowered in HTTP_METHODS or any(lowered.startswith(m + "_") for m in HTTP_METHODS):
144
+ suspects.append(name)
145
+ return suspects
@@ -227,7 +227,7 @@ def _load_schemas_recursive(
227
227
  ) -> None:
228
228
  """Recursively load schema files from directory structure."""
229
229
 
230
- for item in schemas_dir.iterdir():
230
+ for item in sorted(schemas_dir.iterdir()): # sorted: deterministic collision order
231
231
  if item.is_dir():
232
232
  # Skip hidden directories and __pycache__
233
233
  if item.name.startswith(".") or item.name.startswith("__"):
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes