Skip to content

Build Your First API

This tutorial walks you through building a complete, production-ready backend with Kirak. By the end, you will understand the core mental model and have a running API with authentication, data validation, row-level security, and schema migrations.

The application we will build is a Task Manager API where authenticated users create, view, search, and update their own tasks, while administrators have full oversight.


  • Python 3.11+ (tested on 3.11 through 3.13)
  • pip
  • A database:
    • SQLite (built-in, no server required; recommended for following this tutorial)
    • PostgreSQL 13+ or MySQL 8.0.13+

1. Set Up a Virtual Environment & Install Kirak

Section titled “1. Set Up a Virtual Environment & Install Kirak”

Always use an isolated virtual environment:

macOS / Linux:

Terminal window
python3 -m venv .venv
source .venv/bin/activate

Windows (PowerShell):

Terminal window
python -m venv .venv
.venv\Scripts\Activate.ps1

Windows (Command Prompt):

Terminal window
python -m venv .venv
.venv\Scripts\activate.bat

Install Kirak with the driver matching your database:

SQLite:

Terminal window
pip install kirak

PostgreSQL:

Terminal window
pip install "kirak[postgres]"

MySQL:

Terminal window
pip install "kirak[mysql]"

Verify the installation:

Terminal window
kirak --help

Scaffold a new project using kirak new. Use the --database flag to pre-configure your database engine:

SQLite:

Terminal window
kirak new task-api --database sqlite
cd task-api
pip install -e .

PostgreSQL:

Terminal window
kirak new task-api --database postgres
cd task-api
pip install -e .

MySQL:

Terminal window
kirak new task-api --database mysql
cd task-api
pip install -e .

You now have a clean project structure:

task-api/
+-- main.py # Application entry point
+-- kirak.json # Manifest: database connection, CORS, rate limits
+-- .env.example # Template of required secrets
+-- pyproject.toml
+-- models/
| +-- posts.json # Sample model (we will replace this)
+-- src/
| +-- __init__.py # register(kirak), run by main.py once Kirak is ready
| +-- hooks.py # Custom Python business logic
+-- migrations/ # Auto-generated SQL migrations

Copy the template secrets file into .env:

macOS / Linux:

Terminal window
cp .env.example .env

Windows (PowerShell):

Terminal window
Copy-Item .env.example .env

Windows (Command Prompt):

Terminal window
copy .env.example .env

Open .env and set your secrets:

# Database password (leave empty or omit if using SQLite)
DB_PASSWORD=your-database-password
# 32+ character secret key for JWT token signing (required)
KIRAK_AUTH_JWT_SECRET_KEY=replace-with-a-32-byte-or-longer-secret
# Fernet encryption key for email verification links (required)
KIRAK_AUTH_VERIFICATION_KEY=your-fernet-key-here

Generate a secure Fernet key using this one-liner:

Terminal window
python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"

Note (Database Settings in kirak.json): Because you passed --database when creating the project, kirak.json already has the correct database engine and port configured.

If you are using PostgreSQL or MySQL, check the "database" block in kirak.json to verify the host ("localhost"), database name ("task_api"), and username ("postgres" for PostgreSQL, "task_api_app" for MySQL). For SQLite, no database settings need to be modified.

Confirm that all required environment variables are set:

Terminal window
kirak env

Before defining our model, understand what Kirak handles automatically:

Kirak automatically creates, populates, and manages these four columns on every model. Never add them to your JSON schema:

Field Type When Managed
id INTEGER Auto-increment primary key set on INSERT.
created_at TIMESTAMP UTC timestamp recorded on INSERT.
updated_at TIMESTAMP UTC timestamp updated on every UPDATE.
deleted_at TIMESTAMP UTC timestamp set on soft delete, cleared on restore.

Kirak Core manages all authentication tables automatically (users, auth_tokens, auth_social, auth_mfa, and auth_otp). They are automatically generated in migrations — you do not define them.

Every model JSON separates what the data looks like from who is allowed to touch it:

model.json
├── schema -> Defines columns, data types, constraints, and defaults
└── access -> Defines permissions, row-level security (RLS), and ownership rules

When an API request arrives, it flows through Kirak’s security pipeline automatically. No CRUD endpoints or permission checks need to be manually coded:

flowchart TD
Req["Incoming HTTP Request<br/>(e.g., POST /tasks/create)"] --> Auth["1. Auth & JWT Verification<br/>(Extracts user_id, role)"]
Auth --> Access["2. Access Policy Engine<br/>(Verifies role has 'create' permission)"]
Access --> Inject["3. Claim Injection & RLS<br/>(Auto-injects user_id from token)"]
Inject --> BeforeHook["4. Before Hook (Optional)<br/>(Validation or mutation)"]
BeforeHook --> DB[("5. Database Execution<br/>(Parameterized SQL)")]
DB --> AfterHook["6. After Hook (Optional)<br/>(Side-effects, background jobs)"]
AfterHook --> Resp["7. Response Envelope<br/>({statusCode, status, message, data})"]

