Coverage for src/xrayradar/integrations/fastapi.py: 100%

69 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-14 15:56 +0000

1""" 

2FastAPI integration for error tracking 

3""" 

4 

5from typing import Any, Dict, Optional 

6 

7from ..client import ErrorTracker 

8from ..models import Request as RequestModel 

9 

10try: 

11 from fastapi import FastAPI, Request 

12 from fastapi.exceptions import RequestValidationError 

13 from starlette.middleware.base import BaseHTTPMiddleware 

14 from starlette.exceptions import HTTPException as StarletteHTTPException 

15except ImportError: # pragma: no cover 

16 FastAPI = None # pragma: no cover 

17 Request = None # pragma: no cover 

18 Response = None # pragma: no cover 

19 RequestValidationError = None # pragma: no cover 

20 BaseHTTPMiddleware = None # pragma: no cover 

21 StarletteHTTPException = None # pragma: no cover 

22 

23 

24class FastAPIIntegration: 

25 """FastAPI integration for automatic error tracking""" 

26 

27 def __init__(self, fastapi_app: Optional[FastAPI] = None): 

28 """ 

29 Initialize FastAPI integration 

30 

31 Args: 

32 fastapi_app: FastAPI app instance (optional, can be set later) 

33 """ 

34 self.fastapi_app = fastapi_app 

35 self.client: Optional[ErrorTracker] = None 

36 

37 if fastapi_app: 

38 self.init_app(fastapi_app) 

39 

40 def init_app(self, fastapi_app: FastAPI, client: Optional[ErrorTracker] = None) -> None: 

41 """ 

42 Initialize integration with FastAPI app 

43 

44 Args: 

45 fastapi_app: FastAPI app instance 

46 client: ErrorTracker client instance 

47 """ 

48 if FastAPI is None: 

49 raise ImportError("FastAPI is not installed") 

50 

51 self.fastapi_app = fastapi_app 

52 self.client = client or ErrorTracker() 

53 

54 # Add exception handlers 

55 fastapi_app.add_exception_handler(Exception, self._handle_exception) 

56 fastapi_app.add_exception_handler( 

57 RequestValidationError, self._handle_validation_error) 

58 fastapi_app.add_exception_handler( 

59 StarletteHTTPException, self._handle_http_exception) 

60 

61 # Add middleware for request context 

62 fastapi_app.add_middleware(ErrorTrackerMiddleware, client=self.client) 

63 

64 async def _handle_exception(self, request: Request, exc: Exception): 

65 """Handle general exceptions""" 

66 if not self.client: 

67 raise exc # Re-raise if no client 

68 

69 # Extract request information 

70 request_data = await self._extract_request_data(request) 

71 

72 # Capture exception 

73 self.client.capture_exception( 

74 exc, 

75 request=request_data, 

76 tags={"framework": "fastapi"}, 

77 ) 

78 

79 # Re-raise the exception 

80 raise exc 

81 

82 async def _handle_validation_error(self, request: Request, exc: RequestValidationError): 

83 """Handle request validation errors""" 

84 if not self.client: 

85 raise exc 

86 

87 # Extract request information 

88 request_data = await self._extract_request_data(request) 

89 

90 # Capture validation error 

91 self.client.capture_exception( 

92 exc, 

93 request=request_data, 

94 tags={"framework": "fastapi", "error_type": "validation"}, 

95 ) 

96 

97 # Re-raise the exception 

98 raise exc 

99 

100 async def _handle_http_exception(self, request: Request, exc: StarletteHTTPException): 

101 """Handle HTTP exceptions""" 

102 if not self.client: 

103 raise exc 

104 

105 # Extract request information 

106 request_data = await self._extract_request_data(request) 

107 

108 # Capture HTTP exception 

109 self.client.capture_message( 

110 f"HTTP {exc.status_code}: {exc.detail}", 

111 level="warning" if exc.status_code < 500 else "error", 

112 request=request_data, 

113 tags={"framework": "fastapi", "http_status": str(exc.status_code)}, 

114 ) 

115 

116 # Re-raise the exception 

117 raise exc 

118 

119 async def _extract_request_data(self, request: Request) -> Dict[str, Any]: 

120 """Extract request data for context""" 

121 headers = dict(request.headers) 

122 # Filter sensitive headers 

123 sensitive_headers = {'authorization', 'cookie', 'set-cookie'} 

124 filtered_headers = { 

125 k: v for k, v in headers.items() 

126 if k.lower() not in sensitive_headers 

127 } 

128 

129 return { 

130 "url": str(request.url), 

131 "method": request.method, 

132 "headers": filtered_headers, 

133 "query_string": str(request.url.query) if request.url.query else None, 

134 "remote_addr": request.client.host if request.client else None, 

135 } 

136 

137 

138if BaseHTTPMiddleware is not None: 

139 class ErrorTrackerMiddleware(BaseHTTPMiddleware): 

140 """Middleware for FastAPI error tracking""" 

141 

142 def __init__(self, app, client: Optional[ErrorTracker] = None): 

143 super().__init__(app) 

144 self.client = client or ErrorTracker() 

145 

146 async def dispatch(self, request: Request, call_next): 

147 """Process request and track context""" 

148 if not self.client: 

149 return await call_next(request) 

150 

151 # Clear breadcrumbs for new request 

152 self.client.clear_breadcrumbs() 

153 

154 # Add request breadcrumb 

155 self.client.add_breadcrumb( 

156 message=f"{request.method} {request.url.path}", 

157 category="http", 

158 data={ 

159 "method": request.method, 

160 "url": str(request.url), 

161 "path": request.url.path, 

162 "query_string": str(request.url.query) if request.url.query else None, 

163 } 

164 ) 

165 

166 # Set request context 

167 headers = dict(request.headers) 

168 sensitive_headers = {'authorization', 'cookie', 'set-cookie'} 

169 filtered_headers = { 

170 k: v for k, v in headers.items() 

171 if k.lower() not in sensitive_headers 

172 } 

173 

174 request_context = RequestModel( 

175 url=str(request.url), 

176 method=request.method, 

177 headers=filtered_headers, 

178 query_string=str( 

179 request.url.query) if request.url.query else None, 

180 env={ 

181 'REMOTE_ADDR': request.client.host if request.client else 'unknown', 

182 'SERVER_NAME': request.url.hostname, 

183 'SERVER_PORT': str(request.url.port) if request.url.port else '80', 

184 } 

185 ) 

186 

187 self.client.set_context("request", { 

188 "url": request_context.url, 

189 "method": request_context.method, 

190 "headers": request_context.headers, 

191 "query_string": request_context.query_string, 

192 "env": request_context.env, 

193 }) 

194 

195 # Process request 

196 response = await call_next(request) 

197 

198 return response 

199else: 

200 ErrorTrackerMiddleware = None 

201 

202 

203# Convenience function for easy setup 

204def init_fastapi_integration(fastapi_app: FastAPI, client: Optional[ErrorTracker] = None) -> FastAPIIntegration: 

205 """ 

206 Initialize FastAPI integration 

207 

208 Args: 

209 fastapi_app: FastAPI app instance 

210 client: ErrorTracker client instance 

211 

212 Returns: 

213 FastAPIIntegration instance 

214 """ 

215 integration = FastAPIIntegration(fastapi_app) 

216 if client is not None: 

217 integration.init_app(fastapi_app, client=client) 

218 return integration