Agentic Browser

Home Projects Agentic Browser Python Backend Api Api Routers

API Routers

This document provides a comprehensive overview of all FastAPI routers exposed by the Agentic Browser API server. It covers router registration, URL path mapping, architectural patterns, and the request/response flow common to all routers. For detailed information about specific router implementations, see subsections 3.3.1 through 3.3.6. For information about the service layer that routers depend on, see 3.4.

Router Registration and Organization

The FastAPI application in api/main.py serves as the central point where all routers are imported and registered with URL prefixes. The application exposes 11 distinct routers, each handling a specific domain of functionality.

Diagram: Router Registration Flow

Architecture Diagram

The router registration follows this pattern:

  1. Individual router modules define an APIRouter instance named router
  2. The routers/__init__.py package exports each router with a descriptive alias (e.g., health_router, github_router)
  3. The main application imports all routers and registers them with app.include_router(), assigning URL prefixes

Complete Router Inventory

The following table provides a complete reference of all routers, their URL prefixes, primary endpoints, and functional domains:

Router Name URL Prefix Primary Endpoints Functional Domain Sub-Section Reference
health_router /api/genai/health GET / System health monitoring N/A
github_router /api/genai/github POST / GitHub repository Q&A and analysis 3.3.4
website_router /api/genai/website POST / Web page content analysis and Q&A 3.3.2
youtube_router /api/genai/youtube POST / YouTube video transcript Q&A 3.3.3
google_search_router /api/google-search GET / Web search via Tavily API 3.3.2
gmail_router /api/gmail POST /unread POST /latest POST /mark_read POST /send Gmail operations with OAuth 3.3.1
calendar_router /api/calendar POST /events POST /create Google Calendar operations with OAuth 3.3.1
pyjiit_router /api/pyjiit Multiple endpoints JIIT Webportal integration 3.3.5
react_agent_router /api/genai/react POST / Conversational AI with tool use 4.1
website_validator_router /api/validator POST / Prompt injection detection 3.3.6
browser_use_router /api/agent POST / Browser automation script generation 4.2

Router Architecture Pattern

All routers in the application follow a consistent three-tier architecture pattern: Router → Service → Tool. This separation of concerns enables maintainability, testability, and reusability.

Diagram: Three-Tier Router Architecture

Architecture Diagram

Router Tier Responsibilities

The router tier handles HTTP-level concerns:

  • Request validation: Pydantic models parse and validate incoming JSON routers/youtube.py15-17
  • Dependency injection: Services are injected via FastAPI's Depends() mechanism routers/youtube.py10-17
  • Error handling: All exceptions are caught and converted to appropriate HTTPException responses routers/youtube.py50-58
  • Response formatting: Results are serialized to JSON with type-safe response models

Example from YouTube router:

@router.post("/", response_model=dict)
async def ask(
    request: AskRequest, service: YouTubeService = Depends(get_youtube_service)
):

Service Tier Responsibilities

The service tier encapsulates business logic:

  • Orchestration: Coordinates multiple tool calls
  • Data transformation: Converts between external formats and internal models routers/youtube.py24-32
  • Logging: Structured logging at debug and info levels routers/youtube.py40-44
  • Error handling: Service-specific error handling and recovery

Example pattern from YouTube router showing chat history transformation:

chat_history_str = ""
if chat_history_list:
    for entry in chat_history_list:
        if isinstance(entry, dict):
            role = entry.get("role", "")
            content = entry.get("content", "")
            chat_history_str += f"{role}: {content}\n"

Tool Tier Responsibilities

The tool tier provides reusable, testable implementations:

  • External API integration: Direct communication with third-party services
  • Data extraction: Parsing and processing external data formats
  • Caching: Optional caching of expensive operations
  • Error recovery: Graceful handling of external service failures

Common Request/Response Patterns

Authentication Patterns

Routers requiring external service authentication follow one of two patterns:

OAuth Token Pattern (Gmail, Calendar):

class TokenRequest(BaseModel):
    access_token: str

All Gmail and Calendar endpoints require an access_token field in the request body, validated at the router level before service invocation routers/gmail.py12-14 routers/calendar.py13-15

Session-Based Pattern (PyJIIT): The PyJIIT router uses an encrypted session token obtained through a separate authentication flow. Details in 3.3.5.

Q&A Content Pattern

Multiple routers (GitHub, Website, YouTube) implement a Q&A pattern for content analysis:

Common Request Structure:

class AskRequest(BaseModel):
    url: str
    question: str
    chat_history: Optional[List[Dict[str, str]]] = None

This pattern enables:

  • URL-based content: Content is fetched from the provided URL
  • Natural language queries: Users ask questions in plain text
  • Conversation context: Optional chat history maintains context across multiple turns

Error Handling Pattern

All routers implement a consistent error handling strategy:

  1. Validation errors return 400 status codes with descriptive messages
  2. Service errors are caught and logged, then returned as 500 status codes
  3. HTTPException instances are re-raised without modification to preserve status codes

Example from Gmail router:

try:
    if not request.access_token:
        raise HTTPException(status_code=400, detail="access_token is required")

    results = service.list_unread_messages(
        request.access_token, max_results=request.max_results
    )
    return {"messages": results}

except HTTPException:
    raise

except Exception as e:
    raise HTTPException(status_code=500, detail=str(e))

Endpoint Multiplicity Patterns

Some routers expose multiple endpoints for related operations:

Gmail Router Endpoints

Endpoint Method Purpose Required Fields
/unread POST List unread messages access_token, optional max_results
/latest POST Fetch latest messages access_token, optional max_results
/mark_read POST Mark message as read access_token, message_id
/send POST Send email access_token, to, subject, body

Calendar Router Endpoints

Endpoint Method Purpose Required Fields
/events POST List upcoming events access_token, optional max_results
/create POST Create calendar event access_token, summary, start_time, end_time

The Calendar router includes validation for ISO 8601 datetime formats in event creation routers/calendar.py59-91

Health Check Router

The health_router is unique in its simplicity, providing a lightweight endpoint for monitoring system availability:

@router.get("/", response_model=HealthResponse)
async def health_handler():
    return HealthResponse(
        status="healthy",
        message="Agentic Browser API is running smoothly.",
    )

This endpoint requires no authentication and returns a simple JSON response indicating the API server is operational.

Service Dependency Injection

All routers (except health) use FastAPI's dependency injection system to obtain service instances:

Pattern:

def get_youtube_service():
    return YouTubeService()

@router.post("/", response_model=dict)
async def ask(
    request: AskRequest, service: YouTubeService = Depends(get_youtube_service)
):

This pattern enables:

  • Testability: Services can be mocked in unit tests by overriding dependencies
  • Lazy initialization: Service instances are created only when endpoints are called
  • Scope management: Each request gets its own service instance
  • Future extensibility: Service construction can be enhanced (e.g., connection pooling, caching) without changing router code

Agent-Related Routers

Two routers provide AI agent capabilities and are documented in detail in Chapter 4:

  • React Agent Router (/api/genai/react): Implements conversational AI with dynamic tool selection using LangGraph orchestration. See 4.1.
  • Browser Use Router (/api/agent): Generates structured JSON action plans for browser automation. See 4.2.

These routers represent the intelligence layer of the system, leveraging the LLM abstraction layer documented in 4.5.

Diagram: Complete Router-to-Service Mapping

Architecture Diagram