Skip to content

Build a REST API with Shakti

This walks through building a small task-tracking REST API with Shakti Python Framework — a database-backed resource with full CRUD, in well under a hundred lines.

Scaffold the project

shakti new task-api
cd task-api
pip install -r requirements.txt

Generate a model and CRUD router in one command

Shakti can scaffold both the model and the router from a field spec:

shakti generate api Task title:str done:bool priority:int

This writes app/models/task.py (a SQLAlchemy model with title, done, priority, plus an auto-added id and timestamps) and app/routers/task.py (a full CRUD router: list, create, get, update, delete). See Code Generation for the exact field DSL.

Wire it up

In app/main.py:

from app.routers.task import router as task_router
app.include_router(task_router)

Create the table

shakti makemigrations "add tasks"
shakti migrate
shakti run --reload

Use it

curl -X POST http://127.0.0.1:8000/tasks \
  -H "Content-Type: application/json" \
  -d '{"title": "Ship the API", "done": false, "priority": 1}'

curl http://127.0.0.1:8000/tasks
curl http://127.0.0.1:8000/tasks/1
curl -X PUT http://127.0.0.1:8000/tasks/1 -d '{"done": true}'
curl -X DELETE http://127.0.0.1:8000/tasks/1

Five working REST endpoints, backed by a real database, from one CLI command plus a router include.

What's actually happening under the hood

The generated router uses Repository for the database work and Shakti's dependency injection to hand each handler a session-bound repository — no manual session management in your own code:

@router.get("/{id:int}")
async def get_task(id: int, repo: Repository = Depends(_repo)) -> dict:
    return (await repo.get_or_404(id)).to_dict()

get_or_404 raises a proper 404 automatically if the row doesn't exist — see Request & Response for how error handling works across the framework.

Next: lock it down and add AI

A public CRUD API is a starting point, not an endpoint. From here: