Skip to content

Document type annotation principles for FastAPI dependency injection - #1

Draft
wwfyde with Copilot wants to merge 2 commits into
mainfrom
copilot/update-chat-session-endpoint
Draft

Document type annotation principles for FastAPI dependency injection#1
wwfyde with Copilot wants to merge 2 commits into
mainfrom
copilot/update-chat-session-endpoint

Conversation

CopilotAI commented Nov 7, 2025

Copy link
Copy Markdown

The problem statement asks how to properly annotate return types in dependency functions: ChatService() vs ChatService, and requests a principle-based explanation.

Changes

Added comprehensive documentation section "依赖注入的类型注解原理" to FastAPI框架.md covering:

  • Core principle: Use ChatService (type) not ChatService() (call expression) in type annotations
  • Annotated mechanics: First parameter is the type for type checkers, second is FastAPI metadata (Depends)
  • Dependency injection workflow: How FastAPI resolves, calls, validates, and injects dependencies
  • Complete examples: ChatService and CanvasService with correct/incorrect patterns
  • Summary table: Quick reference for return types, parameter types, and return values

Example

# Dependency function - return type uses the class (type)chat_service=ChatService()
defget_chat_service() ->ChatService: # ✅ Type annotationreturnchat_service# ✅ Returns instance# Route function - parameter uses Annotated with type and metadata@router.get("/chat_session/{session_id}")asyncdefget_chat_session(
session_id: str,
chat_service: Annotated[ChatService, Depends(get_chat_service)]
):
returnawaitchat_service.get_chat_history(session_id=session_id)

Type annotations always use types (classes), never call expressions. The dependency system handles instantiation and injection at runtime.

Original prompt

@router.get("/chat_session/{session_id}")
async def get_chat_session(
session_id: str, chat_service=Annotated[ChatService, Depends(get_chat_service)]
):
return await chat_service.get_chat_history(session_id=session_id)
chat_service = ChatService()

def get_canvas_service() -> CanvasService:
return canvas_service

def get_chat_service() -> ChatService:
return chat_service

返回类实例时 Annotated[ChatService, 注解 如何注解 ChatService() 还是 ChatService 从原理上讲清楚


✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

…annotations
Co-authored-by: wwfyde <17171720+wwfyde@users.noreply.github.com>
CopilotAI changed the title [WIP] Update chat session retrieval methodDocument type annotation principles for FastAPI dependency injectionNov 7, 2025
CopilotAI requested a review from wwfydeNovember 7, 2025 02:26
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

@wwfyde