Token导航 LogoToken导航

Agent Skill · 开发

debug%3afastapi(调试 3afastapi)

用于辅助 Python 项目开发、测试、依赖管理和常见框架工作流。它适合让 Agent 阅读 Python 代码、定位测试问题、整理运行命令、生成脚本或分析数据处理逻辑。使用时需要确认项目虚拟环境、依赖版本和测试入口;涉及执行脚本、读写文件、访问数据库或调用外部 API 时,应先明确运行目录和输入输出范围,避免误改生产数据。

debug%3afastapi 是开发类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为操作浏览器;许可证信息还不明确,暂无第三方扫描结果,按安装量在开发类的 21,746 个 Skill 里排第 16,306。

总安装 514周安装 21GitHub Stars 7下载 165核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:debug%3afastapi(调试 3afastapi)
来源仓库:https://github.com/snakeo/claude-debug-and-refactor-skills-plugin
仓库路径:skills/debug%3Afastapi
安装命令:
npx skills add https://github.com/snakeo/claude-debug-and-refactor-skills-plugin --skill debug:fastapi
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/snakeo/claude-debug-and-refactor-skills-plugin --skill debug:fastapi

这个 Skill 是做什么的

开发类 Skill 面向写代码、改代码和排查问题,一般会读写仓库文件,部分还会执行构建或测试命令。

用于辅助 Python 项目开发、测试、依赖管理和常见框架工作流。它适合让 Agent 阅读 Python 代码、定位测试问题、整理运行命令、生成脚本或分析数据处理逻辑。使用时需要确认项目虚拟环境、依赖版本和测试入口;涉及执行脚本、读写文件或访问数据库时应明确运行目录和输入输出范围。

安装命令为 npx skills add https://github.com/snakeo/claude-debug-and-refactor-skills-plugin --skill debug:fastapi,适用于主流 AI 宿主环境。注意该技能归类为开发类,建议在使用前进一步验证其适用场景和安全边界。

来源仓库内路径:skills/debug%3Afastapi

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/snakeo/claude-debug-and-refactor-skills-plugin…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要操作浏览器,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

debug%3afastapi 怎么安装?

在终端执行 npx skills add https://github.com/snakeo/claude-debug-and-refactor-skills-plugin --skill d…。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

debug%3afastapi 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

debug%3afastapi 需要什么权限?

权限级别是操作浏览器。该 Skill 可能涉及浏览器控制能力,使用时可能读取或操作网页内容,需要在受控环境中确认权限边界。

debug%3afastapi 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

debug%3afastapi 用的人多吗?

公开数据是累计安装 514 次,近一周安装 21 次,下载 165 次,GitHub 7 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

debug%3afastapi 安全吗?

没有查到第三方扫描结果,安全性无法从公开资料判断,安装前请自行审查源码、依赖和命令行为。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。

先想清楚的地方

  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 没有第三方扫描结果,安全性只能靠自己读源码判断。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理开发类任务、又不想每次都手写提示词的人。

不太适合

  • 需要明确授权才能用到公司项目里的场景。
  • 要求有安全扫描结论才肯安装的团队。
  • 需要厂商级技术支持和 SLA 的生产系统。

开发类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
skill-vetter

技能审查员 · OpenClaw

8,779,018986操作浏览器MIT-0通过
ontology

本体论 · OpenClaw

6,636,960576只读MIT-0通过
entra-app-registration

内部应用程序注册 · Codex、Claude

6,631,872764接触敏感数据未明确通过
entra-app-registration

内部应用程序注册 · Codex、Claude

3,757,680201接触敏感数据未明确通过
nano-banana-pro

纳米香蕉专业版 · OpenClaw

3,526,898364接触敏感数据MIT-0有提醒
debug%3afastapi

调试 3afastapi · 本页

5147操作浏览器未明确未收录

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

FastAPI Debugging Guide

Overview

This skill provides a systematic approach to debugging FastAPI applications. FastAPI is built on Starlette and Pydantic, which means debugging often involves understanding async behavior, request validation, and dependency injection patterns.

When to use this skill:

  • 422 Unprocessable Entity errors
  • Pydantic ValidationError exceptions
  • Async/await related issues
  • Dependency injection failures
  • CORS errors in browser
  • 500 Internal Server Errors
  • Database session/connection issues
  • Circular import errors on startup

Common Error Patterns

1. Pydantic ValidationError (422 Unprocessable Entity)

Symptoms:

  • API returns 422 status code
  • Response contains detail array with validation errors
  • Client receives "field required" or "type error" messages

Root Causes:

  • Missing required fields in request body
  • Incorrect data types (string instead of int, etc.)
  • Invalid enum values
  • Nested model validation failures

Debugging Steps:

# 1. Check the exact error response
{
    "detail": [
        {
            "loc": ["body", "field_name"],
            "msg": "field required",
            "type": "value_error.missing"
        }
    ]
}

