Kiro steering for FastAPI backends on AWS: Pydantic v2 request/response models, async SQLAlchemy sessions, and calling synchronous boto3 safely.
.kiro/steering/kiro-python-backend.md. Downloaded files need to be placed in that repository path.---
inclusion: fileMatch
fileMatchPattern: "**/*"
---
Apply these rules to Python backend code using FastAPI.
## FastAPI structure
```python
from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException, status
from pydantic import BaseModel, EmailStr
from sqlalchemy.ext.asyncio import AsyncSession
from app.db import get_session
from app.models import User
app = FastAPI()
SessionDep = Annotated[AsyncSession, Depends(get_session)]
class UserCreate(BaseModel):
email: EmailStr # needs the email-validator package
name: str
class UserOut(BaseModel):
id: str
email: EmailStr
name: str
model_config = {"from_attributes": True}
@app.post("/users", status_code=status.HTTP_201_CREATED, response_model=UserOut)
async def create_user(data: UserCreate, session: SessionDep) -> User:
user = User(**data.model_dump())
session.add(user)
await session.commit()
await session.refresh(user)
return user
@app.get("/users/{user_id}", response_model=UserOut)
async def get_user(user_id: str, session: SessionDep) -> User:
user = await session.get(User, user_id)
if user is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
return user
```
- Use separate input and output models; `response_model` controls which fields leave the API (never return password hashes or internal fields).
- `await` only on async APIs: use `AsyncSession` with an async driver (asyncpg, aiosqlite). With a synchronous `Session`, write the endpoint as plain `def` so FastAPI runs it in a thread pool.
## AWS integration
- boto3 is synchronous. Calling it directly inside `async def` blocks the event loop. Either use plain `def` endpoints/functions for boto3 calls, run them with `anyio.to_thread.run_sync` / `starlette.concurrency.run_in_threadpool`, or use an async client library.
```python
import os
import boto3
from starlette.concurrency import run_in_threadpool
_table = boto3.resource("dynamodb").Table(os.environ["USERS_TABLE"])
def _get_user_item(user_id: str) -> dict | None:
response = _table.get_item(Key={"pk": f"USER#{user_id}", "sk": "PROFILE"})
return response.get("Item")
async def get_user_item(user_id: str) -> dict | None:
return await run_in_threadpool(_get_user_item, user_id)
```
- boto3 resource objects are not thread-safe; if requests run in multiple threads, create resources per thread or use low-level clients.
- Read table names and settings from environment variables or configuration, not literals.
- Give the runtime role least-privilege access (for example `dynamodb:GetItem` on one table).
## Testing
- Test endpoints with `TestClient` (or `httpx.AsyncClient`) and override dependencies (`app.dependency_overrides`) to supply a test session or fake repository.
Cursor rule for FastAPI projects using Pydantic v2 schemas, SQLAlchemy 2 async_sessionmaker, lifespan cleanup, explicit commits and 409 conflict handling.
Cursor rule for Express 5 APIs in TypeScript with createApp structure, no try/catch boilerplate, Zod 4 validation into res.locals and a safe central error handler.
Cursor rule for Next.js Route Handlers with Zod 4 safeParse validation, auth and ownership checks, awaited params, bounded pagination and one consistent JSON error shape.
Kiro
backend
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
A Kiro-built FastAPI service annotates a synchronous Session but awaits db.commit(), calls boto3 inside async def, and returns ORM objects that include password_hash.
Refactor app/main.py and app/aws.py following the Python backend steering file. Database: PostgreSQL via asyncpg; DynamoDB table name in USERS_TABLE.
Endpoints use an AsyncSession dependency with Annotated, separate UserCreate/UserOut models with response_model, 201 on create and 404 on missing users; boto3 calls are moved to a sync function run with run_in_threadpool; tests override the session dependency.
Kiro, built and operated by AWS, uses steering files: Markdown documents in .kiro/steering/ that give the agent persistent project knowledge. Front matter controls when each file is included: always, when matching files are in context, manually by #name, or automatically by description. Kiro also includes AGENTS.md files.
.kiro/steering/kiro-python-backend.mdStarting point, not a tested configuration for your repository. Included when files matching fileMatchPattern are in context. Review the instructions, adapt the file paths and run your project's existing checks.
---
inclusion: fileMatch
fileMatchPattern: "**/*"
---
Apply these rules to Python backend code using FastAPI.
## FastAPI structure
```python
from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException, status
from pydantic import BaseModel, EmailStr
from sqlalchemy.ext.asyncio import AsyncSession
from app.db import get_session
from app.models import User
app = FastAPI()
SessionDep = Annotated[AsyncSession, Depends(get_session)]
class UserCreate(BaseModel):
email: EmailStr # needs the email-validator package
name: str
class UserOut(BaseModel):
id: str
email: EmailStr
name: str
model_config = {"from_attributes": True}
@app.post("/users", status_code=status.HTTP_201_CREATED, response_model=UserOut)
async def create_user(data: UserCreate, session: SessionDep) -> User:
user = User(**data.model_dump())
session.add(user)
await session.commit()
await session.refresh(user)
return user
@app.get("/users/{user_id}", response_model=UserOut)
async def get_user(user_id: str, session: SessionDep) -> User:
user = await session.get(User, user_id)
if user is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
return user
```
- Use separate input and output models; `response_model` controls which fields leave the API (never return password hashes or internal fields).
- `await` only on async APIs: use `AsyncSession` with an async driver (asyncpg, aiosqlite). With a synchronous `Session`, write the endpoint as plain `def` so FastAPI runs it in a thread pool.
## AWS integration
- boto3 is synchronous. Calling it directly inside `async def` blocks the event loop. Either use plain `def` endpoints/functions for boto3 calls, run them with `anyio.to_thread.run_sync` / `starlette.concurrency.run_in_threadpool`, or use an async client library.
```python
import os
import boto3
from starlette.concurrency import run_in_threadpool
_table = boto3.resource("dynamodb").Table(os.environ["USERS_TABLE"])
def _get_user_item(user_id: str) -> dict | None:
response = _table.get_item(Key={"pk": f"USER#{user_id}", "sk": "PROFILE"})
return response.get("Item")
async def get_user_item(user_id: str) -> dict | None:
return await run_in_threadpool(_get_user_item, user_id)
```
- boto3 resource objects are not thread-safe; if requests run in multiple threads, create resources per thread or use low-level clients.
- Read table names and settings from environment variables or configuration, not literals.
- Give the runtime role least-privilege access (for example `dynamodb:GetItem` on one table).
## Testing
- Test endpoints with `TestClient` (or `httpx.AsyncClient`) and override dependencies (`app.dependency_overrides`) to supply a test session or fake repository.
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
Front matter must be at the very beginning of a steering file to be recognized. Kiro supports AGENTS.md. According to the steering docs, AGENTS.md files do not support inclusion modes and are always included, so keep scoped guidance in .kiro/steering/ files instead.
Documentation checked 2026-11-05: Kiro docs: SteeringKiro home page
Cursor rule for FastAPI projects using Pydantic v2 schemas, SQLAlchemy 2 async_sessionmaker, lifespan cleanup, explicit commits and 409 conflict handling.
Cursor rule for Express 5 APIs in TypeScript with createApp structure, no try/catch boilerplate, Zod 4 validation into res.locals and a safe central error handler.
Cursor rule for Next.js Route Handlers with Zod 4 safeParse validation, auth and ownership checks, awaited params, bounded pagination and one consistent JSON error shape.