SuperAPI AI Directory

fastapi-fullstack

Coding & development

View repository

Updated 10-15 21:33

About this skill

Fastapi Full-Stack Development Guide

Overview

This skill provides complete full-stack development guidance for Fastapi projects (based on FastAPI + SQLAlchemy asynchronous mode), including the complete workflow from API design to database implementation, code pattern references, and troubleshooting.

Core Capabilities

1. API Endpoint Development

Create new RESTful API endpoints, including:

  • Route definition and registration
  • Request body validation (Pydantic models)
  • Response model design
  • Repository dependency injection
  • Error handling

Trigger scenarios: "Add user management API", "Create order query interface", "Implement statistics data API"

2. Database Model Design

Create and modify data models using SQLAlchemy 2.0 asynchronous ORM:

  • Table structure definition
  • Field types and constraints
  • One-to-many and many-to-many relationships
  • Database migration

Trigger scenarios: "Add a new database model", "Add a field to the user table", "Implement a many-to-many relationship between users and roles"

3. Repository Pattern

Use generic Repository for database operations:

  • Basic CRUD operations
  • Complex queries and filtering
  • Transaction management
  • Relationship query optimization

Trigger scenarios: "Implement user query functionality", "Optimize database query performance", "Handle complex business logic queries"

4. Test Writing

Write and maintain asynchronous tests:

  • API tests
  • Repository tests
  • Database test fixtures
  • Integration tests

Trigger scenarios: "Write tests for new features", "Fix failing tests"

5. Frontend Integration

Configure frontend and backend integration, including:

  • Static file mounting
  • CORS configuration
  • API proxy settings
  • Frontend-backend separated deployment

Trigger scenarios: "Configure frontend static files", "Resolve cross-origin issues", "Deploy frontend build artifacts"

6. Troubleshooting

Diagnose and resolve common issues:

  • Database connection and query errors
  • API endpoint issues
  • Asynchronous programming errors
  • Performance issues

Trigger scenarios: "API returns 500 error", "Database queries are slow", "Tests cannot connect to the database"

Development Workflow

Scenario 1: Add a New Feature Module

Step 1: Understand Requirements

  1. Clarify functional requirements and data structures
  2. Identify the required API endpoints
  3. Determine database tables and relationships

Step 2: Create Database Models

Reference:architecture.md

  1. In <project>/database/models.py define the new ORM model
  2. Use orm.Mapped Define fields
  3. Add necessary comments (in Chinese)
  4. If there are relationships, define association relationships

Template:assets/templates/model_template.py

Step 3: Create Pydantic models

In <project>/api/models.py add:

  • Response model (<Model>)
  • Create request body (Create<Model>Payload)
  • Update request body (Update<Model>Payload)

Template:assets/templates/pydantic_template.py

Reference:conventions.md

Step 4: Create API routes

  1. Create a new file <project>/api/v1/<module>.py
  2. Define routes and endpoints
  3. Use Repository dependency injection
  4. Implement business logic

Template:assets/templates/endpoint_template.py

Reference:patterns.md

Step 5: Register routes

In <project>/api/v1/routes.py import and register the new routes:

from <project>.api.v1 import <module>
router.include_router(<module>.router)

Step 6: Write tests

Create tests/test_<module>.py, write test cases.

Template:assets/templates/test_template.py

Reference:conventions.md

Step 7: Verify

Run tests and code checks:

pytest tests/test_<module>.py -v
ruff check .
ruff format .

Scenario 2: Add a single API endpoint

Quick steps

  1. Check existing models - Confirm the database model already exists
  2. Add Pydantic models - In api/models.py add request/response models
  3. Add endpoint - Add a new endpoint function in the corresponding route file
  4. Testing - Use /api/docs for manual testing or write unit tests

Scenario 3: Modify existing functionality

Modify the database model

  1. Add/modify <project>/database/models.py fields in
  2. If it is a production environment, data migration needs to be considered
  3. Update the related Pydantic models
  4. Update API endpoints (if needed)
  5. Update tests

Modify API endpoints

  1. Modify the endpoint logic in the route file
  2. Update Pydantic models (if the interface changes)
  3. Update related tests
  4. Verify functionality

Quick reference

Common code patterns

