DEV Community

Cover image for Introducing SwiftPY: An Async First Python Framework with the Soul of Laravel
Akeem O. Salau
Akeem O. Salau

Posted on

Introducing SwiftPY: An Async First Python Framework with the Soul of Laravel

Python has world class tools for building APIs. What it has lacked, at least for developers who come from Laravel, Rails or Django, is a framework that decides the boring things for you and then stays out of your way.

SwiftPY is my attempt to fill that gap. It is an ASGI native, Eloquent style Python web framework that combines the developer experience of FastAPI with the elegance and structure of Laravel. It is built on Python 3.12+ and asyncpg, and it is heading towards its first stable release, 1.0.0.

In this post

  • Why SwiftPY exists
  • A tour of the framework in real code
  • The security defaults that ship out of the box
  • Measured performance, with the caveats
  • What is stable today and how you can help before 1.0.0

The gap

FastAPI proved that async first Python can be fast and pleasant. But FastAPI is a toolkit, and every serious project begins with the same assembly work: choose an ORM, choose a migration tool, invent a folder structure, decide where validation lives, wire a connection pool into dependency injection, and figure out background jobs.

Laravel taught a generation of developers that conventions compound. When the framework answers those questions once, every project starts further ahead, and every new teammate already knows where things live.

SwiftPY brings that philosophy to modern async Python. It replaces fragmented third party glue with one cohesive framework.

A tour in code

Routing, groups and middleware

from swiftpy import (
    CORS, Application, CurrentUser, JWTGuard, Request,
    RequestId, Response, RouteGroup, SecurityHeaders, json_response,
)

app = Application(title="SwiftPY Store API", version="1.0.0")
app.middleware([RequestId, SecurityHeaders, CORS])


@app.get("/ping")
async def ping(request: Request) -> dict[str, str]:
    return {"message": "pong"}  # dicts and lists become JSON automatically


@app.group("/api/v1")
def v1_routes(group: RouteGroup) -> None:
    @group.get("/users/{user_id}")
    async def show_user(request: Request, user_id: int) -> Response:
        return json_response({"user_id": user_id, "ok": True})


@app.group("/api/v1/account", middleware=[JWTGuard])
def account_routes(group: RouteGroup) -> None:
    @group.get("/me")
    async def me(user: CurrentUser) -> Response:
        return json_response({"user": dict(user)})
Enter fullscreen mode Exit fullscreen mode

Path parameters are coerced from their type hints (user_id: int), and static routes resolve through a direct dictionary lookup instead of regex scanning.

An Active Record ORM that feels familiar

from swiftpy.database.orm import HasMany, HasOne, Model


class Post(Model):
    __table__ = "posts"
    __fillable__ = ["title", "user_id"]

    id: int
    title: str
    user_id: int


class User(Model):
    __table__ = "users"
    __fillable__ = ["name", "email"]

    id: int
    name: str
    email: str

    posts = HasMany(Post, foreign_key="user_id")


users = await User.with_("posts").where("name", "Alice").get()

user = await User.find(1)
if user is not None:
    user.name = "Alice Cooper"
    await user.save()  # only changed columns are written
Enter fullscreen mode Exit fullscreen mode

Models use plain type hints. Relationships (HasMany, HasOne, BelongsTo, BelongsToMany) load through explicit eager loading, and lazy loading can be switched off entirely with prevent_lazy_loading = True so an accidental N+1 query raises an error instead of quietly slowing you down.

The query builder includes paginate() and a cheaper simple_paginate(), plus group_by(), having() and aggregate selectors.

Validation that runs before your handler

from swiftpy import Response, json_response
from swiftpy.validation import FormRequest
from swiftpy.validation.rules import email, min_, required, string, unique


class RegisterRequest(FormRequest):
    def rules(self) -> dict[str, object]:
        return {
            "name": [required(), string(), min_(3)],
            "email": [required(), email(), unique("users", "email")],
            "password": [required(), string(), min_(8)],
        }


@app.post("/register")
async def register(form: RegisterRequest) -> Response:
    data = form.validated()  # invalid input returns a 422 before this line
    user = await User.create(name=data["name"], email=data["email"])
    return json_response(user.to_dict(), status_code=201)
Enter fullscreen mode Exit fullscreen mode

The unique rule queries PostgreSQL asynchronously, so validation never blocks the event loop.

Migrations with a fluent schema builder

from swiftpy.database.migrations import Blueprint, Migration, Schema


class CreatePostsTable(Migration):
    async def up(self) -> None:
        def define(table: Blueprint) -> None:
            table.id()
            table.big_integer("user_id").unsigned()
            table.string("title", 200)
            table.text("body").nullable()
            table.boolean("is_published").default(False)
            table.timestamps()
            table.foreign_key(
                "user_id", references="id", on="users", on_delete="CASCADE"
            )

        await Schema.create("posts", define)

    async def down(self) -> None:
        await Schema.drop_if_exists("posts")
Enter fullscreen mode Exit fullscreen mode

Concurrent runners are guarded by a PostgreSQL advisory lock, and checksums detect migrations that were edited after they ran.

Background jobs with retries and a dead letter queue

from swiftpy.queue import Job


class SendWelcomeEmail(Job):
    tries = 3
    backoff = (1.0, 5.0, 15.0)

    def __init__(self, user_id: int, email: str) -> None:
        super().__init__(user_id=user_id, email=email)
        self.user_id = user_id
        self.email = email

    async def handle(self) -> None:
        print(f"Sending welcome email to {self.email}")

    async def failed(self, exception: BaseException) -> None:
        print(f"Failed permanently for user {self.user_id}: {exception}")


