FastAPI Target

Compile KERN to Python FastAPI applications. Routes become async endpoint functions, schemas generate Pydantic models, and the server boots with uvicorn.

What it generates

KERN input:

server name=API port=8000
  middleware name=cors

  route method=get path=/api/items
    schema response=Item[]
    handler name=list_items

  route method=post path=/api/items
    schema body=CreateItem response=Item
    handler name=create_item

Compiled output:

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel

class Item(BaseModel):
    id: str
    name: str

class CreateItem(BaseModel):
    name: str

app = FastAPI(title="API")
app.add_middleware(CORSMiddleware, allow_origins=["*"])

@app.get("/api/items", response_model=list[Item])
async def list_items():
    ...

@app.post("/api/items", response_model=Item)
async def create_item(body: CreateItem):
    ...

Target-specific nodes

The FastAPI target shares backend nodes with Express but generates Python instead of TypeScript:

  • server — Application root, emits FastAPI() instance
  • route — HTTP route, emits @app.get / @app.post decorators
  • middleware — Emits app.add_middleware calls
  • handler — Async handler function
  • schema — Emits Pydantic BaseModel classes

Configuration

FastAPI-specific options in kern.config.ts:

  • fastapi.security — Enable security dependencies (OAuth2, API keys)
  • fastapi.cors — CORS configuration (origins, methods, headers)
  • fastapi.gzip — Enable GZip middleware (default: false)
  • fastapi.uvicorn — Uvicorn server options (host, reload, workers)
import { defineConfig } from '@kernlang/cli';

export default defineConfig({
  target: 'fastapi',
  outdir: 'app/',
  fastapi: {
    cors: { origins: ['http://localhost:3000'] },
    gzip: true,
    uvicorn: { host: '0.0.0.0', reload: true },
  },
});

Quick start

kern dev api.kern --target=fastapi