Instruction file imported from soring/copilot-agents (
.github/instructions/python.instructions.md). Copyright stays with the author.
Python Coding Standards
Framework: FastAPI
- Use
APIRouterfor route grouping — never attach routes directly toapp - Define request/response models with Pydantic v2
BaseModel - Use
Annotated[T, Depends(...)]for dependency injection - Return typed response models; never return raw dicts
- Set
status_codeon route decorators; useResponsefor custom headers - Add OpenAPI metadata:
summary,description,tags,response_model
ORM: SQLAlchemy 2.0
- Use 2.0-style
select()statements — never the legacyQueryAPI - Define models with
DeclarativeBaseandMapped[T]type annotations - Use
AsyncSessionfor all database operations - Relationships must have explicit
back_populates - Use
server_defaultfor database-level defaults;defaultfor Python-level - Always use
session.scalars()orsession.execute()— neversession.query()
Error Handling
- Raise
HTTPExceptionwith appropriate status codes anddetailmessages - Register custom exception handlers for domain errors in
app/core/exceptions.py - Never expose stack traces, internal paths, or raw SQL errors in responses
- Use structured error response schema:
{"detail": str, "code": str, "field": str | null}
Async Patterns
- All I/O operations must be
async— database, HTTP, file system - Use
asyncio.gather()for concurrent independent operations - Never use
time.sleep()— useasyncio.sleep()if needed - Background tasks via FastAPI
BackgroundTasksor Celery for heavy work
Imports & Style
- Use absolute imports from the project root
- Group: stdlib → third-party → local, separated by blank lines
- Use
from __future__ import annotationsfor forward references - Follow PEP 8; max line length 99 characters
- Use f-strings for string formatting; never
%or.format()
Project Structure
backend/
├── app/
│ ├── api/ # Route handlers (thin controllers)
│ │ └── v1/ # Versioned API routes
│ ├── core/ # Config, security, dependencies, exceptions
│ ├── models/ # SQLAlchemy ORM models
│ ├── schemas/ # Pydantic request/response schemas
│ ├── services/ # Business logic layer
│ ├── repositories/ # Data access layer (DB queries)
│ └── main.py # FastAPI app factory
├── alembic/ # Database migrations
├── tests/
│ ├── api/ # API integration tests
│ ├── services/ # Service unit tests
│ └── conftest.py # Shared fixtures
└── pyproject.toml
Type Hints
- All function signatures must have complete type annotations
- Use
T | NoneoverOptional[T](Python 3.10+ union syntax) - Use
collections.abctypes:Sequence,Mapping,Iterableover concrete types - Generic return types for repositories:
T | Nonefor single,list[T]for many