await SendWelcomeEmail(user_id=42, email="alice@example.com").dispatch()
Enter fullscreen mode Exit fullscreen mode

Queues use Redis with visibility leases, so a crashed worker does not lose its job. Delivery is at least once, which means handle() should be idempotent. Passing after_commit=True to dispatch() holds the job until the surrounding database transaction commits, and drops it if the transaction rolls back.

A native AI subsystem

SwiftPY grew up alongside AI projects, so AI is a first class module instead of a plugin.

from swiftpy import StreamingResponse
from swiftpy.ai import AI


@app.get("/ai/stream")
async def stream_answer(question: str = "Explain asyncpg pooling") -> StreamingResponse:
    async def chunks():
        client = AI.chat(model="claude-3-5-sonnet-20241022").user(question)
        async for token in client.stream():
            yield token.encode("utf-8")

    return StreamingResponse(chunks(), media_type="text/plain; charset=utf-8")
Enter fullscreen mode Exit fullscreen mode

One shared connection pool serves OpenAI and Anthropic, and the same module includes batched embeddings, vector store adapters (pgvector, Qdrant, Pinecone, Chroma, LanceDB and an in memory store), rag() pipelines with rerankers, and @tool driven Agent loops with session memory. For tests, AIFake intercepts every call:

from swiftpy.ai import Agent, AgentMemory, AIFake, InMemoryMemoryBackend, tool


@tool
async def lookup_order_status(order_id: int) -> dict[str, object]:
    """Look up fulfillment status for a customer order ID."""
    return {"order_id": order_id, "status": "shipped"}


with AIFake("Order #42 is shipped.") as fake:
    agent = Agent(
        name="SupportAssistant",
        system_prompt="Help customers track orders accurately.",
        tools=[lookup_order_status],
        memory=AgentMemory(backend=InMemoryMemoryBackend(), session_id="user-7"),
        model="gpt-4o-mini",
    )
    reply = await agent.run("Where is order #42?", session_id="user-7")
    fake.assert_called_once()
Enter fullscreen mode Exit fullscreen mode

A CLI that writes the boring code

swiftpy new my_service
swiftpy make:model Post --migration
swiftpy make:request RegisterRequest
swiftpy make:service admin/account_service
swiftpy migrate && swiftpy db:seed
swiftpy queue:work --queue default
swiftpy start --host 0.0.0.0 --port 8000 --workers 4
Enter fullscreen mode Exit fullscreen mode

Secure by default

Many of SwiftPY's defaults are deliberately strict, and each one traces back to a security review:

  • Mass assignment is denied unless a model declares __fillable__ or __guarded__.
  • Writes without a WHERE clause raise QueryError, unless you explicitly chain .allow_all().
  • Validation fails closed. If a request's rules cannot be built, the request fails instead of running unvalidated.
  • JWT secrets under 32 bytes are rejected in production, and the JWT issuer rejects the none algorithm and algorithm confusion attacks.
  • SQL identifiers are validated and quoted, and values are always parameterized.
  • Request bodies are capped at 2 MiB with a JSON nesting limit of 32, both configurable per route.
  • WebSocket handshakes enforce same origin checks unless you configure allowed origins.
  • Production mode never leaks tracebacks. Debug mode is refused when APP_ENV=production.

Performance, measured with caveats

These numbers come from wrk against the containerized runtime in Docker, with PostgreSQL and Redis connected. They show where the framework lands on one setup, not a universal promise, so please measure on your own hardware.

  • Simple JSON route: about 6,500 requests per second (P50 14 ms)
  • JWT authenticated route backed by a database query: about 1,065 requests per second (P50 78 ms)
  • Streaming SSE route: about 4,100 requests per second (P50 8 ms)

The biggest wins came from profiling: an O(1) static route table, cached dependency reflection, and a pipelined Redis check for revoked tokens.

What changed in v0.2.0

The latest release focuses on everyday ergonomics:

  • validate(request, rules) returning ValidatedData, with dict and attribute access
  • Request.input() and a declarative abort() helper
  • Router(prefix=..., middleware=...) configured through the constructor
  • Structured, non blocking logging through a Log facade
  • Refresh token rotation with refresh_token_pair(), plus auth().logout() and logout_all()
  • 17 user guides in the repository

Where SwiftPY stands

SwiftPY is in beta, published to PyPI as experimental and beta versions, and I am dogfooding it on real projects, including the framework's own documentation site. Real projects keep exposing unexpected behaviour, weak spots and security gaps, and each one becomes a fix, a test and a new release.

I am not going to publish 1.0.0 just to have a stable looking version number. It will ship when I am confident the framework is stable, secure and reliable enough for production. The documentation site will live at https://swiftpy.net, and the source is at https://github.com/obrainwave/swiftpy.

Help shape it before 1.0.0

I am looking for Python developers who want to get hands on with the beta. You can help by:

  1. Building a small application with SwiftPY.
  2. Testing the ORM, migrations, routing, validation and CLI.
  3. Reporting bugs and potential security issues.
  4. Contributing code, tests, examples or documentation.

No open source experience is required. If you are comfortable with Python, I would love your feedback.

Send me a DM with "SWIFTPY TESTER" and I will share how to get started.

SwiftPY: Building towards 1.0.0.

Top comments (0)