DocsJavaScript backends
From Elysia to Nexy
In Nexy an Elysia route becomes a Python file under src/routes/: t.Object schemas become
Pydantic models, .group becomes a folder, beforeHandle a dependencies.py, and Eden's typed
client becomes typed actions.
Each section below shows an Elysia habit, then the same thing in Nexy.
A route
import { Elysia } from "elysia"; new Elysia().get("/api/hello", () => ({ message: "Hello" })).listen(3000);The file path is the URL, the function name is the method:
async def GET(): return {"message": "Hello"}Params and query with t
import { Elysia, t } from "elysia"; new Elysia().get("/api/users/:id", ({ params, query }) => ({ id: params.id, fields: query.fields }), { params: t.Object({ id: t.Numeric() }), query: t.Object({ fields: t.Optional(t.String()) }),});The types go on the parameters, and :id is a [id] segment:
async def GET(id: int, fields: str | None = None): return {"id": id, "fields": fields}A body with t.Object
app.post("/api/items", ({ body, set }) => { set.status = 201; return body;}, { body: t.Object({ name: t.String(), price: t.Number({ exclusiveMinimum: 0 }) }),});from pydantic import BaseModel, Field from nexy.http import JSONResponse class NewItem(BaseModel): name: str price: float = Field(gt=0) async def POST(item: NewItem): return JSONResponse(item.model_dump(), status_code=201)response schemas
app.get("/api/me", () => ({ name: "Ada" }), { response: t.Object({ name: t.String() }),});The return type is the response schema: undeclared fields are left out of the answer.
from pydantic import BaseModel class PublicUser(BaseModel): name: str async def GET() -> PublicUser: return {"name": "Ada", "password_hash": "x"}.group
app.group("/admin", (admin) => admin.get("/stats", () => ({ users: 3 })));The folder is the group:
async def GET(): return {"users": 3}beforeHandle and guard
app.group("/admin", (admin) => admin .guard({ beforeHandle({ headers, error }) { if (headers["x-role"] !== "admin") return error(403, "Admins only"); }, }) .get("/stats", () => ({ users: 3 })),);A dependencies.py guards every route of its folder:
from nexy.http import Header, HTTPException def require_admin(x_role: str = Header("")) -> None: if x_role != "admin": raise HTTPException(status_code=403, detail="Admins only") dependencies = [require_admin]derive, decorate and state
app .derive(({ headers }) => ({ token: headers.authorization?.replace("Bearer ", "") })) .get("/api/whoami", ({ token }) => ({ token }));What derive adds to the context is a dependency, asked for by the handler:
from nexy.http import Depends, Header def token(authorization: str = Header("")) -> str: return authorization.removeprefix("Bearer ") async def GET(token: str = Depends(token)): return {"token": token}decorate and state are plain module-level objects, imported where they are needed.
onAfterHandle and mapResponse
app.onAfterHandle(({ set }) => { set.headers["x-app"] = "demo";});from nexy.http import Request async def middleware(request: Request, call_next): response = await call_next(request) response.headers["x-app"] = "demo" return responseerror() and onError
app.get("/api/orders/:id", ({ params, error }) => { if (Number(params.id) > 100) return error(404, "No such order"); return { id: params.id };});from nexy.http import HTTPException async def GET(id: int): if id > 100: raise HTTPException(status_code=404, detail="No such order") return {"id": id}A notfound.nexy at the routes root answers browsers on an unknown URL.
Cookies
app.get("/api/theme", ({ cookie: { theme } }) => ({ theme: theme.value ?? "light" }));from nexy.http import Cookie async def GET(theme: str = Cookie("light")): return {"theme": theme}Eden Treaty
const app = new Elysia().post("/todos", ({ body }) => ({ title: body.title, done: false }), { body: t.Object({ title: t.String() }),}); export type App = typeof app;import { treaty } from "@elysiajs/eden";import type { App } from "./src/index"; const api = treaty<App>("localhost:3000");const { data } = await api.todos.post({ title: "Write the docs" });An action is the Python function and its typed client at once. Nexy generates the TypeScript types from the Python signature:
from pydantic import BaseModel from nexy.decorators import Action class Todo(BaseModel): title: str done: bool = False @Actionasync def add_todo(title: str) -> Todo: return Todo(title=title)import { useAction } from "@nexy/client";import { add_todo } from "@nexy/actions"; export function AddTodo() { const { run, pending, data } = useAction(add_todo); return ( <button disabled={pending} onClick={() => run({ title: "Write the docs" })}> {data ? `Added ${data.title}` : "Add"} </button> );}See Actions.
Plugins: cors, swagger, static
import { cors } from "@elysiajs/cors";import { staticPlugin } from "@elysiajs/static";import { swagger } from "@elysiajs/swagger"; app.use(cors({ origin: "https://example.com" })).use(swagger()).use(staticPlugin());| Elysia plugin | Nexy |
|---|---|
@elysiajs/cors |
useCORS = {"allow_origins": [...]} in nexyconfig.py |
@elysiajs/swagger |
nothing: /docs is on by default |
@elysiajs/static |
nothing: public/ is served at / |
from nexy.core.models import NexyConfigModel class NexyConfig(NexyConfigModel): useCORS = {"allow_origins": ["https://example.com"]}WebSockets
app.ws("/ws/echo", { message(ws, message) { ws.send(message); },});from fastapi import WebSocket async def SOCKET(websocket: WebSocket): await websocket.accept() await websocket.send_text(await websocket.receive_text())Tests with app.handle
import { describe, expect, it } from "bun:test"; it("says hello", async () => { const response = await app.handle(new Request("http://localhost/api/hello")); expect(await response.json()).toEqual({ message: "Hello" });});from fastapi.testclient import TestClient from nexy.app import app def test_hello(): assert TestClient(app).get("/api/hello").json() == {"message": "Hello"}Running
| Elysia | Nexy |
|---|---|
bun create elysia app |
nx new |
bun dev |
nx dev |
bun build --compile |
nx build, then nx start |
bun test |
nx test |
Nexy runs on Python. Node is only needed when the project has client components: Vite
builds them, and nx start runs without it.