gaganyatri commited on
Commit
fb0b173
·
verified ·
1 Parent(s): 5c797ac

Update src/server/main.py

Browse files
Files changed (1) hide show
  1. src/server/main.py +25 -4
src/server/main.py CHANGED
@@ -2,20 +2,41 @@ from fastapi import FastAPI, Request, HTTPException
2
  from fastapi.responses import Response
3
  import httpx
4
  import os
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  # FastAPI app setup
6
  app = FastAPI(
7
  title="Dhwani API Proxy",
8
- description="A proxy that forwards all requests to a target server.",
9
  version="1.0.0",
10
  redirect_slashes=False,
11
  )
12
 
13
- # Target server to forward requests to
14
- TARGET_SERVER = os.getenv("DWANI_API_BASE_URL") # Replace with the actual target server IP and port
 
15
 
 
 
16
 
17
- # Catch-all route to forward all requests
18
  @app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS", "HEAD"])
 
19
  async def proxy(request: Request, path: str):
20
  # Construct the target URL
21
  target_url = f"{TARGET_SERVER}/{path}"
 
2
  from fastapi.responses import Response
3
  import httpx
4
  import os
5
+ from slowapi import Limiter, _rate_limit_exceeded_handler
6
+ from slowapi.errors import RateLimitExceeded
7
+
8
+ # Custom key function to extract api_key from headers or query params
9
+ def get_api_key(request: Request) -> str:
10
+ # Check headers first
11
+ api_key = request.headers.get("X-API-Key")
12
+ if not api_key:
13
+ # Fallback to query parameters
14
+ api_key = request.query_params.get("api_key")
15
+ if not api_key:
16
+ raise HTTPException(status_code=400, detail="API key is required in 'X-API-Key' header or 'api_key' query parameter")
17
+ return api_key
18
+
19
+ # Initialize rate limiter with custom key function
20
+ limiter = Limiter(key_func=get_api_key)
21
+
22
  # FastAPI app setup
23
  app = FastAPI(
24
  title="Dhwani API Proxy",
25
+ description="A proxy that forwards all requests to the Dhwani API target server.",
26
  version="1.0.0",
27
  redirect_slashes=False,
28
  )
29
 
30
+ # Add rate limit exceeded handler
31
+ app.state.limiter = limiter
32
+ app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
33
 
34
+ # Target server to forward requests to
35
+ TARGET_SERVER = os.getenv("DWANI_API_BASE_URL", "http://localhost:8000")
36
 
37
+ # Catch-all route to forward all requests with rate limiting
38
  @app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS", "HEAD"])
39
+ @limiter.limit("5/minute") # Limit to 100 requests per minute per api_key
40
  async def proxy(request: Request, path: str):
41
  # Construct the target URL
42
  target_url = f"{TARGET_SERVER}/{path}"