Skip to content

Python FastAPI Best Practices .cursorrules prompt file

Author: Caio Barbieri

What you can build

Scalable API Development Platform: Build a cloud-based platform that simplifies the development of scalable APIs using Python and FastAPI. It should include templates and modules for setting up API routes, input validation with Pydantic, middleware for error handling, and performance monitoring.Async Data Processing Library: Create a Python library focused on asynchronous data processing tasks, leveraging FastAPI's async capabilities. The library would include utilities for handling asynchronous database operations, integration with async libraries like asyncpg, and caching mechanisms.API Performance Analyzer: Develop a tool that analyzes FastAPI applications for performance bottlenecks. It should focus on response time, latency, and throughput metrics, providing recommendations for optimizing asynchronous flows and reducing blocking operations.Pydantic Validation Toolkit: Offer a toolkit that enhances Pydantic validation features, providing advanced error handling and logging capabilities. This toolkit could include plugins for custom error types and validation schemas for complex data structures.FastAPI Middleware Extensions: Create a set of middleware extensions for FastAPI, focusing on logging, error monitoring, and performance optimization. These would include tools for managing startup/shutdown events, HTTP error responses, and performance metrics.API Error Handling Framework: Design a framework that standardizes error handling in FastAPI applications. This framework should offer consistent error messages, logging strategies, and error monitoring, utilizing custom error types and factories.Lazy Data Loading Service: Build a service that facilitates lazy loading of large datasets in FastAPI applications. This could include APIs and utilities for managing paginated responses and on-demand data fetching strategies.Database Interaction ORM: Develop a lightweight ORM optimized for asynchronous database interactions in FastAPI using SQLAlchemy 2.0, focusing on reducing blocking operations and caching frequently accessed data.Declarative Route Builder: Provide a tool for building FastAPI routes using a declarative syntax that emphasizes type safety, clear return type annotations, and modular components. This could streamline route definitions and enhance maintainability.API Caching System: Implement a caching system tailored for FastAPI APIs, using tools like Redis or in-memory stores to efficiently manage cacheable responses and static content, improving performance and reducing latency.

Benefits

Synopsis

Developers creating scalable APIs with FastAPI will benefit from this prompt to design performant, modular, and maintainable services using Python and modern asynchronous techniques.

Overview of .cursorrules prompt

The .cursorrules file outlines best practices and guidelines for Python and FastAPI development, emphasizing scalable API solutions. It covers principles like functional and declarative programming, error handling, and performance optimization. It recommends concise and accurate Python examples, type hints, Pydantic models for validation, and asynchronous operations. Developers are encouraged to use FastAPI's dependency injection and middleware for improved performance and maintainability, with specific focus on managing startup and shutdown processes efficiently and employing caching strategies. The file prioritizes readability, modularization, and error logging, along with leveraging FastAPI-specific features like Pydantic models for consistency.

.cursorrules Content

json
You are an expert in Python, FastAPI, and scalable API development.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.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()).Prioritize error handling and edge cases:FastAPIPydantic v2Async database libraries like asyncpg or aiomysqlSQLAlchemy 2.0 (if using ORM features)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.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.Refer to FastAPI documentation for Data Models, Path Operations, and Middleware for best practices.

Released under the MIT License.