py-fast-api — правило для Cursor: что делает и как установить
Правило задаёт стиль для Python-бэкендов на FastAPI: структура маршрутов, валидация через Pydantic и обработка ошибок. Пригодится для новых API и рефакторинга.
.cursor/rules/py-fast-api.mdcЧто делает py-fast-api
Правило направляет Cursor при разработке FastAPI-бэкенда. Оно советует использовать обычные функции для синхронного кода и async def для операций ввода-вывода, добавлять типы во все сигнатуры и описывать входные данные моделями Pydantic. Для маршрутов предлагаются явные схемы ответа, dependency injection и раздельная структура с роутерами, подмаршрутами, утилитами и моделями.
Отдельный блок посвящён ошибкам: проверки ставятся в начале функции, невалидные состояния обрабатываются через guard clauses и ранний возврат, а неожиданные сбои проходят через middleware с логированием. Для запуска и завершения приложения правило советует lifespan-контекст вместо частого применения @app.on_event. В списке зависимостей есть FastAPI, Pydantic v2, асинхронные библиотеки баз данных и SQLAlchemy 2.0 при использовании ORM.
У правила задан шаблон файлов **/*, но alwaysApply: false, поэтому Cursor не подключает его ко всем запросам автоматически. Без асинхронных операций для запросов к базе и внешним API рекомендации по неблокирующему исполнению не будут соблюдаться.
Какие задачи решает
- спроектировать структуру FastAPI-маршрутов
- описать входные и выходные схемы через Pydantic
- разнести синхронные и асинхронные операции
- обработать ошибки через ранние возвраты и middleware
- подготовить API к работе с асинхронной базой
Примеры запросов агенту
- Создай FastAPI-маршрут для управления пользователями с моделями Pydantic и типами ответа.
- Перепиши этот обработчик: вынеси проверки в начало, убери вложенные условия и добавь обработку ошибок.
- Разложи API по роутерам, утилитам и моделям, используя асинхронные вызовы для базы данных.
Как установить py-fast-api
Вручную: положить файлы
.cursor/rules/py-fast-api.mdcВо frontmatter: description, globs, alwaysApply
Вручную: положить файлы
.claude/rules/py-fast-api.mdПоле paths во frontmatter ограничивает файлы: globs из источника → paths
AGENTS.md
Codex читает AGENTS.md: вставьте текст правила туда
Вручную: положить файлы
.github/instructions/py-fast-api.instructions.mdПоле applyTo задаёт, к каким файлам применять: globs из источника → applyTo
Вручную: положить файлы
.devin/rules/py-fast-api.mdВручную: положить файлы
.clinerules/py-fast-api.mdПо шагам, с командами для каждой платформы: Cursor rules: файлы .mdc, четыре режима и замена .cursorrules
Вопросы о py-fast-api
Как установить py-fast-api в Cursor?
Поместите файл правила в .cursor/rules/py-fast-api.mdc.
Что делает py-fast-api?
Правило задаёт соглашения для Python и FastAPI: типизацию, Pydantic-модели, структуру маршрутов, dependency injection, middleware и обработку ошибок.
Какие зависимости учитывает py-fast-api?
В рекомендациях указаны FastAPI, Pydantic v2 и асинхронные библиотеки вроде asyncpg или aiomysql. SQLAlchemy 2.0 применяется при использовании ORM.
Исходный текст
py-fast-api.mdc · CC0-1.0
---
description: "Cursor rules for Python FastAPI backend development and best practices."
globs: **/*
alwaysApply: false
---
You are an expert in Python, FastAPI, and scalable API development.
Key Principles
- Write concise, technical responses with accurate Python examples.
- Use functional, declarative programming; avoid classes where possible.
- Prefer iteration and modularization over code duplication.
- Use descriptive variable names with auxiliary verbs (e.g., is_active, has_permission).
- Use lowercase with underscores for directories and files (e.g., routers/user_routes.py).
- Favor named exports for routes and utility functions.
- Use the Receive an Object, Return an Object (RORO) pattern.
Python/FastAPI
- Use def for pure functions and async def for asynchronous operations.
- Use type hints for all function signatures. Prefer Pydantic models over raw dictionaries for input validation.
- File structure: exported router, sub-routes, utilities, static content, types (models, schemas).
- Avoid unnecessary curly braces in conditional statements.
- For single-line statements in conditionals, omit curly braces.
- Use concise, one-line syntax for simple conditional statements (e.g., if condition: do_something()).
Error Handling and Validation
- Prioritize error handling and edge cases:
- Handle errors and edge cases at the beginning of functions.
- Use early returns for error conditions to avoid deeply nested if statements.
- Place the happy path last in the function for improved readability.
- Avoid unnecessary else statements; use the if-return pattern instead.
- Use guard clauses to handle preconditions and invalid states early.
- Implement proper error logging and user-friendly error messages.
- Use custom error types or error factories for consistent error handling.
Dependencies
- FastAPI
- Pydantic v2
- Async database libraries like asyncpg or aiomysql
- SQLAlchemy 2.0 (if using ORM features)
FastAPI-Specific Guidelines
- Use functional components (plain functions) and Pydantic models for input validation and response schemas.
- Use declarative route definitions with clear return type annotations.
- Use def for synchronous operations and async def for asynchronous ones.
- Minimize @app.on_event("startup") and @app.on_event("shutdown"); prefer lifespan context managers for managing startup and shutdown events.
- Use middleware for logging, error monitoring, and performance optimization.
- Optimize for performance using async functions for I/O-bound tasks, caching strategies, and lazy loading.
- Use HTTPException for expected errors and model them as specific HTTP responses.
- Use middleware for handling unexpected errors, logging, and error monitoring.
- Use Pydantic's BaseModel for consistent input/output validation and response schemas.
Performance Optimization
- Minimize blocking I/O operations; use asynchronous operations for all database calls and external API requests.
- Implement caching for static and frequently accessed data using tools like Redis or in-memory stores.
- Optimize data serialization and deserialization with Pydantic.
- Use lazy loading techniques for large datasets and substantial API responses.
Key Conventions
1. Rely on FastAPI’s dependency injection system for managing state and shared resources.
2. Prioritize API performance metrics (response time, latency, throughput).
3. Limit blocking operations in routes:
- Favor asynchronous and non-blocking flows.
- Use dedicated async functions for database and external API operations.
- Structure routes and dependencies clearly to optimize readability and maintainability.
Refer to FastAPI documentation for Data Models, Path Operations, and Middleware for best practices.
© PatrickJS · CC0-1.0 · PatrickJS/awesome-cursorrules