Delete the starter models/posts.json file and create models/tasks.json:

{
"$schema": "../.kirak/model.schema.json",
"table": "tasks",
"soft_delete": true,
"schema": {
"title": { "type": "string", "required": true, "max_length": 200, "searchable": true },
"description": { "type": "text" },
"status": { "type": "string", "required": true, "default": "pending",
"enum": ["pending", "in_progress", "done"] },
"user_id": { "type": "integer", "required": true }
},
"access": {
"fetch": [{ "role": "user", "condition": "user_id = {user_id}" },
{ "role": "admin" }],
"search": [{ "role": "user", "condition": "user_id = {user_id}" },
{ "role": "admin" }],
"count": [{ "role": "user", "condition": "user_id = {user_id}" },
{ "role": "admin" }],
"create": [{ "role": "user", "condition": "user_id = {user_id}" },
{ "role": "admin" }],
"update": [{ "role": "user", "condition": "user_id = {user_id}" },
{ "role": "admin" }],
"delete": [{ "role": "user", "condition": "user_id = {user_id}" },
{ "role": "admin" }],
"destroy": [{ "role": "admin" }]
}
}
  • soft_delete: true: When a record is deleted, Kirak sets deleted_at instead of dropping the row. Soft-deleted tasks are invisible to fetch, search, and count queries.
  • enum on status: Enforces validation at the API boundary. Submitting any value other than "pending", "in_progress", or "done" returns an immediate 400 VALIDATION_ERROR.
  • searchable: true on title: Enables text search via GET /tasks/search.
  • Deny-by-default Access: If an operation or role is not explicitly listed in "access", requests are rejected with 403 PERMISSION_DENIED. Notice that hard deletion (destroy) is restricted to the admin role.
  • Row-Level Security (condition): Kirak appends an SQL WHERE user_id = <token_user_id> clause automatically. Regular users only ever see and modify their own tasks.
  • Automatic Ownership Injection: On create, Kirak extracts user_id from the caller’s JWT claims and injects it into the INSERT. Clients cannot forge another user’s ID.

Check your schema for errors before generating SQL:

Terminal window
kirak validate models

  • SQLite: No database creation step needed. SQLite creates the database file automatically.
  • PostgreSQL: Ensure the database exists (matching "name" in kirak.json):
    Terminal window
    createdb task_api
  • MySQL: Ensure the database exists (matching "name" in kirak.json):
    Terminal window
    mysql -u root -p -e "CREATE DATABASE task_api CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
    Then create the app user task_api_app with rights on that database only, and put its password in .env as DB_PASSWORD:
    Terminal window
    mysql -u root -p -e "CREATE USER 'task_api_app'@'%' IDENTIFIED BY 'choose-a-password'; GRANT ALL PRIVILEGES ON task_api.* TO 'task_api_app'@'%';"

Generate and apply the initial database migration:

Terminal window
kirak db init

Output:

Created: migrations/20260801100000_initial.sql
Snapshot: migrations/models_snapshot.json
Applying migration...
Done -- 1 applied, 0 already applied.

Your database now contains the tasks table as well as all auth tables (users, auth_tokens, etc.).


Start your API with Uvicorn:

Terminal window
kirak run

Your API is live at http://localhost:8000. You can inspect the markdown API documentation at http://localhost:8000/docs.


In a separate terminal window, register a user:

Terminal window
curl -X POST http://localhost:8000/auth/register \
-H "Content-Type: application/json" \
-d '{"email": "alice@example.com", "password": "Secret!Pass123", "first_name": "Alice"}'

Important — Check Your Server Terminal Log: Until a production email provider is configured, Kirak prints the email verification link directly to the terminal running Uvicorn:

[kirak] No verification email was sent for alice@example.com. Open this link to verify the account:
http://localhost:8000/auth/verify-email?token=...

Copy and open that link in your web browser, then press Verify my email to verify Alice’s account before attempting to log in.


Log in to receive your JWT access token:

Terminal window
curl -X POST http://localhost:8000/auth/login \
-H "Content-Type: application/json" \
-d '{"email": "alice@example.com", "password": "Secret!Pass123"}'

Response:

{
"statusCode": 200,
"status": "success",
"message": "Login successful",
"data": {
"user": { "user_id": 1, "email": "alice@example.com", "role": "user" },
"accessToken": "eyJhbGciOi...",
"refreshToken": "eyJhbGciOi...",
"expiresIn": 3600
}
}

