Antigravity workspace rule for FastAPI services with Pydantic v2 schemas, per-request SQLAlchemy 2 async sessions, explicit transactions and 409 handling.
.agents/rules/antigravity-python-backend.md. Downloaded files need to be placed in that repository path.---
trigger: glob
globs: "**/*"
---
# Python Backend with FastAPI and SQLAlchemy
Applies to: FastAPI services that use Pydantic v2 for request and response models and SQLAlchemy 2.x (asyncio) for persistence.
Version baseline: checked against FastAPI 0.116, Pydantic 2.11, SQLAlchemy 2.0/2.1 and Python 3.11+. Read `pyproject.toml` (or `requirements*.txt`) first. If the project is on Pydantic v1 or SQLAlchemy 1.4, follow the installed APIs and say so.
## Before editing
- Read the app factory or `main.py`, the existing session dependency, one router and its models. Reuse the project's session dependency, error format and settings object.
- List the files you will change (router, schemas, ORM model, migration, tests). Ask before adding a dependency or creating an Alembic migration.
## Request and response models
- Keep separate Pydantic models for input (`UserCreate`), partial updates (`UserUpdate`) and output (`UserRead`). Never return ORM objects without a response model, because that can leak columns such as password hashes.
- Use Pydantic v2 APIs: `model_config = ConfigDict(from_attributes=True)`, `model_dump()` and `model_validate()`. Do not use `class Config`, `orm_mode` or `.dict()`.
- Use `EmailStr` for email fields. It needs the `email-validator` extra (`pydantic[email]`).
## Sessions and transactions
- Create one engine per process and an `async_sessionmaker(engine, expire_on_commit=False)`. Yield one `AsyncSession` per request from a dependency. Never share a session between concurrent tasks.
- Make the transaction boundary explicit. Use `async with session.begin():` around the writes that must succeed or fail together, and keep slow network calls outside it.
- Turn constraint violations (`IntegrityError`) into a 409 or 400 response. Don't let them become 500s, and don't use a check-then-insert race as the only uniqueness guard.
```python
from typing import Annotated, AsyncIterator
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel, ConfigDict, EmailStr, Field
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from app.config import settings
from app.models import User # SQLAlchemy 2.0 mapped class with a unique email column
engine = create_async_engine(settings.database_url)
SessionLocal = async_sessionmaker(engine, expire_on_commit=False)
async def get_session() -> AsyncIterator[AsyncSession]:
async with SessionLocal() as session:
yield session
SessionDep = Annotated[AsyncSession, Depends(get_session)]
class UserCreate(BaseModel):
email: EmailStr
name: str = Field(min_length=1, max_length=100)
class UserRead(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
email: str
name: str
router = APIRouter(prefix="/users", tags=["users"])
@router.post("", response_model=UserRead, status_code=status.HTTP_201_CREATED)
async def create_user(data: UserCreate, session: SessionDep) -> User:
"""Create a user. Returns 409 when the email is already registered."""
user = User(**data.model_dump())
try:
async with session.begin():
session.add(user)
except IntegrityError:
raise HTTPException(status.HTTP_409_CONFLICT, "Email already registered") from None
return user
```
## Errors
- Raise `HTTPException` for expected client errors. Register exception handlers for domain exceptions so routers stay thin, and keep one error body shape across the API.
- Never use a bare `except:` or `except Exception` to turn every failure into the same status code.
## Startup and shutdown
- Use the `lifespan` parameter of `FastAPI(...)` for startup and shutdown work such as `await engine.dispose()`. `@app.on_event` is deprecated, and FastAPI ignores it when `lifespan` is set.
## Type hints and docs
- Type every function signature. Give public endpoints a docstring or `summary=`, because both feed the OpenAPI description.
## Tests
- Test endpoints with `fastapi.testclient.TestClient` (or `httpx.AsyncClient` with `ASGITransport`), and override `get_session` with a test session or fake via `app.dependency_overrides`.
- Cover 201, 409 (duplicate), 422 (invalid body) and the response shape, including that no private columns are returned.
## Verify before finishing
Run when available in the project:
- `pytest` (async tests need `pytest-asyncio` or `anyio`)
- `ruff check .` and `mypy` or `pyright` if configured
- `alembic upgrade head` against a disposable local database only, when a migration was added
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.
Antigravity
backend
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
An Antigravity agent adds a create-user endpoint to a FastAPI service that already has an async SQLAlchemy engine and a users table with a unique email column.
Add POST /users accepting email and name (1-100 chars). Duplicate emails must return 409, invalid bodies 422, success 201 with id, email and name only. app/models.py has User(id, email unique, name, password_hash).
Illustrative; not a recorded model run. A file plan, then UserCreate/UserRead models with model_config = ConfigDict(from_attributes=True), a route using an Annotated session dependency, `async with session.begin()` around the insert, IntegrityError mapped to 409, response_model hiding password_hash, a TestClient test overriding get_session that asserts 201/409/422 and the response keys, and the pytest/ruff results.
Google describes Antigravity as its agentic development platform. Antigravity reads workspace rules from AGENTS.md or GEMINI.md and from Markdown files in .agents/rules/, with a trigger front matter field that sets when a rule is active. Global rules live under ~/.gemini/.
.agents/rules/antigravity-python-backend.mdStarting point, not a tested configuration for your repository. Active when files matching globs are involved (trigger: glob). Review the instructions, adapt the file paths and run your project's existing checks.
---
trigger: glob
globs: "**/*"
---
# Python Backend with FastAPI and SQLAlchemy
Applies to: FastAPI services that use Pydantic v2 for request and response models and SQLAlchemy 2.x (asyncio) for persistence.
Version baseline: checked against FastAPI 0.116, Pydantic 2.11, SQLAlchemy 2.0/2.1 and Python 3.11+. Read `pyproject.toml` (or `requirements*.txt`) first. If the project is on Pydantic v1 or SQLAlchemy 1.4, follow the installed APIs and say so.
## Before editing
- Read the app factory or `main.py`, the existing session dependency, one router and its models. Reuse the project's session dependency, error format and settings object.
- List the files you will change (router, schemas, ORM model, migration, tests). Ask before adding a dependency or creating an Alembic migration.
## Request and response models
- Keep separate Pydantic models for input (`UserCreate`), partial updates (`UserUpdate`) and output (`UserRead`). Never return ORM objects without a response model, because that can leak columns such as password hashes.
- Use Pydantic v2 APIs: `model_config = ConfigDict(from_attributes=True)`, `model_dump()` and `model_validate()`. Do not use `class Config`, `orm_mode` or `.dict()`.
- Use `EmailStr` for email fields. It needs the `email-validator` extra (`pydantic[email]`).
## Sessions and transactions
- Create one engine per process and an `async_sessionmaker(engine, expire_on_commit=False)`. Yield one `AsyncSession` per request from a dependency. Never share a session between concurrent tasks.
- Make the transaction boundary explicit. Use `async with session.begin():` around the writes that must succeed or fail together, and keep slow network calls outside it.
- Turn constraint violations (`IntegrityError`) into a 409 or 400 response. Don't let them become 500s, and don't use a check-then-insert race as the only uniqueness guard.
```python
from typing import Annotated, AsyncIterator
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel, ConfigDict, EmailStr, Field
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from app.config import settings
from app.models import User # SQLAlchemy 2.0 mapped class with a unique email column
engine = create_async_engine(settings.database_url)
SessionLocal = async_sessionmaker(engine, expire_on_commit=False)
async def get_session() -> AsyncIterator[AsyncSession]:
async with SessionLocal() as session:
yield session
SessionDep = Annotated[AsyncSession, Depends(get_session)]
class UserCreate(BaseModel):
email: EmailStr
name: str = Field(min_length=1, max_length=100)
class UserRead(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
email: str
name: str
router = APIRouter(prefix="/users", tags=["users"])
@router.post("", response_model=UserRead, status_code=status.HTTP_201_CREATED)
async def create_user(data: UserCreate, session: SessionDep) -> User:
"""Create a user. Returns 409 when the email is already registered."""
user = User(**data.model_dump())
try:
async with session.begin():
session.add(user)
except IntegrityError:
raise HTTPException(status.HTTP_409_CONFLICT, "Email already registered") from None
return user
```
## Errors
- Raise `HTTPException` for expected client errors. Register exception handlers for domain exceptions so routers stay thin, and keep one error body shape across the API.
- Never use a bare `except:` or `except Exception` to turn every failure into the same status code.
## Startup and shutdown
- Use the `lifespan` parameter of `FastAPI(...)` for startup and shutdown work such as `await engine.dispose()`. `@app.on_event` is deprecated, and FastAPI ignores it when `lifespan` is set.
## Type hints and docs
- Type every function signature. Give public endpoints a docstring or `summary=`, because both feed the OpenAPI description.
## Tests
- Test endpoints with `fastapi.testclient.TestClient` (or `httpx.AsyncClient` with `ASGITransport`), and override `get_session` with a test session or fake via `app.dependency_overrides`.
- Cover 201, 409 (duplicate), 422 (invalid body) and the response shape, including that no private columns are returned.
## Verify before finishing
Run when available in the project:
- `pytest` (async tests need `pytest-asyncio` or `anyio`)
- `ruff check .` and `mypy` or `pyright` if configured
- `alembic upgrade head` against a disposable local database only, when a migration was added
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.
Antigravity truncates any single rule file over 24,000 bytes, and global plus always_on rules share a 20,000-token budget, according to the docs. AGENTS.md (or GEMINI.md) in a workspace directory is one of the documented rule locations, and ~/.gemini/AGENTS.md works globally. Use .agents/rules/ when a rule should only apply in some situations.
Documentation checked 2026-11-05: Google Antigravity docs: RulesGoogle Antigravity 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.