# 2. Validate your Pydantic model directly
from pydantic import BaseModel, ValidationError

class UserCreate(BaseModel):
    name: str
    email: str
    age: int

try:
    user = UserCreate(**your_data)
except ValidationError as e:
    print(e.json())  # Detailed error info

# 3. Use Optional for non-required fields
from typing import Optional

class UserCreate(BaseModel):
    name: str
    email: str
    age: Optional[int] = None  # Now optional with default

2. 500 Internal Server Error

Symptoms:

  • Generic "Internal Server Error" response
  • No detailed error in API response
  • Error details only in server logs

Root Causes:

  • Unhandled exceptions in endpoint code
  • Database connection failures
  • Dependency injection failures
  • Division by zero, null attribute access
  • External service timeouts

Debugging Steps:

# 1. Add exception logging middleware
import logging
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

app = FastAPI()

@app.middleware("http")
async def log_exceptions(request: Request, call_next):
    try:
        return await call_next(request)
    except Exception as e:
        logger.exception(f"Unhandled exception: {e}")
        raise

# 2. Add global exception handler
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    logger.exception(f"Unhandled: {exc}")
    return JSONResponse(
        status_code=500,
        content={"detail": str(exc)}  # Only in dev!
    )

# 3. Check dependency injection
from fastapi import Depends

def get_db():
    db = SessionLocal()
    try:
        yield db
    except Exception as e:
        logger.error(f"DB error: {e}")
        raise
    finally:
        db.close()

3. Async/Await Issues

Symptoms:

  • RuntimeError: Event loop is already running
  • RuntimeWarning: coroutine was never awaited
  • Blocking behavior in async endpoints
  • TypeError: object X can't be used in 'await' expression

Root Causes:

  • Mixing sync and async code incorrectly
  • Using blocking I/O in async functions
  • Missing await keywords
  • Sync database calls in async context

Debugging Steps:

# 1. Check for missing await
# Wrong
@app.get("/users")
async def get_users():
    users = db.get_users()  # If async, needs await!
    return users

# Correct
@app.get("/users")
async def get_users():
    users = await db.get_users()
    return users

# 2. Don't use blocking I/O in async functions
# Wrong - blocks event loop
@app.get("/data")
async def get_data():
    import time
    time.sleep(5)  # BLOCKS!
    return {"data": "done"}

# Correct - use asyncio.sleep or run_in_executor
import asyncio
@app.get("/data")
async def get_data():
    await asyncio.sleep(5)  # Non-blocking
    return {"data": "done"}

# 3. For sync database operations, use def instead of async def
@app.get("/users")
def get_users(db: Session = Depends(get_db)):
    # FastAPI runs sync functions in threadpool
    return db.query(User).all()

4. Dependency Injection Errors

Symptoms:

  • TypeError: X() takes Y positional arguments but Z were given
  • Dependencies not being called
  • ValidationError from dependency parameters

Debugging Steps:

# 1. Ensure Depends() is used correctly
from fastapi import Depends

# Wrong - function is called immediately
@app.get("/items")
def get_items(db = get_db()):  # WRONG!
    pass

# Correct - FastAPI manages the dependency
@app.get("/items")
def get_items(db = Depends(get_db)):
    pass

# 2. Debug dependency chain
def get_settings():
    print("Loading settings...")  # Debug print
    return Settings()

def get_db(settings: Settings = Depends(get_settings)):
    print(f"Connecting to {settings.db_url}")  # Debug print
    return create_engine(settings.db_url)

# 3. Handle dependency failures gracefully
async def get_current_user(token: str = Depends(oauth2_scheme)):
    try:
        user = await verify_token(token)
        if not user:
            raise HTTPException(status_code=401, detail="Invalid token")
        return user
    except Exception as e:
        logger.error(f"Auth failed: {e}")
        raise HTTPException(status_code=401, detail="Authentication failed")

5. CORS Problems

Symptoms:

  • Browser console shows CORS errors
  • API works in Postman but not browser
  • Preflight OPTIONS requests failing

Debugging Steps:

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

# 1. Add CORS middleware (MUST be before routes)
app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:3000"],  # Or ["*"] for dev
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 2. Debug: Log all requests
@app.middleware("http")
async def log_requests(request, call_next):
    print(f"Origin: {request.headers.get('origin')}")
    print(f"Method: {request.method}")
    response = await call_next(request)
    print(f"CORS headers: {dict(response.headers)}")
    return response

# 3. Common issues:
# - allow_origins must match EXACTLY (including protocol and port)
# - allow_credentials=True requires specific origins (not "*")
# - Check if middleware order is correct

6. Database Session Issues

Symptoms:

  • sqlalchemy.exc.InvalidRequestError: This Session's transaction has been rolled back
  • Database connections exhausted
  • Stale data being returned

