@umacloud/knowledge 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/00-governance/governance-capabilities.md +557 -0
- package/00-governance/knowledge-map.md +39 -0
- package/00-governance/maintenance-policy.md +76 -0
- package/00-governance/review-checklist.md +81 -0
- package/README.md +13 -0
- package/ai/01-standards/agent-development-complete.md +691 -0
- package/ai/01-standards/llm-application-complete.md +488 -0
- package/ai/01-standards/mlops-complete.md +798 -0
- package/ai/01-standards/prompt-engineering-complete.md +646 -0
- package/ai/01-standards/rag-architecture-complete.md +649 -0
- package/ai/02-playbooks/llm-evaluation-playbook.md +847 -0
- package/ai/03-checklists/ai-project-checklist.md +215 -0
- package/ai/04-antipatterns/ai-antipatterns.md +661 -0
- package/ai/05-cases/case-rag-production.md +147 -0
- package/ai/06-glossary/ai-glossary.md +162 -0
- package/ai/agent-evaluation-benchmark.md +53 -0
- package/ai/ai-agent-memory-context-management.md +41 -0
- package/ai/ai-cost-capacity-optimization-playbook.md +42 -0
- package/ai/ai-data-security-and-compliance-playbook.md +37 -0
- package/ai/ai-domain-index-and-checklist.md +40 -0
- package/ai/ai-governance-maturity-model.md +50 -0
- package/ai/ai-model-selection-and-routing-strategy.md +47 -0
- package/ai/ai-observability-and-oncall-runbook.md +52 -0
- package/ai/ai-rag-engineering-playbook.md +42 -0
- package/ai/ai-red-team-and-safety-evaluation.md +42 -0
- package/ai/ai-release-readiness-and-rollback-gate.md +42 -0
- package/ai/llm-agent-engineering-deep-dive.md +57 -0
- package/ai/prompt-and-tool-guardrails.md +52 -0
- package/api/01-standards/enterprise-api-standards.md +198 -0
- package/api/01-standards/rest-api-design-guide.md +63 -0
- package/api/02-playbooks/api-pagination-playbook.md +93 -0
- package/api/02-playbooks/graphql-production-playbook.md +176 -0
- package/api/03-checklists/api-review-checklist.md +55 -0
- package/api/04-antipatterns/api-antipatterns.md +112 -0
- package/architecture/01-standards/api-gateway-patterns.md +496 -0
- package/architecture/01-standards/cloud-native-patterns.md +644 -0
- package/architecture/01-standards/distributed-systems-patterns.md +591 -0
- package/architecture/01-standards/event-driven-architecture.md +595 -0
- package/architecture/01-standards/microservices-patterns-complete.md +968 -0
- package/architecture/01-standards/microservices-patterns.md +495 -0
- package/architecture/01-standards/system-design-interview.md +664 -0
- package/architecture/02-playbooks/microservices-patterns-playbook.md +137 -0
- package/architecture/02-playbooks/migration-playbook.md +780 -0
- package/architecture/02-playbooks/system-design-playbook.md +779 -0
- package/architecture/03-checklists/architecture-decision-checklist.md +297 -0
- package/architecture/04-antipatterns/architecture-antipatterns.md +417 -0
- package/architecture/05-cases/case-netflix-microservices.md +413 -0
- package/architecture/06-glossary/architecture-glossary.md +164 -0
- package/architecture/adr-template-and-examples.md +38 -0
- package/architecture/api-gateway-deep-dive.md +1291 -0
- package/architecture/configuration-management.md +1162 -0
- package/architecture/distributed-transactions.md +1220 -0
- package/architecture/microservices-complete.md +735 -0
- package/architecture/resilience-and-disaster-patterns.md +37 -0
- package/architecture/service-governance.md +1198 -0
- package/architecture/system-architecture-deep-dive.md +37 -0
- package/backend/01-standards/analytics-and-growth.md +65 -0
- package/backend/01-standards/api-and-error-conventions.md +120 -0
- package/backend/01-standards/application-layering-and-packaging.md +160 -0
- package/backend/01-standards/auth-implementation.md +104 -0
- package/backend/01-standards/backend-framework-idioms.md +74 -0
- package/backend/01-standards/background-jobs-and-async.md +66 -0
- package/backend/01-standards/caching-strategies-complete.md +390 -0
- package/backend/01-standards/config-and-observability.md +77 -0
- package/backend/01-standards/data-modeling-and-persistence.md +94 -0
- package/backend/01-standards/django-complete.md +1765 -0
- package/backend/01-standards/email-and-notifications.md +64 -0
- package/backend/01-standards/fastapi-complete.md +925 -0
- package/backend/01-standards/file-upload-and-storage.md +66 -0
- package/backend/01-standards/graphql-api-complete.md +416 -0
- package/backend/01-standards/llm-application-standard.md +78 -0
- package/backend/01-standards/message-queue-patterns.md +379 -0
- package/backend/01-standards/microservices-and-distributed.md +78 -0
- package/backend/01-standards/nestjs-complete.md +2167 -0
- package/backend/01-standards/payment-integration.md +80 -0
- package/backend/01-standards/rate-limiting-complete.md +451 -0
- package/backend/01-standards/realtime-and-websocket.md +65 -0
- package/backend/01-standards/search-and-filtering.md +64 -0
- package/backend/01-standards/spring-boot-complete.md +445 -0
- package/backend/02-playbooks/api-design-playbook.md +718 -0
- package/backend/02-playbooks/email-send-playbook.md +130 -0
- package/backend/02-playbooks/file-upload-s3-playbook.md +153 -0
- package/backend/02-playbooks/typescript-enterprise-playbook.md +133 -0
- package/backend/02-playbooks/websocket-realtime-playbook.md +154 -0
- package/backend/03-checklists/api-launch-checklist.md +189 -0
- package/backend/04-antipatterns/backend-antipatterns.md +1051 -0
- package/blockchain/01-standards/blockchain-basics.md +557 -0
- package/blockchain/01-standards/smart-contract-development.md +1315 -0
- package/cicd/01-standards/deployment-and-delivery-standard.md +96 -0
- package/cicd/01-standards/github-actions-complete.md +473 -0
- package/cicd/01-standards/release-and-store-submission.md +75 -0
- package/cicd/02-playbooks/cicd-pipeline-playbook.md +144 -0
- package/cicd/02-playbooks/release-management-playbook.md +605 -0
- package/cicd/03-checklists/pipeline-security-checklist.md +168 -0
- package/cicd/04-antipatterns/cicd-antipatterns.md +589 -0
- package/cicd/05-cases/case-deployment-automation.md +221 -0
- package/cicd/05-cases/case-gitops-transformation.md +212 -0
- package/cicd/06-glossary/cicd-glossary.md +114 -0
- package/cicd/cicd-blueprint-deep-dive.md +38 -0
- package/cicd/release-readiness-gate.md +37 -0
- package/cloud-native/01-standards/container-security.md +741 -0
- package/cloud-native/01-standards/kubernetes-complete.md +812 -0
- package/cloud-native/02-playbooks/api-gateway-playbook.md +155 -0
- package/cloud-native/02-playbooks/gitops-with-argocd.md +760 -0
- package/cloud-native/02-playbooks/k8s-troubleshooting-playbook.md +1942 -0
- package/cloud-native/02-playbooks/message-queue-playbook.md +129 -0
- package/cloud-native/02-playbooks/multicloud-governance.md +726 -0
- package/cloud-native/02-playbooks/serverless-patterns.md +788 -0
- package/cloud-native/02-playbooks/service-mesh-playbook.md +612 -0
- package/cloud-native/02-playbooks/terraform-iac-playbook.md +143 -0
- package/cloud-native/03-checklists/container-security-checklist.md +431 -0
- package/cloud-native/03-checklists/k8s-production-readiness-checklist.md +460 -0
- package/cloud-native/04-antipatterns/container-antipatterns.md +660 -0
- package/cloud-native/04-antipatterns/k8s-antipatterns.md +743 -0
- package/cloud-native/05-cases/case-k8s-migration.md +478 -0
- package/cloud-native/05-cases/case-k8s-scaling.md +642 -0
- package/cloud-native/05-cases/case-k8s-security-incident.md +397 -0
- package/cloud-native/06-glossary/cloud-native-glossary.md +337 -0
- package/cross-platform/01-standards/cross-platform-frameworks.md +83 -0
- package/cross-platform/01-standards/platform-selection-and-architecture.md +77 -0
- package/data/01-standards/elasticsearch-complete.md +2098 -0
- package/data/01-standards/postgresql-complete.md +1613 -0
- package/data/01-standards/redis-complete.md +1527 -0
- package/data/02-playbooks/database-optimization-playbook.md +403 -0
- package/data/02-playbooks/elasticsearch-production-playbook.md +132 -0
- package/data/03-checklists/database-launch-checklist.md +187 -0
- package/data/04-antipatterns/database-antipatterns.md +873 -0
- package/data/05-cases/case-database-migration.md +310 -0
- package/data/06-glossary/database-glossary.md +440 -0
- package/data/data-governance-and-modeling-deep-dive.md +39 -0
- package/data-engineering/01-standards/airflow-complete.md +523 -0
- package/data-engineering/01-standards/kafka-complete.md +1521 -0
- package/data-engineering/02-playbooks/spark-etl-playbook.md +496 -0
- package/data-engineering/03-checklists/pipeline-launch-checklist.md +194 -0
- package/data-engineering/04-antipatterns/data-pipeline-antipatterns.md +684 -0
- package/data-engineering/05-cases/case-real-time-pipeline.md +355 -0
- package/data-engineering/06-glossary/data-engineering-glossary.md +429 -0
- package/database/01-standards/database-schema-standards.md +147 -0
- package/database/02-playbooks/postgresql-optimization-quick.md +52 -0
- package/database/02-playbooks/postgresql-performance-optimization.md +58 -0
- package/database/02-playbooks/postgresql-production-playbook.md +146 -0
- package/database/02-playbooks/redis-caching-playbook.md +117 -0
- package/database/03-checklists/database-review-checklist.md +50 -0
- package/database/04-antipatterns/database-antipatterns.md +112 -0
- package/design/01-standards/ui-design-system-complete.md +423 -0
- package/design/02-playbooks/design-handoff-playbook.md +254 -0
- package/design/02-playbooks/design-review-playbook.md +388 -0
- package/design/03-checklists/design-review-checklist.md +246 -0
- package/design/04-antipatterns/design-antipatterns.md +378 -0
- package/design/05-cases/case-design-system-adoption.md +328 -0
- package/design/06-glossary/design-glossary.md +329 -0
- package/design/ui-full-lifecycle-cross-platform-playbook.md +571 -0
- package/design/ux-system-deep-dive.md +38 -0
- package/design-systems/00-craft-rules.md +71 -0
- package/design-systems/aesthetic-families.md +43 -0
- package/design-systems/anti-ai-slop.md +162 -0
- package/design-systems/bold-geometric.md +120 -0
- package/design-systems/brutalist-bold.md +103 -0
- package/design-systems/editorial-clean.md +109 -0
- package/design-systems/glass-aurora.md +108 -0
- package/design-systems/modern-minimal.md +145 -0
- package/design-systems/premium-luxury.md +106 -0
- package/design-systems/product-type-design-map.md +48 -0
- package/design-systems/soft-warm.md +123 -0
- package/design-systems/tech-utility.md +113 -0
- package/desktop/01-standards/desktop-app-standard.md +72 -0
- package/desktop/01-standards/desktop-design.md +71 -0
- package/development/00-governance/document-template.md +41 -0
- package/development/01-standards/api-versioning-strategies.md +432 -0
- package/development/01-standards/authentication-patterns-complete.md +479 -0
- package/development/01-standards/css-architecture-complete.md +550 -0
- package/development/01-standards/database-migration-strategies.md +484 -0
- package/development/01-standards/elasticsearch-complete.md +347 -0
- package/development/01-standards/git-complete.md +371 -0
- package/development/01-standards/golang-complete.md +1565 -0
- package/development/01-standards/graphql-complete.md +298 -0
- package/development/01-standards/javascript-bundlers-complete.md +469 -0
- package/development/01-standards/javascript-typescript-complete.md +528 -0
- package/development/01-standards/jest-complete.md +275 -0
- package/development/01-standards/linux-complete.md +234 -0
- package/development/01-standards/logging-observability-complete.md +526 -0
- package/development/01-standards/microservices-communication.md +502 -0
- package/development/01-standards/mongodb-complete.md +406 -0
- package/development/01-standards/oauth2-complete.md +285 -0
- package/development/01-standards/performance-optimization-complete.md +289 -0
- package/development/01-standards/playwright-complete.md +247 -0
- package/development/01-standards/postgresql-complete.md +456 -0
- package/development/01-standards/pytest-complete.md +340 -0
- package/development/01-standards/python-async-programming.md +902 -0
- package/development/01-standards/python-complete.md +956 -0
- package/development/01-standards/python-decorators-complete.md +799 -0
- package/development/01-standards/python-design-patterns.md +2854 -0
- package/development/01-standards/python-packaging-distribution.md +420 -0
- package/development/01-standards/python-testing-strategies.md +607 -0
- package/development/01-standards/python-web-frameworks-comparison.md +471 -0
- package/development/01-standards/redis-complete.md +317 -0
- package/development/01-standards/rest-api-complete.md +316 -0
- package/development/01-standards/rust-complete.md +578 -0
- package/development/01-standards/typescript-advanced-types.md +1513 -0
- package/development/01-standards/web-security-complete.md +292 -0
- package/development/02-playbooks/api-design-playbook.md +810 -0
- package/development/02-playbooks/database-migration-playbook.md +580 -0
- package/development/02-playbooks/debugging-playbook.md +692 -0
- package/development/02-playbooks/feature-delivery-playbook.md +430 -0
- package/development/02-playbooks/incident-hotfix-playbook.md +387 -0
- package/development/02-playbooks/performance-optimization-playbook.md +531 -0
- package/development/02-playbooks/performance-tuning-playbook.md +652 -0
- package/development/02-playbooks/refactor-playbook.md +403 -0
- package/development/02-playbooks/release-playbook.md +469 -0
- package/development/03-checklists/architecture-review-checklist.md +168 -0
- package/development/03-checklists/data-migration-checklist.md +157 -0
- package/development/03-checklists/oncall-handover-checklist.md +173 -0
- package/development/03-checklists/pr-checklist.md +158 -0
- package/development/03-checklists/production-readiness-checklist.md +190 -0
- package/development/03-checklists/release-readiness-checklist.md +154 -0
- package/development/03-checklists/security-review-checklist.md +182 -0
- package/development/04-antipatterns/api-antipatterns.md +657 -0
- package/development/04-antipatterns/architecture-antipatterns.md +686 -0
- package/development/04-antipatterns/backend-antipatterns.md +648 -0
- package/development/04-antipatterns/cicd-antipatterns.md +540 -0
- package/development/04-antipatterns/code-smell-antipatterns.md +571 -0
- package/development/04-antipatterns/data-antipatterns.md +658 -0
- package/development/04-antipatterns/database-antipatterns.md +578 -0
- package/development/04-antipatterns/frontend-antipatterns.md +635 -0
- package/development/04-antipatterns/reliability-antipatterns.md +700 -0
- package/development/04-antipatterns/security-antipatterns.md +747 -0
- package/development/05-cases/case-api-version-migration.md +428 -0
- package/development/05-cases/case-authorization-hardening.md +383 -0
- package/development/05-cases/case-bluegreen-rollback.md +466 -0
- package/development/05-cases/case-cache-snowball-protection.md +485 -0
- package/development/05-cases/case-ci-cd-pipeline.md +544 -0
- package/development/05-cases/case-database-scaling.md +500 -0
- package/development/05-cases/case-db-hotspot-optimization.md +487 -0
- package/development/05-cases/case-incident-mttr-reduction.md +563 -0
- package/development/05-cases/case-microservice-migration.md +375 -0
- package/development/05-cases/case-performance-optimization.md +406 -0
- package/development/05-cases/case-security-incident-response.md +345 -0
- package/development/06-glossary/full-stack-glossary.md +166 -0
- package/development/09-maturity/quarterly-audit-template.md +35 -0
- package/development/11-ui-excellence/ui-aesthetic-system.md +41 -0
- package/development/11-ui-excellence/ui-engineering-excellence.md +435 -0
- package/development/12-scenarios/development-scenarios-guide.md +565 -0
- package/development/13-implementation-assets/implementation-toolkit.md +282 -0
- package/development/13-implementation-assets/knowledge-gates-execution.md +43 -0
- package/development/14-full-lifecycle/software-lifecycle-gates.md +511 -0
- package/development/15-lifecycle-templates/project-templates-collection.md +791 -0
- package/development/api-contract-and-versioning-guide.md +36 -0
- package/development/api-governance-complete.md +43 -0
- package/development/backend-engineering-complete.md +43 -0
- package/development/code-review-quality-complete.md +43 -0
- package/development/concurrency-reliability-complete.md +43 -0
- package/development/database-engineering-complete.md +43 -0
- package/development/engineering-effectiveness-complete.md +43 -0
- package/development/engineering-standards-deep-dive.md +38 -0
- package/development/frontend-engineering-complete.md +43 -0
- package/development/performance-capacity-complete.md +43 -0
- package/development/refactor-migration-complete.md +42 -0
- package/development/refactoring-and-techdebt-playbook.md +37 -0
- package/development/security-in-development-complete.md +43 -0
- package/devops/01-standards/cicd-pipeline-complete.md +262 -0
- package/devops/01-standards/docker-complete.md +1490 -0
- package/devops/01-standards/github-actions-complete.md +337 -0
- package/devops/01-standards/kubernetes-complete.md +638 -0
- package/devops/01-standards/terraform-complete.md +2117 -0
- package/devops/02-playbooks/docker-compose-playbook.md +233 -0
- package/devops/02-playbooks/docker-k8s-production-playbook.md +186 -0
- package/devops/02-playbooks/docker-production-playbook.md +952 -0
- package/edge-iot/01-standards/edge-iot-complete.md +473 -0
- package/experts/architect/api-design.md +178 -0
- package/experts/architect/methodology.md +124 -0
- package/experts/architect/security.md +75 -0
- package/experts/backend-lead/methodology.md +216 -0
- package/experts/devops/methodology.md +160 -0
- package/experts/frontend-lead/methodology.md +178 -0
- package/experts/product-manager/industry/ecommerce.md +43 -0
- package/experts/product-manager/industry/saas.md +40 -0
- package/experts/product-manager/methodology.md +97 -0
- package/experts/qa-lead/methodology.md +123 -0
- package/experts/qa-lead/test-strategy.md +128 -0
- package/experts/uiux-designer/methodology.md +125 -0
- package/frontend/01-standards/accessibility-complete.md +532 -0
- package/frontend/01-standards/accessibility-standard.md +74 -0
- package/frontend/01-standards/admin-dashboard-and-crud.md +72 -0
- package/frontend/01-standards/design-tokens-complete.md +444 -0
- package/frontend/01-standards/forms-and-validation.md +77 -0
- package/frontend/01-standards/frontend-architecture-and-layering.md +119 -0
- package/frontend/01-standards/i18n-and-localization.md +65 -0
- package/frontend/01-standards/nextjs-complete.md +451 -0
- package/frontend/01-standards/react-complete.md +713 -0
- package/frontend/01-standards/react-hooks-complete-guide.md +1100 -0
- package/frontend/01-standards/react-hooks-complete.md +1171 -0
- package/frontend/01-standards/seo-and-web-vitals.md +77 -0
- package/frontend/01-standards/state-management-complete.md +444 -0
- package/frontend/01-standards/vue-complete.md +499 -0
- package/frontend/01-standards/vue3-complete.md +2002 -0
- package/frontend/01-standards/web-framework-best-practices.md +64 -0
- package/frontend/01-standards/web-performance-complete.md +495 -0
- package/frontend/02-playbooks/accessibility-a11y-playbook.md +161 -0
- package/frontend/02-playbooks/frontend-performance-playbook.md +707 -0
- package/frontend/02-playbooks/i18n-internationalization-playbook.md +120 -0
- package/frontend/02-playbooks/performance-optimization-playbook.md +163 -0
- package/frontend/02-playbooks/react-nextjs-production-playbook.md +167 -0
- package/frontend/02-playbooks/react-state-management-playbook.md +173 -0
- package/frontend/03-checklists/component-quality-checklist.md +166 -0
- package/frontend/03-checklists/frontend-launch-checklist.md +299 -0
- package/frontend/04-antipatterns/frontend-antipatterns.md +886 -0
- package/frontend/05-cases/case-performance-optimization.md +274 -0
- package/harmony/01-standards/harmonyos-arkts-standard.md +75 -0
- package/harmony/01-standards/harmonyos-design.md +65 -0
- package/high-quality-engineering-playbook.md +54 -0
- package/incident/01-standards/incident-response-complete.md +303 -0
- package/incident/02-playbooks/chaos-engineering-playbook.md +883 -0
- package/incident/02-playbooks/postmortem-playbook.md +398 -0
- package/incident/03-checklists/incident-readiness-checklist.md +181 -0
- package/incident/04-antipatterns/incident-antipatterns.md +490 -0
- package/incident/05-cases/case-cascade-failure.md +176 -0
- package/incident/06-glossary/incident-glossary.md +114 -0
- package/incident/postmortem-and-response-deep-dive.md +39 -0
- package/industries/ecommerce/ecommerce-complete.md +631 -0
- package/industries/education/education-complete.md +555 -0
- package/industries/fintech/fintech-complete.md +501 -0
- package/industries/gaming/gaming-complete.md +587 -0
- package/industries/healthcare/healthcare-complete.md +452 -0
- package/low-code/01-standards/low-code-complete.md +944 -0
- package/miniprogram/01-standards/ai-common-mistakes.md +61 -0
- package/miniprogram/01-standards/miniprogram-custom-navbar-capsule.md +77 -0
- package/miniprogram/01-standards/miniprogram-design.md +61 -0
- package/miniprogram/01-standards/miniprogram-standard.md +81 -0
- package/mobile/01-standards/android-material-design.md +70 -0
- package/mobile/01-standards/flutter-complete.md +384 -0
- package/mobile/01-standards/ios-design-hig.md +78 -0
- package/mobile/01-standards/mobile-app-standard.md +85 -0
- package/mobile/01-standards/react-native-complete.md +352 -0
- package/mobile/02-playbooks/mobile-cross-platform-playbook.md +175 -0
- package/mobile/02-playbooks/mobile-performance.md +473 -0
- package/mobile/03-checklists/mobile-release-checklist.md +234 -0
- package/mobile/04-antipatterns/mobile-antipatterns.md +798 -0
- package/mobile/05-cases/case-app-performance.md +500 -0
- package/mobile/05-cases/case-app-startup-optimization.md +218 -0
- package/mobile/06-glossary/mobile-glossary.md +484 -0
- package/observability/01-standards/observability-standards.md +103 -0
- package/observability/02-playbooks/prometheus-grafana-playbook.md +135 -0
- package/observability/02-playbooks/structured-logging-playbook.md +73 -0
- package/observability/03-checklists/observability-checklist.md +54 -0
- package/observability/04-antipatterns/observability-antipatterns.md +106 -0
- package/operations/01-standards/prometheus-monitoring-complete.md +1578 -0
- package/operations/02-playbooks/capacity-planning-playbook.md +620 -0
- package/operations/03-checklists/production-launch-checklist.md +365 -0
- package/operations/04-antipatterns/operations-antipatterns.md +664 -0
- package/operations/05-cases/case-sre-practices.md +581 -0
- package/operations/06-glossary/operations-glossary.md +120 -0
- package/operations/aiops-anomaly-detection.md +758 -0
- package/operations/capacity-planning.md +1061 -0
- package/operations/chaos-engineering.md +659 -0
- package/operations/incident-command-system.md +38 -0
- package/operations/observability-complete.md +442 -0
- package/operations/slo-sli-playbook.md +517 -0
- package/operations/sre-operations-deep-dive.md +39 -0
- package/package.json +8 -0
- package/performance/01-standards/performance-and-scalability.md +80 -0
- package/performance/01-standards/performance-standards.md +156 -0
- package/performance/02-playbooks/query-optimization-playbook.md +103 -0
- package/performance/03-checklists/performance-checklist.md +56 -0
- package/performance/04-antipatterns/performance-antipatterns.md +146 -0
- package/product/01-standards/product-management-complete.md +285 -0
- package/product/02-playbooks/feature-launch-playbook.md +207 -0
- package/product/02-playbooks/user-research-playbook.md +532 -0
- package/product/03-checklists/feature-launch-checklist.md +275 -0
- package/product/04-antipatterns/product-antipatterns.md +355 -0
- package/product/05-cases/case-mvp-to-scale.md +384 -0
- package/product/06-glossary/product-glossary.md +462 -0
- package/product/feature-prioritization-framework.md +40 -0
- package/product/kpi-and-metric-tree.md +37 -0
- package/product/product-discovery-and-prd-deep-dive.md +41 -0
- package/quantum/01-standards/quantum-complete.md +1186 -0
- package/security/01-standards/api-security-complete.md +511 -0
- package/security/01-standards/container-runtime-security.md +574 -0
- package/security/01-standards/data-protection-gdpr.md +543 -0
- package/security/01-standards/owasp-top10-complete.md +1890 -0
- package/security/01-standards/secure-coding-baseline.md +90 -0
- package/security/01-standards/supply-chain-security.md +441 -0
- package/security/01-standards/web-security-checklist.md +108 -0
- package/security/01-standards/zero-trust-architecture.md +521 -0
- package/security/02-playbooks/auth-sso-playbook.md +166 -0
- package/security/02-playbooks/incident-response-security-playbook.md +588 -0
- package/security/02-playbooks/owasp-api-security-playbook.md +129 -0
- package/security/02-playbooks/payment-integration-playbook.md +119 -0
- package/security/02-playbooks/penetration-testing-playbook.md +517 -0
- package/security/03-checklists/security-audit-checklist.md +356 -0
- package/security/04-antipatterns/security-coding-antipatterns.md +580 -0
- package/security/05-cases/case-log4shell-incident.md +537 -0
- package/security/05-cases/case-major-breaches.md +468 -0
- package/security/06-glossary/security-glossary.md +212 -0
- package/security/compliance-automation.md +993 -0
- package/security/container-security.md +680 -0
- package/security/devsecops-complete.md +426 -0
- package/security/sast-dast-sca.md +775 -0
- package/security/secrets-management.md +594 -0
- package/security/security-architecture-deep-dive.md +37 -0
- package/security/threat-modeling-stride-playbook.md +40 -0
- package/seed-templates/auth-system.md +59 -0
- package/seed-templates/blog-content.md +94 -0
- package/seed-templates/dashboard.md +89 -0
- package/seed-templates/docs-site.md +73 -0
- package/seed-templates/e-commerce.md +50 -0
- package/seed-templates/saas-landing.md +92 -0
- package/seed-templates/settings-page.md +51 -0
- package/testing/01-standards/test-strategy-and-layering.md +83 -0
- package/testing/01-standards/testing-strategy-complete.md +422 -0
- package/testing/01-standards/unit-testing-best-practices.md +118 -0
- package/testing/02-playbooks/e2e-testing-playbook.md +988 -0
- package/testing/02-playbooks/testing-strategy-playbook.md +126 -0
- package/testing/03-checklists/test-strategy-checklist.md +208 -0
- package/testing/04-antipatterns/testing-antipatterns.md +718 -0
- package/testing/05-cases/case-testing-transformation.md +300 -0
- package/testing/06-glossary/testing-glossary.md +110 -0
- package/testing/risk-based-test-matrix.md +36 -0
- package/testing/testing-strategy-deep-dive.md +37 -0
|
@@ -0,0 +1,810 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: api-design-playbook
|
|
3
|
+
title: REST API 设计作战手册 (API Design Playbook)
|
|
4
|
+
domain: development
|
|
5
|
+
category: 02-playbooks
|
|
6
|
+
difficulty: intermediate
|
|
7
|
+
tags: [agent, api, checklist, design, development, playbook, 前置条件, 回滚方案]
|
|
8
|
+
quality_score: 70
|
|
9
|
+
last_updated: 2026-06-15
|
|
10
|
+
---
|
|
11
|
+
# REST API 设计作战手册 (API Design Playbook)
|
|
12
|
+
|
|
13
|
+
## 概述
|
|
14
|
+
|
|
15
|
+
本手册定义了 REST API 设计的完整最佳实践,涵盖 URL 设计、版本控制、请求/响应格式、错误处理、分页过滤、认证授权、限流保护和文档自动化。目标是构建一致、可预测、易于使用且可长期演进的 API。
|
|
16
|
+
|
|
17
|
+
## 前置条件
|
|
18
|
+
|
|
19
|
+
### 必须满足
|
|
20
|
+
|
|
21
|
+
- [ ] 已明确 API 的目标用户(内部/合作方/公开)
|
|
22
|
+
- [ ] 已定义核心资源模型和关系
|
|
23
|
+
- [ ] 已确定认证授权方案
|
|
24
|
+
- [ ] 已确定 API 版本策略
|
|
25
|
+
- [ ] 有 API 设计评审流程
|
|
26
|
+
|
|
27
|
+
### 建议满足
|
|
28
|
+
|
|
29
|
+
- [ ] 有 API 设计规范文档(本手册可作为基础)
|
|
30
|
+
- [ ] 有 OpenAPI/Swagger 工具链
|
|
31
|
+
- [ ] 有 API 网关(用于限流、认证、监控)
|
|
32
|
+
|
|
33
|
+
---
|
|
34
|
+
|
|
35
|
+
## 步骤一:URL 设计
|
|
36
|
+
|
|
37
|
+
### 1.1 资源命名规则
|
|
38
|
+
|
|
39
|
+
```
|
|
40
|
+
规则 1: 使用名词复数形式表示资源集合
|
|
41
|
+
/api/v1/users ✓
|
|
42
|
+
/api/v1/getUsers ✗ (动词)
|
|
43
|
+
/api/v1/user ✗ (单数)
|
|
44
|
+
|
|
45
|
+
规则 2: 使用路径表达资源层级关系
|
|
46
|
+
/api/v1/users/123/orders ✓ (用户的订单)
|
|
47
|
+
/api/v1/users/123/orders/456 ✓ (具体订单)
|
|
48
|
+
/api/v1/getUserOrders?userId=123 ✗ (RPC 风格)
|
|
49
|
+
|
|
50
|
+
规则 3: 层级不超过 3 层,过深用查询参数
|
|
51
|
+
/api/v1/users/123/orders/456/items ✓ (3 层)
|
|
52
|
+
/api/v1/users/123/orders/456/items/789/reviews ✗ (太深)
|
|
53
|
+
/api/v1/order-items/789/reviews ✓ (扁平化)
|
|
54
|
+
|
|
55
|
+
规则 4: 使用 kebab-case
|
|
56
|
+
/api/v1/order-items ✓
|
|
57
|
+
/api/v1/orderItems ✗ (camelCase)
|
|
58
|
+
/api/v1/order_items ✗ (snake_case)
|
|
59
|
+
|
|
60
|
+
规则 5: 非 CRUD 操作使用动词子资源
|
|
61
|
+
POST /api/v1/orders/123/cancel ✓ (取消订单)
|
|
62
|
+
POST /api/v1/orders/123/refund ✓ (退款)
|
|
63
|
+
POST /api/v1/users/123/activate ✓ (激活用户)
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
### 1.2 HTTP 方法语义
|
|
67
|
+
|
|
68
|
+
```
|
|
69
|
+
GET /resources 获取资源列表(安全、幂等)
|
|
70
|
+
GET /resources/:id 获取单个资源(安全、幂等)
|
|
71
|
+
POST /resources 创建资源(非幂等)
|
|
72
|
+
PUT /resources/:id 全量更新资源(幂等)
|
|
73
|
+
PATCH /resources/:id 部分更新资源(幂等)
|
|
74
|
+
DELETE /resources/:id 删除资源(幂等)
|
|
75
|
+
|
|
76
|
+
HEAD /resources/:id 获取资源元信息(安全、幂等)
|
|
77
|
+
OPTIONS /resources 获取支持的方法(安全、幂等)
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
### 1.3 HTTP 状态码规范
|
|
81
|
+
|
|
82
|
+
```
|
|
83
|
+
2xx 成功
|
|
84
|
+
200 OK GET/PUT/PATCH/DELETE 成功
|
|
85
|
+
201 Created POST 创建成功(响应中包含 Location 头)
|
|
86
|
+
202 Accepted 异步操作已接受
|
|
87
|
+
204 No Content DELETE 成功(无响应体)
|
|
88
|
+
|
|
89
|
+
3xx 重定向
|
|
90
|
+
301 Moved Permanently 永久重定向(API 版本废弃)
|
|
91
|
+
304 Not Modified 条件请求命中缓存
|
|
92
|
+
|
|
93
|
+
4xx 客户端错误
|
|
94
|
+
400 Bad Request 请求参数非法
|
|
95
|
+
401 Unauthorized 未认证
|
|
96
|
+
403 Forbidden 已认证但无权限
|
|
97
|
+
404 Not Found 资源不存在
|
|
98
|
+
405 Method Not Allowed HTTP 方法不支持
|
|
99
|
+
409 Conflict 资源冲突(重复创建、乐观锁冲突)
|
|
100
|
+
415 Unsupported Media Type Content-Type 不支持
|
|
101
|
+
422 Unprocessable Entity 参数格式正确但语义错误
|
|
102
|
+
429 Too Many Requests 限流
|
|
103
|
+
|
|
104
|
+
5xx 服务端错误
|
|
105
|
+
500 Internal Server Error 未处理的服务端异常
|
|
106
|
+
502 Bad Gateway 上游服务异常
|
|
107
|
+
503 Service Unavailable 服务暂时不可用
|
|
108
|
+
504 Gateway Timeout 上游服务超时
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
---
|
|
112
|
+
|
|
113
|
+
## 步骤二:版本控制
|
|
114
|
+
|
|
115
|
+
### 2.1 版本策略对比
|
|
116
|
+
|
|
117
|
+
| 策略 | 示例 | 优点 | 缺点 |
|
|
118
|
+
|------|------|------|------|
|
|
119
|
+
| URL 路径 | `/api/v1/users` | 直观、缓存友好 | URL 变长 |
|
|
120
|
+
| 请求头 | `Accept: application/vnd.api.v1+json` | URL 干净 | 不直观、调试困难 |
|
|
121
|
+
| 查询参数 | `/api/users?version=1` | 简单 | 缓存不友好 |
|
|
122
|
+
|
|
123
|
+
**推荐:URL 路径版本**,理由:最直观、CDN/缓存友好、易于文档化。
|
|
124
|
+
|
|
125
|
+
### 2.2 版本演进策略
|
|
126
|
+
|
|
127
|
+
```python
|
|
128
|
+
# FastAPI 多版本路由示例
|
|
129
|
+
from fastapi import FastAPI, APIRouter
|
|
130
|
+
|
|
131
|
+
app = FastAPI()
|
|
132
|
+
|
|
133
|
+
# V1 路由
|
|
134
|
+
v1_router = APIRouter(prefix="/api/v1")
|
|
135
|
+
|
|
136
|
+
@v1_router.get("/users/{user_id}")
|
|
137
|
+
async def get_user_v1(user_id: int):
|
|
138
|
+
"""V1: 返回基础用户信息"""
|
|
139
|
+
return {"id": user_id, "name": "...", "email": "..."}
|
|
140
|
+
|
|
141
|
+
# V2 路由 - 向后兼容的增强
|
|
142
|
+
v2_router = APIRouter(prefix="/api/v2")
|
|
143
|
+
|
|
144
|
+
@v2_router.get("/users/{user_id}")
|
|
145
|
+
async def get_user_v2(user_id: int):
|
|
146
|
+
"""V2: 增加 profile 嵌套对象"""
|
|
147
|
+
return {
|
|
148
|
+
"id": user_id,
|
|
149
|
+
"name": "...",
|
|
150
|
+
"email": "...",
|
|
151
|
+
"profile": {"avatar": "...", "bio": "..."}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
app.include_router(v1_router)
|
|
155
|
+
app.include_router(v2_router)
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
### 2.3 版本废弃流程
|
|
159
|
+
|
|
160
|
+
```
|
|
161
|
+
1. 宣布废弃:在响应头中添加 Deprecation 和 Sunset 头
|
|
162
|
+
Deprecation: true
|
|
163
|
+
Sunset: Sat, 01 Jun 2025 00:00:00 GMT
|
|
164
|
+
Link: <https://api.example.com/api/v2/users>; rel="successor-version"
|
|
165
|
+
|
|
166
|
+
2. 发送通知:提前 6 个月通知 API 消费方
|
|
167
|
+
|
|
168
|
+
3. 监控使用量:追踪旧版本 API 的调用量
|
|
169
|
+
|
|
170
|
+
4. 关闭旧版本:到期后返回 410 Gone
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
---
|
|
174
|
+
|
|
175
|
+
## 步骤三:请求与响应格式
|
|
176
|
+
|
|
177
|
+
### 3.1 请求格式
|
|
178
|
+
|
|
179
|
+
```python
|
|
180
|
+
from pydantic import BaseModel, Field, validator
|
|
181
|
+
from typing import Optional
|
|
182
|
+
from enum import Enum
|
|
183
|
+
|
|
184
|
+
class OrderStatus(str, Enum):
|
|
185
|
+
DRAFT = "draft"
|
|
186
|
+
CONFIRMED = "confirmed"
|
|
187
|
+
SHIPPED = "shipped"
|
|
188
|
+
|
|
189
|
+
class CreateOrderRequest(BaseModel):
|
|
190
|
+
"""创建订单请求"""
|
|
191
|
+
product_id: int = Field(..., gt=0, description="商品 ID")
|
|
192
|
+
quantity: int = Field(..., ge=1, le=999, description="数量")
|
|
193
|
+
shipping_address: str = Field(
|
|
194
|
+
..., min_length=5, max_length=500, description="收货地址"
|
|
195
|
+
)
|
|
196
|
+
note: Optional[str] = Field(
|
|
197
|
+
None, max_length=1000, description="订单备注"
|
|
198
|
+
)
|
|
199
|
+
|
|
200
|
+
@validator("shipping_address")
|
|
201
|
+
def validate_address(cls, v):
|
|
202
|
+
if not v.strip():
|
|
203
|
+
raise ValueError("地址不能为空白")
|
|
204
|
+
return v.strip()
|
|
205
|
+
|
|
206
|
+
class UpdateOrderRequest(BaseModel):
|
|
207
|
+
"""部分更新订单请求(PATCH)"""
|
|
208
|
+
status: Optional[OrderStatus] = None
|
|
209
|
+
shipping_address: Optional[str] = Field(None, min_length=5, max_length=500)
|
|
210
|
+
note: Optional[str] = Field(None, max_length=1000)
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
### 3.2 响应格式
|
|
214
|
+
|
|
215
|
+
```python
|
|
216
|
+
from datetime import datetime
|
|
217
|
+
from typing import TypeVar, Generic, List, Optional
|
|
218
|
+
from pydantic import BaseModel
|
|
219
|
+
|
|
220
|
+
T = TypeVar("T")
|
|
221
|
+
|
|
222
|
+
# 单个资源响应
|
|
223
|
+
class OrderResponse(BaseModel):
|
|
224
|
+
id: int
|
|
225
|
+
product_id: int
|
|
226
|
+
quantity: int
|
|
227
|
+
status: str
|
|
228
|
+
total_amount: float
|
|
229
|
+
shipping_address: str
|
|
230
|
+
note: Optional[str]
|
|
231
|
+
created_at: datetime
|
|
232
|
+
updated_at: datetime
|
|
233
|
+
|
|
234
|
+
class Config:
|
|
235
|
+
json_encoders = {
|
|
236
|
+
datetime: lambda v: v.isoformat()
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
# 列表响应(带分页)
|
|
240
|
+
class PaginatedResponse(BaseModel, Generic[T]):
|
|
241
|
+
data: List[T]
|
|
242
|
+
pagination: dict # {"page": 1, "per_page": 20, "total": 150, "total_pages": 8}
|
|
243
|
+
links: dict # {"self": "...", "first": "...", "prev": "...", "next": "...", "last": "..."}
|
|
244
|
+
|
|
245
|
+
# HATEOAS 链接(可选)
|
|
246
|
+
class OrderWithLinks(OrderResponse):
|
|
247
|
+
links: dict = {}
|
|
248
|
+
|
|
249
|
+
@classmethod
|
|
250
|
+
def from_order(cls, order, base_url: str):
|
|
251
|
+
return cls(
|
|
252
|
+
**order.dict(),
|
|
253
|
+
links={
|
|
254
|
+
"self": f"{base_url}/orders/{order.id}",
|
|
255
|
+
"cancel": f"{base_url}/orders/{order.id}/cancel",
|
|
256
|
+
"user": f"{base_url}/users/{order.user_id}",
|
|
257
|
+
}
|
|
258
|
+
)
|
|
259
|
+
```
|
|
260
|
+
|
|
261
|
+
---
|
|
262
|
+
|
|
263
|
+
## 步骤四:错误处理
|
|
264
|
+
|
|
265
|
+
### 4.1 统一错误格式
|
|
266
|
+
|
|
267
|
+
```python
|
|
268
|
+
from fastapi import FastAPI, Request
|
|
269
|
+
from fastapi.responses import JSONResponse
|
|
270
|
+
from pydantic import BaseModel
|
|
271
|
+
from typing import Optional, List
|
|
272
|
+
|
|
273
|
+
class ErrorDetail(BaseModel):
|
|
274
|
+
field: Optional[str] = None
|
|
275
|
+
message: str
|
|
276
|
+
code: str
|
|
277
|
+
|
|
278
|
+
class ErrorResponse(BaseModel):
|
|
279
|
+
error: dict # {"code": "...", "message": "...", "details": [...], "request_id": "..."}
|
|
280
|
+
|
|
281
|
+
# 统一错误响应示例
|
|
282
|
+
{
|
|
283
|
+
"error": {
|
|
284
|
+
"code": "VALIDATION_ERROR",
|
|
285
|
+
"message": "请求参数校验失败",
|
|
286
|
+
"details": [
|
|
287
|
+
{"field": "quantity", "message": "必须大于 0", "code": "INVALID_VALUE"},
|
|
288
|
+
{"field": "email", "message": "邮箱格式不正确", "code": "INVALID_FORMAT"}
|
|
289
|
+
],
|
|
290
|
+
"request_id": "req_abc123def456",
|
|
291
|
+
"doc_url": "https://docs.example.com/errors/VALIDATION_ERROR"
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
# 业务错误码定义
|
|
296
|
+
ERROR_CODES = {
|
|
297
|
+
# 通用错误 (1xxx)
|
|
298
|
+
"VALIDATION_ERROR": {"status": 400, "message": "请求参数校验失败"},
|
|
299
|
+
"UNAUTHORIZED": {"status": 401, "message": "未认证"},
|
|
300
|
+
"FORBIDDEN": {"status": 403, "message": "无权限"},
|
|
301
|
+
"NOT_FOUND": {"status": 404, "message": "资源不存在"},
|
|
302
|
+
"CONFLICT": {"status": 409, "message": "资源冲突"},
|
|
303
|
+
"RATE_LIMITED": {"status": 429, "message": "请求频率超限"},
|
|
304
|
+
|
|
305
|
+
# 订单错误 (2xxx)
|
|
306
|
+
"ORDER_NOT_FOUND": {"status": 404, "message": "订单不存在"},
|
|
307
|
+
"ORDER_ALREADY_CANCELLED": {"status": 409, "message": "订单已取消"},
|
|
308
|
+
"INSUFFICIENT_STOCK": {"status": 422, "message": "库存不足"},
|
|
309
|
+
|
|
310
|
+
# 支付错误 (3xxx)
|
|
311
|
+
"PAYMENT_FAILED": {"status": 422, "message": "支付失败"},
|
|
312
|
+
"PAYMENT_TIMEOUT": {"status": 504, "message": "支付超时"},
|
|
313
|
+
}
|
|
314
|
+
```
|
|
315
|
+
|
|
316
|
+
### 4.2 全局异常处理
|
|
317
|
+
|
|
318
|
+
```python
|
|
319
|
+
from fastapi import FastAPI, Request
|
|
320
|
+
from fastapi.responses import JSONResponse
|
|
321
|
+
from fastapi.exceptions import RequestValidationError
|
|
322
|
+
import uuid
|
|
323
|
+
import logging
|
|
324
|
+
|
|
325
|
+
logger = logging.getLogger(__name__)
|
|
326
|
+
app = FastAPI()
|
|
327
|
+
|
|
328
|
+
class BusinessError(Exception):
|
|
329
|
+
def __init__(self, code: str, message: str = None, details: list = None):
|
|
330
|
+
self.code = code
|
|
331
|
+
self.message = message or ERROR_CODES.get(code, {}).get("message", "未知错误")
|
|
332
|
+
self.status = ERROR_CODES.get(code, {}).get("status", 500)
|
|
333
|
+
self.details = details or []
|
|
334
|
+
|
|
335
|
+
@app.exception_handler(BusinessError)
|
|
336
|
+
async def business_error_handler(request: Request, exc: BusinessError):
|
|
337
|
+
request_id = request.headers.get("X-Request-ID", str(uuid.uuid4()))
|
|
338
|
+
return JSONResponse(
|
|
339
|
+
status_code=exc.status,
|
|
340
|
+
content={
|
|
341
|
+
"error": {
|
|
342
|
+
"code": exc.code,
|
|
343
|
+
"message": exc.message,
|
|
344
|
+
"details": exc.details,
|
|
345
|
+
"request_id": request_id,
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
)
|
|
349
|
+
|
|
350
|
+
@app.exception_handler(RequestValidationError)
|
|
351
|
+
async def validation_error_handler(request: Request, exc: RequestValidationError):
|
|
352
|
+
request_id = request.headers.get("X-Request-ID", str(uuid.uuid4()))
|
|
353
|
+
details = [
|
|
354
|
+
{"field": ".".join(str(loc) for loc in err["loc"]), "message": err["msg"], "code": "INVALID_VALUE"}
|
|
355
|
+
for err in exc.errors()
|
|
356
|
+
]
|
|
357
|
+
return JSONResponse(
|
|
358
|
+
status_code=400,
|
|
359
|
+
content={
|
|
360
|
+
"error": {
|
|
361
|
+
"code": "VALIDATION_ERROR",
|
|
362
|
+
"message": "请求参数校验失败",
|
|
363
|
+
"details": details,
|
|
364
|
+
"request_id": request_id,
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
)
|
|
368
|
+
|
|
369
|
+
@app.exception_handler(Exception)
|
|
370
|
+
async def general_error_handler(request: Request, exc: Exception):
|
|
371
|
+
request_id = request.headers.get("X-Request-ID", str(uuid.uuid4()))
|
|
372
|
+
logger.exception("Unhandled exception", extra={"request_id": request_id})
|
|
373
|
+
return JSONResponse(
|
|
374
|
+
status_code=500,
|
|
375
|
+
content={
|
|
376
|
+
"error": {
|
|
377
|
+
"code": "INTERNAL_ERROR",
|
|
378
|
+
"message": "服务内部错误",
|
|
379
|
+
"request_id": request_id,
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
)
|
|
383
|
+
```
|
|
384
|
+
|
|
385
|
+
---
|
|
386
|
+
|
|
387
|
+
## 步骤五:分页与过滤
|
|
388
|
+
|
|
389
|
+
### 5.1 分页实现
|
|
390
|
+
|
|
391
|
+
```python
|
|
392
|
+
from fastapi import Query
|
|
393
|
+
from typing import Optional
|
|
394
|
+
from math import ceil
|
|
395
|
+
|
|
396
|
+
# 偏移量分页(适用于中小数据集)
|
|
397
|
+
@app.get("/api/v1/orders")
|
|
398
|
+
async def list_orders(
|
|
399
|
+
page: int = Query(1, ge=1, description="页码"),
|
|
400
|
+
per_page: int = Query(20, ge=1, le=100, description="每页数量"),
|
|
401
|
+
):
|
|
402
|
+
offset = (page - 1) * per_page
|
|
403
|
+
total = await Order.count()
|
|
404
|
+
orders = await Order.find().skip(offset).limit(per_page).to_list()
|
|
405
|
+
|
|
406
|
+
total_pages = ceil(total / per_page)
|
|
407
|
+
base_url = "/api/v1/orders"
|
|
408
|
+
|
|
409
|
+
return {
|
|
410
|
+
"data": orders,
|
|
411
|
+
"pagination": {
|
|
412
|
+
"page": page,
|
|
413
|
+
"per_page": per_page,
|
|
414
|
+
"total": total,
|
|
415
|
+
"total_pages": total_pages,
|
|
416
|
+
},
|
|
417
|
+
"links": {
|
|
418
|
+
"self": f"{base_url}?page={page}&per_page={per_page}",
|
|
419
|
+
"first": f"{base_url}?page=1&per_page={per_page}",
|
|
420
|
+
"last": f"{base_url}?page={total_pages}&per_page={per_page}",
|
|
421
|
+
"prev": f"{base_url}?page={page-1}&per_page={per_page}" if page > 1 else None,
|
|
422
|
+
"next": f"{base_url}?page={page+1}&per_page={per_page}" if page < total_pages else None,
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
# 游标分页(适用于大数据集,避免深度分页)
|
|
427
|
+
@app.get("/api/v1/events")
|
|
428
|
+
async def list_events(
|
|
429
|
+
cursor: Optional[str] = Query(None, description="分页游标"),
|
|
430
|
+
limit: int = Query(20, ge=1, le=100, description="每页数量"),
|
|
431
|
+
):
|
|
432
|
+
query = {}
|
|
433
|
+
if cursor:
|
|
434
|
+
query["id"] = {"$gt": decode_cursor(cursor)}
|
|
435
|
+
|
|
436
|
+
events = await Event.find(query).sort("id", 1).limit(limit + 1).to_list()
|
|
437
|
+
|
|
438
|
+
has_next = len(events) > limit
|
|
439
|
+
if has_next:
|
|
440
|
+
events = events[:limit]
|
|
441
|
+
|
|
442
|
+
next_cursor = encode_cursor(events[-1]["id"]) if has_next else None
|
|
443
|
+
|
|
444
|
+
return {
|
|
445
|
+
"data": events,
|
|
446
|
+
"pagination": {
|
|
447
|
+
"has_next": has_next,
|
|
448
|
+
"next_cursor": next_cursor,
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
```
|
|
452
|
+
|
|
453
|
+
### 5.2 过滤与排序
|
|
454
|
+
|
|
455
|
+
```python
|
|
456
|
+
from fastapi import Query
|
|
457
|
+
from typing import Optional, List
|
|
458
|
+
from enum import Enum
|
|
459
|
+
|
|
460
|
+
class SortOrder(str, Enum):
|
|
461
|
+
ASC = "asc"
|
|
462
|
+
DESC = "desc"
|
|
463
|
+
|
|
464
|
+
@app.get("/api/v1/orders")
|
|
465
|
+
async def list_orders(
|
|
466
|
+
# 精确过滤
|
|
467
|
+
status: Optional[str] = Query(None, description="订单状态"),
|
|
468
|
+
user_id: Optional[int] = Query(None, description="用户 ID"),
|
|
469
|
+
|
|
470
|
+
# 范围过滤
|
|
471
|
+
min_amount: Optional[float] = Query(None, ge=0, description="最小金额"),
|
|
472
|
+
max_amount: Optional[float] = Query(None, ge=0, description="最大金额"),
|
|
473
|
+
created_after: Optional[datetime] = Query(None, description="创建时间起始"),
|
|
474
|
+
created_before: Optional[datetime] = Query(None, description="创建时间结束"),
|
|
475
|
+
|
|
476
|
+
# 模糊搜索
|
|
477
|
+
q: Optional[str] = Query(None, min_length=2, max_length=100, description="关键词搜索"),
|
|
478
|
+
|
|
479
|
+
# 排序
|
|
480
|
+
sort_by: str = Query("created_at", description="排序字段"),
|
|
481
|
+
sort_order: SortOrder = Query(SortOrder.DESC, description="排序方向"),
|
|
482
|
+
|
|
483
|
+
# 字段选择(减少传输量)
|
|
484
|
+
fields: Optional[str] = Query(None, description="返回字段,逗号分隔"),
|
|
485
|
+
|
|
486
|
+
# 分页
|
|
487
|
+
page: int = Query(1, ge=1),
|
|
488
|
+
per_page: int = Query(20, ge=1, le=100),
|
|
489
|
+
):
|
|
490
|
+
# 构建查询
|
|
491
|
+
filters = {}
|
|
492
|
+
if status:
|
|
493
|
+
filters["status"] = status
|
|
494
|
+
if user_id:
|
|
495
|
+
filters["user_id"] = user_id
|
|
496
|
+
if min_amount is not None:
|
|
497
|
+
filters["amount__gte"] = min_amount
|
|
498
|
+
if max_amount is not None:
|
|
499
|
+
filters["amount__lte"] = max_amount
|
|
500
|
+
|
|
501
|
+
# 排序白名单(防止任意字段排序导致的性能问题)
|
|
502
|
+
ALLOWED_SORT_FIELDS = {"created_at", "updated_at", "amount", "status"}
|
|
503
|
+
if sort_by not in ALLOWED_SORT_FIELDS:
|
|
504
|
+
raise BusinessError("VALIDATION_ERROR", f"不支持按 {sort_by} 排序")
|
|
505
|
+
|
|
506
|
+
# 执行查询...
|
|
507
|
+
pass
|
|
508
|
+
```
|
|
509
|
+
|
|
510
|
+
---
|
|
511
|
+
|
|
512
|
+
## 步骤六:认证与授权
|
|
513
|
+
|
|
514
|
+
### 6.1 认证方案
|
|
515
|
+
|
|
516
|
+
```python
|
|
517
|
+
from fastapi import Depends, HTTPException, Security
|
|
518
|
+
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
|
519
|
+
import jwt
|
|
520
|
+
|
|
521
|
+
security = HTTPBearer()
|
|
522
|
+
|
|
523
|
+
async def verify_token(
|
|
524
|
+
credentials: HTTPAuthorizationCredentials = Security(security)
|
|
525
|
+
) -> dict:
|
|
526
|
+
"""JWT Bearer Token 认证"""
|
|
527
|
+
try:
|
|
528
|
+
payload = jwt.decode(
|
|
529
|
+
credentials.credentials,
|
|
530
|
+
SECRET_KEY,
|
|
531
|
+
algorithms=["HS256"],
|
|
532
|
+
options={"require": ["exp", "sub", "iss"]}
|
|
533
|
+
)
|
|
534
|
+
return payload
|
|
535
|
+
except jwt.ExpiredSignatureError:
|
|
536
|
+
raise HTTPException(status_code=401, detail="Token 已过期")
|
|
537
|
+
except jwt.InvalidTokenError:
|
|
538
|
+
raise HTTPException(status_code=401, detail="无效的 Token")
|
|
539
|
+
|
|
540
|
+
# API Key 认证(用于服务间调用)
|
|
541
|
+
from fastapi.security import APIKeyHeader
|
|
542
|
+
|
|
543
|
+
api_key_header = APIKeyHeader(name="X-API-Key")
|
|
544
|
+
|
|
545
|
+
async def verify_api_key(api_key: str = Security(api_key_header)) -> dict:
|
|
546
|
+
"""API Key 认证"""
|
|
547
|
+
client = await get_api_client(api_key)
|
|
548
|
+
if not client:
|
|
549
|
+
raise HTTPException(status_code=401, detail="无效的 API Key")
|
|
550
|
+
return client
|
|
551
|
+
```
|
|
552
|
+
|
|
553
|
+
### 6.2 授权中间件
|
|
554
|
+
|
|
555
|
+
```python
|
|
556
|
+
from functools import wraps
|
|
557
|
+
from fastapi import Depends
|
|
558
|
+
|
|
559
|
+
def require_permission(permission: str):
|
|
560
|
+
"""基于权限的访问控制"""
|
|
561
|
+
async def check_permission(user: dict = Depends(verify_token)):
|
|
562
|
+
user_permissions = await get_user_permissions(user["sub"])
|
|
563
|
+
if permission not in user_permissions:
|
|
564
|
+
raise BusinessError("FORBIDDEN", f"缺少权限: {permission}")
|
|
565
|
+
return user
|
|
566
|
+
return check_permission
|
|
567
|
+
|
|
568
|
+
# 使用示例
|
|
569
|
+
@app.delete("/api/v1/orders/{order_id}")
|
|
570
|
+
async def delete_order(
|
|
571
|
+
order_id: int,
|
|
572
|
+
user: dict = Depends(require_permission("order:delete"))
|
|
573
|
+
):
|
|
574
|
+
...
|
|
575
|
+
|
|
576
|
+
# 资源级别权限检查
|
|
577
|
+
@app.get("/api/v1/orders/{order_id}")
|
|
578
|
+
async def get_order(
|
|
579
|
+
order_id: int,
|
|
580
|
+
user: dict = Depends(verify_token)
|
|
581
|
+
):
|
|
582
|
+
order = await Order.get(order_id)
|
|
583
|
+
if not order:
|
|
584
|
+
raise BusinessError("ORDER_NOT_FOUND")
|
|
585
|
+
# 检查资源所有权
|
|
586
|
+
if order.user_id != user["sub"] and "admin" not in user.get("roles", []):
|
|
587
|
+
raise BusinessError("FORBIDDEN")
|
|
588
|
+
return order
|
|
589
|
+
```
|
|
590
|
+
|
|
591
|
+
---
|
|
592
|
+
|
|
593
|
+
## 步骤七:限流保护
|
|
594
|
+
|
|
595
|
+
### 7.1 限流策略
|
|
596
|
+
|
|
597
|
+
```python
|
|
598
|
+
import time
|
|
599
|
+
import redis
|
|
600
|
+
|
|
601
|
+
redis_client = redis.Redis()
|
|
602
|
+
|
|
603
|
+
class RateLimiter:
|
|
604
|
+
"""滑动窗口限流"""
|
|
605
|
+
|
|
606
|
+
def __init__(self, key_prefix: str, max_requests: int, window_seconds: int):
|
|
607
|
+
self.key_prefix = key_prefix
|
|
608
|
+
self.max_requests = max_requests
|
|
609
|
+
self.window_seconds = window_seconds
|
|
610
|
+
|
|
611
|
+
def is_allowed(self, identifier: str) -> tuple[bool, dict]:
|
|
612
|
+
key = f"rate:{self.key_prefix}:{identifier}"
|
|
613
|
+
now = time.time()
|
|
614
|
+
window_start = now - self.window_seconds
|
|
615
|
+
|
|
616
|
+
pipe = redis_client.pipeline()
|
|
617
|
+
pipe.zremrangebyscore(key, 0, window_start) # 清理过期记录
|
|
618
|
+
pipe.zcard(key) # 当前计数
|
|
619
|
+
pipe.zadd(key, {str(now): now}) # 添加当前请求
|
|
620
|
+
pipe.expire(key, self.window_seconds) # 设置过期
|
|
621
|
+
results = pipe.execute()
|
|
622
|
+
|
|
623
|
+
current_count = results[1]
|
|
624
|
+
remaining = max(0, self.max_requests - current_count - 1)
|
|
625
|
+
reset_at = int(now + self.window_seconds)
|
|
626
|
+
|
|
627
|
+
headers = {
|
|
628
|
+
"X-RateLimit-Limit": str(self.max_requests),
|
|
629
|
+
"X-RateLimit-Remaining": str(remaining),
|
|
630
|
+
"X-RateLimit-Reset": str(reset_at),
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
if current_count >= self.max_requests:
|
|
634
|
+
headers["Retry-After"] = str(self.window_seconds)
|
|
635
|
+
return False, headers
|
|
636
|
+
|
|
637
|
+
return True, headers
|
|
638
|
+
|
|
639
|
+
# 限流配置
|
|
640
|
+
RATE_LIMITS = {
|
|
641
|
+
"default": RateLimiter("default", max_requests=100, window_seconds=60),
|
|
642
|
+
"auth": RateLimiter("auth", max_requests=10, window_seconds=60),
|
|
643
|
+
"search": RateLimiter("search", max_requests=30, window_seconds=60),
|
|
644
|
+
"export": RateLimiter("export", max_requests=5, window_seconds=300),
|
|
645
|
+
}
|
|
646
|
+
```
|
|
647
|
+
|
|
648
|
+
### 7.2 限流中间件
|
|
649
|
+
|
|
650
|
+
```python
|
|
651
|
+
from fastapi import Request
|
|
652
|
+
from fastapi.responses import JSONResponse
|
|
653
|
+
|
|
654
|
+
@app.middleware("http")
|
|
655
|
+
async def rate_limit_middleware(request: Request, call_next):
|
|
656
|
+
# 确定限流 key
|
|
657
|
+
client_ip = request.client.host
|
|
658
|
+
api_key = request.headers.get("X-API-Key", "")
|
|
659
|
+
identifier = api_key or client_ip
|
|
660
|
+
|
|
661
|
+
# 选择限流策略
|
|
662
|
+
path = request.url.path
|
|
663
|
+
if "/auth/" in path:
|
|
664
|
+
limiter = RATE_LIMITS["auth"]
|
|
665
|
+
elif "/search" in path:
|
|
666
|
+
limiter = RATE_LIMITS["search"]
|
|
667
|
+
elif "/export" in path:
|
|
668
|
+
limiter = RATE_LIMITS["export"]
|
|
669
|
+
else:
|
|
670
|
+
limiter = RATE_LIMITS["default"]
|
|
671
|
+
|
|
672
|
+
allowed, headers = limiter.is_allowed(identifier)
|
|
673
|
+
|
|
674
|
+
if not allowed:
|
|
675
|
+
return JSONResponse(
|
|
676
|
+
status_code=429,
|
|
677
|
+
content={"error": {"code": "RATE_LIMITED", "message": "请求频率超限"}},
|
|
678
|
+
headers=headers,
|
|
679
|
+
)
|
|
680
|
+
|
|
681
|
+
response = await call_next(request)
|
|
682
|
+
for k, v in headers.items():
|
|
683
|
+
response.headers[k] = v
|
|
684
|
+
return response
|
|
685
|
+
```
|
|
686
|
+
|
|
687
|
+
---
|
|
688
|
+
|
|
689
|
+
## 步骤八:API 文档
|
|
690
|
+
|
|
691
|
+
### 8.1 OpenAPI 自动生成
|
|
692
|
+
|
|
693
|
+
```python
|
|
694
|
+
from fastapi import FastAPI
|
|
695
|
+
|
|
696
|
+
app = FastAPI(
|
|
697
|
+
title="Order Service API",
|
|
698
|
+
description="订单服务 API 文档",
|
|
699
|
+
version="1.2.0",
|
|
700
|
+
docs_url="/api/docs",
|
|
701
|
+
redoc_url="/api/redoc",
|
|
702
|
+
openapi_url="/api/openapi.json",
|
|
703
|
+
servers=[
|
|
704
|
+
{"url": "https://api.example.com", "description": "生产环境"},
|
|
705
|
+
{"url": "https://staging-api.example.com", "description": "预发布环境"},
|
|
706
|
+
],
|
|
707
|
+
)
|
|
708
|
+
|
|
709
|
+
# 为每个端点添加详细文档
|
|
710
|
+
@app.post(
|
|
711
|
+
"/api/v1/orders",
|
|
712
|
+
response_model=OrderResponse,
|
|
713
|
+
status_code=201,
|
|
714
|
+
summary="创建订单",
|
|
715
|
+
description="创建新订单。需要 order:create 权限。",
|
|
716
|
+
responses={
|
|
717
|
+
201: {"description": "订单创建成功"},
|
|
718
|
+
400: {"description": "请求参数校验失败", "model": ErrorResponse},
|
|
719
|
+
401: {"description": "未认证"},
|
|
720
|
+
422: {"description": "库存不足", "model": ErrorResponse},
|
|
721
|
+
},
|
|
722
|
+
tags=["orders"],
|
|
723
|
+
)
|
|
724
|
+
async def create_order(request: CreateOrderRequest):
|
|
725
|
+
...
|
|
726
|
+
```
|
|
727
|
+
|
|
728
|
+
### 8.2 API 文档检查清单
|
|
729
|
+
|
|
730
|
+
```markdown
|
|
731
|
+
每个 API 端点必须包含:
|
|
732
|
+
- [ ] 简短的摘要(summary)
|
|
733
|
+
- [ ] 详细的描述(description),包含使用场景
|
|
734
|
+
- [ ] 所有参数的类型、约束和说明
|
|
735
|
+
- [ ] 所有可能的响应状态码和示例
|
|
736
|
+
- [ ] 认证要求
|
|
737
|
+
- [ ] 限流配额
|
|
738
|
+
- [ ] 请求/响应示例(至少一个成功和一个失败)
|
|
739
|
+
```
|
|
740
|
+
|
|
741
|
+
---
|
|
742
|
+
|
|
743
|
+
## 验证
|
|
744
|
+
|
|
745
|
+
### API 设计评审 Checklist
|
|
746
|
+
|
|
747
|
+
```markdown
|
|
748
|
+
### URL 设计
|
|
749
|
+
- [ ] 资源命名使用复数名词
|
|
750
|
+
- [ ] 层级不超过 3 层
|
|
751
|
+
- [ ] 使用 kebab-case
|
|
752
|
+
- [ ] HTTP 方法语义正确
|
|
753
|
+
|
|
754
|
+
### 请求/响应
|
|
755
|
+
- [ ] 所有输入有校验规则
|
|
756
|
+
- [ ] 响应格式统一
|
|
757
|
+
- [ ] 日期时间使用 ISO 8601
|
|
758
|
+
- [ ] 金额使用最小单位(分)或 Decimal
|
|
759
|
+
|
|
760
|
+
### 错误处理
|
|
761
|
+
- [ ] 错误码体系完整
|
|
762
|
+
- [ ] 错误响应包含 request_id
|
|
763
|
+
- [ ] 4xx 和 5xx 区分清晰
|
|
764
|
+
- [ ] 不泄漏内部信息
|
|
765
|
+
|
|
766
|
+
### 安全
|
|
767
|
+
- [ ] 认证机制就位
|
|
768
|
+
- [ ] 授权检查到位(资源级别)
|
|
769
|
+
- [ ] 限流配置合理
|
|
770
|
+
- [ ] CORS 配置正确
|
|
771
|
+
- [ ] 敏感数据不出现在 URL 中
|
|
772
|
+
```
|
|
773
|
+
|
|
774
|
+
---
|
|
775
|
+
|
|
776
|
+
## 回滚方案
|
|
777
|
+
|
|
778
|
+
### API 版本回滚
|
|
779
|
+
|
|
780
|
+
```bash
|
|
781
|
+
# 如果新版 API 有问题,保持旧版 API 可用
|
|
782
|
+
# 通过 API 网关路由切换
|
|
783
|
+
curl -X PUT http://api-gateway/routes/v2/orders \
|
|
784
|
+
-d '{"upstream": "order-service-v1", "status": "deprecated"}'
|
|
785
|
+
|
|
786
|
+
# 如果破坏性变更已影响客户端
|
|
787
|
+
# 1. 立即回滚服务到旧版本
|
|
788
|
+
kubectl rollout undo deployment/order-service -n production
|
|
789
|
+
# 2. 发布兼容性补丁
|
|
790
|
+
# 3. 通知受影响的 API 消费方
|
|
791
|
+
```
|
|
792
|
+
|
|
793
|
+
---
|
|
794
|
+
|
|
795
|
+
## Agent Checklist
|
|
796
|
+
|
|
797
|
+
AI 编码 Agent 在设计或实现 API 时必须逐项确认:
|
|
798
|
+
|
|
799
|
+
- [ ] **URL 规范**:资源命名、HTTP 方法、状态码均符合 RESTful 规范
|
|
800
|
+
- [ ] **版本策略**:使用 URL 路径版本,有版本演进计划
|
|
801
|
+
- [ ] **输入校验**:所有参数有类型、范围、长度约束
|
|
802
|
+
- [ ] **响应格式**:统一的成功和错误响应结构
|
|
803
|
+
- [ ] **错误处理**:完整的错误码体系,包含 request_id
|
|
804
|
+
- [ ] **分页实现**:列表接口有分页,大数据集使用游标分页
|
|
805
|
+
- [ ] **过滤排序**:排序字段有白名单限制
|
|
806
|
+
- [ ] **认证授权**:所有非公开接口有认证,敏感操作有授权检查
|
|
807
|
+
- [ ] **限流保护**:已配置合理的限流策略,响应包含限流头
|
|
808
|
+
- [ ] **文档完整**:OpenAPI 文档覆盖所有端点和错误码
|
|
809
|
+
- [ ] **幂等性**:PUT/DELETE 幂等,POST 有去重机制(如需)
|
|
810
|
+
- [ ] **向后兼容**:新增字段可选,不删除已有字段
|