Audit and, when explicitly agreed, incrementally improve existing FastAPI code. Identify risks with contextual evidence, preserve the project's established architecture and tooling, and propose safe migration steps. Use when a user asks to review, improve, refactor, restructure, clean up, or compare existing backend code with a reference.
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Fastapi Code Upgrade?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/amralhorimy-fastapi-code-upgrade)
---
name: fastapi-code-upgrade
description: Audit and, when explicitly agreed, incrementally improve existing FastAPI code. Identify risks with contextual evidence, preserve the project's established architecture and tooling, and propose safe migration steps. Use when a user asks to review, improve, refactor, restructure, clean up, or compare existing backend code with a reference.
---
# Code Upgrade: audit and improve safely
Never rewrite blindly: **map -> audit -> report -> agree scope -> make small verified changes -> re-audit.** Preserve working behavior and the project's existing conventions unless a change is agreed.
## Process
1. **Map**: inspect the tree, entrypoints, modules, infrastructure, run/test commands, dependencies, and available tools before judging or changing anything. Identify the existing architecture and select a fit:
- **Profile A**: an established or explicitly adopted domain/application/adapters (hexagonal) structure, with suitable architecture checks where available.
- **Profile B**: a simpler established route/service/repository structure, or another coherent project-specific layout. Keep its conventions rather than imposing Profile A.
- For mixed, legacy, or nonstandard layouts, describe what exists and tailor recommendations; do not force a profile or a wholesale move.
2. **Audit** using `references/audit-checklist.md` and, where relevant, `references/layering-check.md`. Treat grep, AST, lint, and architecture-tool results as **leads**, not confirmed defects: inspect surrounding code, call sites, configuration, runtime behavior, and project conventions before drawing a conclusion. Adapt paths and commands to the actual tree and installed tools; do not install or impose tooling automatically. State checks not run and why.
3. **Report** findings with file:line evidence and context, severity, confidence/limitations, production cost, what is already good, and proportionate next steps. Redact secrets, credentials, tokens, personal data, and sensitive values from command output, logs, diffs, and reports; never reproduce a discovered secret.
4. **Plan** only agreed changes. Include a migration map when moving code is in scope, but do not move or rebuild unused code automatically: record why it is unused and ask whether it should be removed, retained, or revisited. Agree the target profile and phase scope before structural changes; defer the rest to a phase plan (`fastapi-phase-planning`).
5. **Refactor** in small, independently reviewable steps. For each step, run the relevant available tests/checks, inspect and present the diff, and report outcomes. Do not create commits automatically. Commit only when the user explicitly requests and authorizes the commit; otherwise leave changes uncommitted and offer the diff and test results for review. Never combine a refactor with a behavior change without explicitly identifying and agreeing to that behavior change.
6. **Verify** with the stage report format (`fastapi-testing-verification`) when available; otherwise report concrete commands and results, then re-audit. Compare findings before/after only where the same checks and scope make that comparison meaningful.
7. **Data safety**: before any schema/data migration, backfill, destructive operation, or index change with operational impact, plan the migration and recovery path: backup/snapshot and verification, staging or dry-run where feasible, ordering and compatibility, monitoring, rollback or forward-recovery steps, and ownership/approval. Do not run a risky data operation without an appropriate plan and explicit authorization.
8. **Behavior changes** must be listed explicitly for the client team (e.g. error shape, 409 vs 400, 422, time-zone-aware dates, removed endpoints). Keep legacy fields temporarily only with a documented rationale and removal condition.
## Severity
- **Critical**: evidenced privilege escalation, injection, exposed secrets in a public repository, data loss, or unauthenticated expensive/admin endpoints.
- **High**: evidenced missing object-level authorization, race conditions on uniqueness/counters/status, blocking calls on the loop, absent timeouts, unbounded queries, or data leaks through views/projections.
- **Medium**: confirmed layering violations, swallowed errors, inconsistent error shape, unbounded inputs, or missing tests on core rules.
- **Low**: naming, style, docs, or genuinely unused code. Confirm usage and impact before classifying code as dead.
A pattern match alone is not evidence sufficient to assign a severity. Explain the context and confidence, and distinguish a confirmed defect from a question or potential risk.
## Defect patterns to investigate (not assume)
Examples seen in FastAPI projects include client-controlled roles, archived records still readable, incorrect `await` use, secrets in logs, unsafe upload keys, empty slugs, response-model mismatches, projection leaks, lost updates, exception text exposed to clients, debug endpoints leaking headers, uniqueness races, fragile in-memory queues, naive datetimes, and shutdown/attempt limits not enforced. Verify the relevant path and impact in this project before reporting any of them as findings.
## Smell -> possible fix (choose in project context)
| Pattern to investigate | Possible direction, if confirmed and appropriate |
|---|---|
| Logic + queries in route functions | Keep routes thin; place rules in the project's existing service/use-case/domain convention |
| `HTTPException` raised from services/repos | Map application/domain errors at the HTTP boundary when that matches the architecture |
| Raw dicts from DB / returning storage documents | Consider mappers and response DTOs where they improve boundaries |
| Clients created globally at import | Consider lifespan/composition-root ownership if lifecycle or testability requires it |
| Business code importing drivers | Consider consumer-owned ports and adapters if the project uses or needs those boundaries |
| Modules importing each other | Examine dependency direction; use a port, event, or bridge only when warranted |
| `except Exception: pass`, `print()` | Confirm behavior and logging policy; handle/report errors appropriately |
| Check-then-insert; read-modify-write counters | Confirm concurrency risk; consider unique constraints or atomic updates and a safe migration plan |
| Missing indexes, unbounded lists, offset paging | Inspect real query paths, cardinality, workload, and query plans; add indexes or bounded/cursor paging only when justified |
| Blocking calls in `async def` | Confirm call behavior; consider async clients, thread offload, or workers as appropriate |
| Work inside a request that must not be lost | Assess delivery guarantees and operational needs before introducing a durable queue |
| Scattered `os.getenv`, default secrets | Consider typed settings and production validation consistent with current deployment |
| No tests / tests need the network | Add focused fakes or integration tests that match project conventions |
| Docs absent or stale | Update the project's existing operational and architecture documentation |
Do not rebuild unused code or create performance indexes automatically. Treat indexes as workload- and database-specific changes; assess their write/storage costs, correctness role, deployment method, and recovery path first.
## Guided review of the user's own code
Name what is genuinely good (specifically), then explain confirmed gaps and potential risks with their evidence, context, confidence, and production cost. Offer the smallest suitable improvement for this codebase rather than treating a reference architecture as mandatory. Compare against a reference only on the requested scope and distinguish preferences from defects.
## Audit report template
```
# Audit: <project> - <date>
Summary: overall assessment, biggest evidenced risk, biggest strength (3 lines)
Findings: id | area | finding/question | evidence file:line + context | confidence | severity | fix | effort
Already good: ...
Quick wins (< 1 day): ...
Migration map + agreed phases (if applicable): ...
Data migration/recovery plan (if applicable): ...
Behavior changes for clients: ...
Checks run / not run and limitations: ...
Not reviewed: ...
```