Debugging Steps:

from sqlalchemy.orm import Session
from contextlib import contextmanager

# 1. Proper session management
def get_db():
    db = SessionLocal()
    try:
        yield db
        db.commit()  # Commit on success
    except Exception:
        db.rollback()  # Rollback on error
        raise
    finally:
        db.close()  # Always close

# 2. Check connection pool settings
from sqlalchemy import create_engine

engine = create_engine(
    DATABASE_URL,
    pool_size=5,
    max_overflow=10,
    pool_timeout=30,
    pool_pre_ping=True,  # Test connections before use
    echo=True,  # Log all SQL (debug only!)
)

# 3. Debug session state
@app.get("/debug-db")
def debug_db(db: Session = Depends(get_db)):
    print(f"Session active: {db.is_active}")
    print(f"Session dirty: {db.dirty}")
    print(f"Session new: {db.new}")
    return {"status": "ok"}

7. Circular Import Errors

Symptoms:

  • ImportError: cannot import name 'X' from partially initialized module
  • Application fails to start
  • AttributeError: module has no attribute

Debugging Steps:

# 1. Identify the circular dependency
# app/models.py
from app.schemas import UserSchema  # Imports schemas

# app/schemas.py
from app.models import User  # Imports models - CIRCULAR!

# 2. Solution: Use TYPE_CHECKING
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from app.models import User

# 3. Or use string annotations
class UserSchema(BaseModel):
    user: "User"  # Forward reference

# 4. Or restructure: Move shared code to separate module
# app/base.py - Contains shared Base class
# app/models.py - Imports from base
# app/schemas.py - Imports from base

Debugging Tools

1. Python Debugger (pdb/breakpoint)

# Insert breakpoint in your code
@app.get("/debug")
def debug_endpoint():
    data = fetch_data()
    breakpoint()  # Execution stops here
    return process(data)

# Run with: uvicorn main:app --reload
# When breakpoint hits, use pdb commands:
# n - next line
# s - step into
# c - continue
# p variable - print variable
# l - list code around current line
# q - quit debugger

2. Uvicorn with Reload

# Development server with auto-reload
uvicorn main:app --reload --log-level debug

# With specific host/port
uvicorn main:app --reload --host 0.0.0.0 --port 8000

# Show access logs
uvicorn main:app --reload --access-log

3. OpenAPI /docs Endpoint

# FastAPI auto-generates interactive docs
# Access at: http://localhost:8000/docs (Swagger UI)
# Or: http://localhost:8000/redoc (ReDoc)

# Customize docs
app = FastAPI(
    title="My API",
    description="Debug info here",
    docs_url="/docs",  # Or None to disable
    redoc_url="/redoc",
)

# Test endpoints directly in browser!

4. Logging Module

import logging
from fastapi import FastAPI

# Configure logging
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

app = FastAPI()

@app.on_event("startup")
async def startup():
    logger.info("Application starting...")

@app.get("/")
def root():
    logger.debug("Root endpoint called")
    logger.info("Processing request")
    return {"status": "ok"}

5. httpx for Testing

# tests/test_api.py
import pytest
from httpx import AsyncClient, ASGITransport
from main import app

@pytest.mark.asyncio
async def test_endpoint():
    transport = ASGITransport(app=app)
    async with AsyncClient(transport=transport, base_url="http://test") as client:
        response = await client.get("/users")
        assert response.status_code == 200
        print(response.json())  # Debug output

# Sync testing with TestClient
from fastapi.testclient import TestClient

def test_sync():
    client = TestClient(app)
    response = client.get("/users")
    assert response.status_code == 200

6. VS Code Debugging

// .vscode/launch.json
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "FastAPI",
            "type": "debugpy",
            "request": "launch",
            "module": "uvicorn",
            "args": ["main:app", "--reload"],
            "jinja": true,
            "env": {
                "PYTHONPATH": "${workspaceFolder}"
            }
        }
    ]
}

7. Debug Middleware

from starlette.middleware.base import BaseHTTPMiddleware
import time

class DebugMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request, call_next):
        # Log request details
        print(f"Request: {request.method} {request.url}")
        print(f"Headers: {dict(request.headers)}")

        # Time the request
        start = time.time()
        response = await call_next(request)
        duration = time.time() - start

        print(f"Response: {response.status_code} in {duration:.3f}s")
        return response

app.add_middleware(DebugMiddleware)

The Four Phases of FastAPI Debugging

Phase 1: Reproduce and Identify

  1. Reproduce the error consistently # Use curl to reproduce curl -X POST http://localhost:8000/api/users \ -H "Content-Type: application/json" \ -d '{"name": "test"}'
  2. Check the error response # 422 = Validation error (check Pydantic model) # 401/403 = Auth issue (check dependencies) # 500 = Server error (check logs) # 404 = Route not found (check URL and method)
  3. Review server logs # Check uvicorn output uvicorn main:app --log-level debug