See:patterns.md

  • Create API endpoints - Route definitions, dependency injection, response format
  • Repository queries - CRUD operations, complex queries, relationship queries
  • Password encryption - Use bcrypt for encryption and verification
  • Pagination queries - Implement paginated lists
  • Frontend integration - Static file mounting, CORS configuration, API proxy

Code standards

See:conventions.md

  • Naming conventions - Naming of classes, functions, variables, and database tables
  • Type annotations - Use modern type annotation syntax
  • Asynchronous programming - Correctly use async/await
  • Error handling - Business errors vs system exceptions
  • Testing conventions - Test file naming, asynchronous testing

Project architecture

See:architecture.md

  • Tech stack - FastAPI, SQLAlchemy, MySQL, etc.
  • Project structure - Directory organization and file responsibilities
  • Core Components - Application entry, database session, Repository, dependency injection
  • Data Flow - Complete flow from request to response

Troubleshooting

Common Issues

See:troubleshooting.md

Index by category:

  • Database Issues - Connection errors, table does not exist, transaction timeout
  • API Issues - 400 errors, 404 errors, 500 errors
  • Async Issues - RuntimeWarning, event loop errors
  • Dependency Injection - Repository injection failure
  • Performance Issues - Slow queries, high memory usage
  • Testing Issues - Test database connection failure
  • Deployment Issues - Docker container, environment variables

Debugging Tips

  • Enable verbose logging - View detailed error information
  • Use API documentation - Access /api/docs to test endpoints
  • Database query logging - Print all SQL queries
  • Exception tracing - Use traceback to view the full stack

Using Resources

Template Files (assets/templates/)

The following template files can be copied and used directly; remember to replace the placeholders:

  • app_template.py - FastAPI application entry template, including static file mounting and CORS configuration
  • endpoint_template.py - API route template, including complete CRUD operations
  • model_template.py - SQLAlchemy ORM model template
  • pydantic_template.py - Pydantic request/response model template
  • test_template.py - pytest test template, including common test cases

Reference Documents (references/)

Load into context as needed:

  • architecture.md - Project architecture description, including tech stack, project structure, core components
  • patterns.md - Common code patterns, including actual code examples
  • conventions.md - Code standards and conventions, ensuring code consistency
  • troubleshooting.md - Troubleshooting guide, solving common issues

When to Load Reference Documents

  • Before starting new feature development: load architecture.md and conventions.md
  • When implementing specific features: load patterns.md to view code patterns
  • When encountering issues: load troubleshooting.md to find solutions

Best Practices

1. Incremental Development

  • Implement basic functionality first, then optimize and refine
  • Run tests to verify after completing each step
  • Keep code runnable, avoid long periods of "work-in-progress" state

2. Use Templates

  • Refer to template files when developing new features
  • Templates already include the project's best practices
  • Maintain a consistent style when replacing placeholders

3. Follow Standards

  • Write code strictly according to code standards
  • Use the project's agreed naming and structure
  • Add necessary Chinese comments

4. Testing First

  • Write tests alongside feature development
  • Use tests to verify functionality correctness
  • Prioritize fixing when tests fail

5. Security First

  • Passwords must be encrypted using bcrypt
  • Sensitive information is read from environment variables
  • Input validation uses Pydantic models
  • Avoid directly concatenating SQL

Checklist

After completing the feature, ensure that:

  • Database models are correctly defined and inherit Base
  • All fields have Chinese comments
  • Pydantic models have enabled from_attributes=True
  • API endpoints correctly use async/await
  • Repository dependency injection is correctly configured
  • Error handling complies with the specification (business errors use CommonResponse, system errors use HTTP exceptions)
  • Test cases cover the core functionality
  • Code passes ruff check check
  • Code has been formatted using ruff format formatted
  • Routes are registered in routes.py registered in
  • Static file mounting is correctly configured (if the frontend is involved)
  • CORS configuration meets the requirements of the development and production environments
  • Frontend API request paths correctly use the /api prefix

Common Commands

# 启动开发服务器
uvicorn <project>.app:app --reload

# 运行所有测试
pytest -v

# 运行特定测试
pytest tests/test_<module>.py -v

# 代码风格检查
ruff check .

# 代码格式化
ruff format .

# 类型检查
pyright

# 查看 API 文档
# 访问 http://localhost:8000/api/docs

Note: All code and comments should use Chinese, unless the project has an explicit English convention.