Store your access token in an environment variable:

macOS / Linux (Bash/Zsh):

Terminal window
export TOKEN="eyJhbGciOi..."

Windows (PowerShell):

Terminal window
$TOKEN = "eyJhbGciOi..."

Windows (Command Prompt):

Terminal window
set TOKEN=eyJhbGciOi...

Note that user_id is automatically injected from the token:

Terminal window
curl -X POST http://localhost:8000/tasks/create \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"data": {"title": "Write documentation", "status": "in_progress"}}'

Response:

{
"statusCode": 200,
"status": "success",
"message": "tasks created successfully",
"data": { "id": 1 }
}

Only tasks belonging to the current user are returned:

Terminal window
curl "http://localhost:8000/tasks/fetch?limit=10&page=1" \
-H "Authorization: Bearer $TOKEN"

Pass the text as search:

Terminal window
curl "http://localhost:8000/tasks/search?search=documentation" \
-H "Authorization: Bearer $TOKEN"

Row-level security ensures users cannot modify tasks belonging to others:

Terminal window
curl -X PUT http://localhost:8000/tasks/update \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"where": {"id": 1}, "data": {"status": "done"}}'

Marks the task as deleted (deleted_at set):

Terminal window
curl -X DELETE "http://localhost:8000/tasks/delete?id=1" \
-H "Authorization: Bearer $TOKEN"

Hooks run before or after database operations without modifying generated routes.

Open src/hooks.py and register an after_create hook:

def register(kirak):
@kirak.on("tasks").hook("after_create")
async def log_new_task(result):
task_id = result["data"]["id"]
print(f"[HOOK] Task #{task_id} was created. Trigger notifications or async jobs here.")
return result # Always return the result to continue the pipeline

There is nothing to add to main.py: it passes register from src/__init__.py as on_kirak_ready, and that calls hooks.register(kirak).

Restart Uvicorn and create a task via curl. The log message will display in your server terminal.


As requirements change, you update the JSON model and generate incremental migrations.

Add a priority field to models/tasks.json:

"priority": { "type": "integer", "default": 0 }

Generate and apply the migration:

Terminal window
kirak db makemigrations add-priority-field
kirak db migrate

Kirak updates your database schema while preserving existing data, populating existing rows with the default value 0.


Kirak runs anywhere Python does. To share the API without setting up a server, kirak deploy puts the project on Kirak’s hosting in one command, with no account and no email:

Terminal window
kirak deploy
Deployed: https://<your-app>...
Claim URL: https://...
Run 'kirak deploy claim-code' to retrieve your claim code.
Custom Python found (1 file). Until you claim this instance, custom endpoints answer 403 INSTANCE_NOT_CLAIMED, and hooks, tools and tasks don't run.

The deploy runs kirak validate first, sends the project’s files (never .env or kirak.local.json) and its secrets from .env, and prints the public URL. It also prints:

  • A claim link. An unclaimed instance is temporary. Open the link, sign in, and enter the 8-character claim code from kirak deploy claim-code to make the instance yours and keep it running. After five wrong codes the claim locks; kirak deploy claim-code --new makes a new code and unlocks it.
  • When it expires, while it is unclaimed, and anything an unclaimed instance does not run yet.

Run kirak deploy again from the same folder to update the same instance: the CLI keeps its state in .kirak/project.json (commit it) and its credentials in .kirak/deploy.json (never commit it; the CLI adds it to .gitignore). After claiming, kirak login lets you deploy from any machine.

How long an unclaimed instance lives, and what the free tier includes: kirak.io/deploy. Every option of the command: kirak deploy.


You have experienced the complete Kirak development cycle: declare schema $\rightarrow$ migrate $\rightarrow$ secure $\rightarrow$ extend with hooks $\rightarrow$ evolve.

flowchart LR
A["1. Declare<br/>(models/*.json)"] --> B["2. Validate<br/>(kirak validate)"]
B --> C["3. Migrate<br/>(kirak db makemigrations)"]
C --> D["4. Extend<br/>(src/*.py)"]
D --> E["5. Evolve<br/>(Repeat as schema changes)"]
Topic Guide
Complete field types, validations, and indexes Defining Models
Filtering, pagination, sorting, and bulk CRUD operations CRUD Operations
Advanced access control, guest access, and dynamic conditions Access Control
Sync vs. async hooks, before/after interceptors, and auth hooks Hooks & Events
Social login, Multi-Factor Authentication (TOTP), and SMS OTP Authentication Guide
Optional modules (Storage, Payments, Notifications, AI, Queues) Modules Overview