Phase 2: Isolate the Problem

  1. Simplify the endpoint @app.post("/api/users") async def create_user(user: UserCreate, db: Session = Depends(get_db)): # Comment out sections to isolate # return {"debug": "step 1"} # Check user data print(f"User data: {user.dict()}") # Check db connection print(f"DB connected: {db.is_active}") return create_user_in_db(db, user)
  2. Test dependencies individually # Test in Python shell from app.dependencies import get_db db = next(get_db()) print(db.execute("SELECT 1").scalar())
  3. Validate request data @app.post("/api/users") async def create_user(request: Request): body = await request.json() print(f"Raw body: {body}") # Try manual validation from app.schemas import UserCreate user = UserCreate(**body) # Will raise if invalid return {"validated": user.dict()}

Phase 3: Fix and Verify

  1. Apply the fix # Before class UserCreate(BaseModel): name: str email: str # After (with proper validation) from pydantic import BaseModel, EmailStr, validator class UserCreate(BaseModel): name: str email: EmailStr @validator('name') def name_not_empty(cls, v): if not v.strip(): raise ValueError('Name cannot be empty') return v
  2. Test the fix # Test valid request curl -X POST http://localhost:8000/api/users \ -H "Content-Type: application/json" \ -d '{"name": "John", "email": "john@example.com"}' # Test edge cases curl -X POST http://localhost:8000/api/users \ -H "Content-Type: application/json" \ -d '{"name": "", "email": "invalid"}'

Phase 4: Prevent Regression

  1. Add tests def test_create_user_valid(): response = client.post("/api/users", json={"name": "John", "email": "john@example.com"}) assert response.status_code == 200 def test_create_user_invalid_email(): response = client.post("/api/users", json={"name": "John", "email": "invalid"}) assert response.status_code == 422
  2. Add error handling from fastapi import HTTPException @app.post("/api/users") async def create_user(user: UserCreate, db: Session = Depends(get_db)): try: return create_user_in_db(db, user) except IntegrityError: raise HTTPException(status_code=409, detail="User already exists") except Exception as e: logger.exception("Failed to create user") raise HTTPException(status_code=500, detail="Internal error")

Quick Reference Commands

Starting and Running

# Development server
uvicorn main:app --reload --log-level debug

# With custom host/port
uvicorn main:app --reload --host 0.0.0.0 --port 8000

# Production (multiple workers)
uvicorn main:app --workers 4

# With gunicorn
gunicorn main:app -w 4 -k uvicorn.workers.UvicornWorker

Testing Endpoints

# GET request
curl http://localhost:8000/api/users

# POST with JSON
curl -X POST http://localhost:8000/api/users \
  -H "Content-Type: application/json" \
  -d '{"name": "test", "email": "test@example.com"}'

# With authentication
curl -H "Authorization: Bearer TOKEN" \
  http://localhost:8000/api/protected

# Verbose output for debugging
curl -v http://localhost:8000/api/users

Python Debugging

# Insert breakpoint
breakpoint()

# Or use pdb directly
import pdb; pdb.set_trace()

# Quick debug print
print(f"DEBUG: {variable=}")  # Python 3.8+ f-string debugging

# Log at debug level
import logging
logging.debug(f"Variable value: {variable}")

Database Debugging

# Enable SQLAlchemy echo
engine = create_engine(DATABASE_URL, echo=True)

# Check session state
print(f"Session: dirty={db.dirty}, new={db.new}, deleted={db.deleted}")

# Raw SQL for debugging
result = db.execute("SELECT * FROM users WHERE id = :id", {"id": 1})
print(result.fetchall())

Async Debugging

# Check if running in async context
import asyncio
try:
    loop = asyncio.get_running_loop()
    print(f"Running in event loop: {loop}")
except RuntimeError:
    print("No event loop running")

# Debug coroutines
import asyncio
asyncio.run(your_async_function())

Environment and Configuration

# Check Python environment
python -c "import fastapi; print(fastapi.__version__)"
python -c "import pydantic; print(pydantic.__version__)"

# List installed packages
pip list | grep -E "(fastapi|pydantic|uvicorn|starlette)"

# Check environment variables
python -c "import os; print(os.environ.get('DATABASE_URL'))"

Additional Resources

平台分布

Codex

36.57%
按下载量换算60

Claude

29.41%
按下载量换算49

Cursor

19.8%
按下载量换算33

Gemini CLI

9.4%
按下载量换算16

安全审计

暂无安全审计结果可展示。

权限和风险

操作浏览器

该 Skill 可能涉及浏览器控制能力,使用时可能读取或操作网页内容,需要在受控环境中确认权限边界。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills