Skip to main content

SwiftAPI

PyPI Python CI License Typed

异步微服务工程内核 —— 不依赖任何 Web 框架(无 FastAPI / Starlette / Django / Flask),自研 ASGI 微框架 + Pydantic 契约,补齐「从 hello world 到能上生产」之间那段没人愿意写、但每个团队都要重写一遍的代码。

不是又一个 Web 框架,而是内核 + 强约定 + 生成器:显式依赖注入、用例层事务边界、RFC 9457 错误契约、可插拔后端、多方言数据层、双基类模型层、SaaS 多租户、Outbox、管理后台。

安装包名是 swiftapi-kernel,import 包名与 CLI 命令是 swiftapi。当前 0.1.2(Beta),Python ≥ 3.12。


为什么选它

零 Web 框架依赖 路由 / 参数绑定 / 中间件 / OpenAPI 全部自研(约 1.5k 行),依赖面收敛到 Pydantic + SQLAlchemy;ruff banned-api 强制拦截 fastapi / starlette / flask / django
强约定,不靠自觉 一个用例一个事务、租户查询 fail-closed、事件写在业务事务内;ruff + mypy --strict + import-linter + 覆盖率把规则变成 CI 门禁
生成器产出可运行结构 new project / new resource / new endpoint 直接生成五层竖切 + 迁移 + 测试:结构正确,业务自己写

能力一览

层 能力
ASGI 内核 App / Router / 参数绑定 / problem+json / OpenAPI 3.1 / 纯 ASGI 中间件 / 安全头
配置 单一 Settings(Django 风格模块 + 环境变量 + .env),启动期组合校验,非法组合拒绝启动
DI 三作用域容器(singleton / request / transient),启动期依赖图、循环、作用域倒挂校验
数据层 BaseModel / TenantScopedModel、CRUDBase、UnitOfWork、迁移引擎,SQLite / PostgreSQL / MySQL
多租户 row / schema / database 三种策略;JWT / header / path / subdomain 解析;查询级自动过滤
韧性 出站客户端(SSRF 防护 + 舱壁 + 熔断 + 重试)、限流、JWT、Outbox + 中继 + 幂等、Redis Streams、RabbitMQ
运维面 四路日志 + 归档、Prometheus 指标、/livez /readyz、管理后台、审计哈希链、TS 类型生成

安装

pip install swiftapi-kernel
swiftapi version          # → swiftapi 0.1.2

默认依赖已包含 SQLite 驱动 + uvicorn + httpx,装完即可跑通全流程。按需加后端(只改配置,不改代码):

pip install "swiftapi-kernel[postgres]"   # asyncpg
pip install "swiftapi-kernel[mysql]"      # asyncmy
pip install "swiftapi-kernel[cache]"      # redis
pip install "swiftapi-kernel[rabbitmq]"   # aio-pika

从源码开发:

uv venv --python 3.12 .venv && source .venv/bin/activate   # Windows: .venv\Scripts\activate
uv pip install -e ".[dev]"
make dev

快速上手(5 分钟)

# 1) 创建项目:在项目根目录执行,生成 myservice/myservice/
mkdir myservice && cd myservice
swiftapi new project myservice --path .

# 2) 生成迁移并建表(默认 SQLite,开箱即用)
cd myservice
swiftapi db revision --models myservice.models -m init --dir migrations
swiftapi db upgrade --dir migrations

# 3) 启动自检:真正 import 项目并生成 OpenAPI,路由/依赖/配置问题先在这里暴露
swiftapi check

# 4) 启动(开发模式,自动重载)
swiftapi run --reload --port 8000

启动后:

地址 期望
http://127.0.0.1:8000/livez {"status":"ok"}
http://127.0.0.1:8000/readyz 各依赖健康状态
http://127.0.0.1:8000/version 名称 / 版本 / 环境
http://127.0.0.1:8000/docs 文档页(docs.enabled=true)
http://127.0.0.1:8000/metrics Prometheus 指标
http://127.0.0.1:8000/openapi.json OpenAPI 3.1 契约

配置在 myservice/settings.py,换数据库只改 database.url 一行:

settings = {
    "app": {"name": "myservice", "env": "dev"},
    "database": {"url": "sqlite+aiosqlite:///./myservice.db"},   # 换 PG/MySQL 只改这行
    "tenant": {"enabled": True, "resolver": ["jwt", "header"], "default_slug": "acme"},
    "security": {
        "jwt_algorithm": "HS256",
        "jwt_private_key": "myservice-dev-secret-please-rotate-32",
        "allow_insecure": True,          # 仅开发;prod 强制 RS256
    },
    "docs": {"enabled": True, "title": "myservice API"},
    "observability": {"log_level": "INFO", "log_format": "console"},
}

加第一个业务能力

cd ..        # 回到 myservice/(项目包的父目录)
swiftapi new resource order --project myservice
cd myservice
swiftapi db revision --models myservice.models -m "add order" --dir migrations
swiftapi db upgrade --dir migrations
pytest resources/order/test_api.py -q    # 需先 pip install pytest

生成器产出 model / schemas / service / router / test_api 五件套(默认带分页、软删、乐观锁、 Idempotency-Key 幂等和 2 个通过的测试)。只加一个接口用:

swiftapi new endpoint assign_ticket --project myservice --method POST

常用命令

场景 命令
版本 swiftapi version
生效配置 + 来源 swiftapi config show
启动自检 swiftapi check
启动 swiftapi run --port 8000(带端口预检)
起项目(示例模板) swiftapi new project <name> --path <dir>
起项目(Django 风格) swift-api startproject <name> / swift-api startapp <app>
加 CRUD swiftapi new resource <entity> --project <pkg>
加单接口 swiftapi new endpoint <name> --project <pkg> --method POST
生成迁移 swiftapi db revision --models <pkg>.models -m "msg" --dir migrations
执行迁移 swiftapi db upgrade --dir migrations [--dry-run]
导出契约 swiftapi openapi spec --out openapi.json
生成 TS 类型 swiftapi openapi ts --out clients/ts/types.ts

项目结构

<project>/
├── settings.py          # 唯一配置来源
├── app.py               # 装配入口 create_app()
├── models.py            # 领域模型入口
├── schemas.py           # 跨资源共享的契约
├── service.py           # 跨资源共享的用例
├── api.py               # 模板自带示例域的路由
├── endpoints/           # new endpoint 产物(单接口,自包含)
└── resources/<entity>/  # new resource 产物(一条 CRUD 竖切)
    ├── model.py  schemas.py  service.py  router.py  test_api.py

质量门禁

make check     # ruff + mypy --strict + import-linter + pytest(含 services/mall)
make cov       # 覆盖率(门槛 85%)
make audit     # bandit + pip-audit

CI 矩阵:Ubuntu / macOS / Windows × Python 3.12,Python 3.13 兼容性,SQLite / PostgreSQL / MySQL 三轮集成,Redis Streams / RabbitMQ,wheel/sdist 干净安装冒烟。

文档

以下文档在本地维护,不随公开仓库分发(.gitignore 已忽略 docs/)。

  • 完整使用规范、硬性规则、能力说明与实测数据:docs/使用注意文档.md
  • 发布流程(详细版):docs/发布文档.md
  • 安全策略:docs/安全策略.md
  • 变更记录:docs/变更记录.md
  • 开发约定(面向贡献者与 AI 代理):AGENTS.md

License

Apache-2.0

Metadata

Release files for swiftapi-kernel 0.1.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for swiftapi-kernel 0.1.2
File Size Uploaded Provenance Actions
swiftapi_kernel-0.1.2.tar.gz 288.0 kB Without provenance Details for swiftapi_kernel-0.1.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for swiftapi-kernel 0.1.2
File Interpreter ABI Platform Actions
swiftapi_kernel-0.1.2-py3-none-any.whl Python 3 none any Details for swiftapi_kernel-0.1.2-py3-none-any.whl

Total release size: 549.1 kB

Release files / swiftapi_kernel-0.1.2.tar.gz

Download URL swiftapi_kernel-0.1.2.tar.gz
Size 288.0 kB
Tags Source
SHA-256 checksum
How to use checksums
80c2d057726788f413a592df09c9b3db3539855798a45cc10b23c5e124b80836
BLAKE2b-256 checksum
How to use checksums
12f86d1ba701c05c13a8354d1dbffceef6ef95b889ab56df48b7795566507667
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / swiftapi_kernel-0.1.2-py3-none-any.whl

Download URL swiftapi_kernel-0.1.2-py3-none-any.whl
Size 261.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
860242956c5a3b3416ec90f3643b09cdd21455a88352b3d5143cbfde2a03dce9
BLAKE2b-256 checksum
How to use checksums
a32649cfff67635d0214695c18281c07fb41252c1228defb75b8f9693ba7e51b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Security for swiftapi-kernel 0.1.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.2 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page