Advertisement
Radeen10-_

fastapi proxy

Mar 16th, 2025 (edited)
386
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.38 KB | Gaming | 0 0
  1. from fastapi import FastAPI, HTTPException, Path, Body
  2. import httpx
  3. import json
  4. from pydantic import BaseModel
  5. from typing import Any, Dict, List
  6.  
  7. app = FastAPI()
  8.  
  9. # The base URL of the target service
  10. TARGET_BASE_URL = "http://20.212.243.159:7800"
  11.  
  12. # Pydantic model for the request body
  13. class AnswerRequest(BaseModel):
  14.     answer: str
  15.    
  16. # Pydantic model for the sync database request
  17. class SyncDatabaseRequest(BaseModel):
  18.     mode: str
  19.     test_users: List[str]
  20.  
  21. @app.post("/api/forms/{form_id}/{user_id}/answer")
  22. async def proxy_answer(
  23.     form_id: str = Path(..., description="Form ID"),
  24.     user_id: str = Path(..., description="User ID"),
  25.     request_data: AnswerRequest = Body(...)
  26. ):
  27.     """
  28.    Proxy endpoint that forwards form answer requests to the target service.
  29.    """
  30.     target_url = f"{TARGET_BASE_URL}/api/forms/{form_id}/{user_id}/answer"
  31.    
  32.     try:
  33.         async with httpx.AsyncClient() as client:
  34.             response = await client.post(
  35.                 target_url,
  36.                 json={"answer": request_data.answer},
  37.                 headers={
  38.                     "Content-Type": "application/json",
  39.                     "accept": "application/json"
  40.                 }
  41.             )
  42.            
  43.             # Return the response from the target service
  44.             return response.json()
  45.     except httpx.HTTPError as e:
  46.         raise HTTPException(status_code=500, detail=f"Error forwarding request: {str(e)}")
  47.  
  48. @app.post("/api/sync-database")
  49. async def sync_database(
  50.     request_data: SyncDatabaseRequest = Body(...)
  51. ):
  52.     """
  53.    Proxy endpoint that forwards database synchronization requests to the target service.
  54.    """
  55.     target_url = f"{TARGET_BASE_URL}/api/sync-database"
  56.    
  57.     try:
  58.         async with httpx.AsyncClient() as client:
  59.             response = await client.post(
  60.                 target_url,
  61.                 json={
  62.                     "mode": request_data.mode,
  63.                     "test_users": request_data.test_users
  64.                 },
  65.                 headers={
  66.                     "Content-Type": "application/json",
  67.                     "accept": "application/json"
  68.                 }
  69.             )
  70.            
  71.             # Return the response from the target service
  72.             return response.json()
  73.     except httpx.HTTPError as e:
  74.         raise HTTPException(status_code=500, detail=f"Error forwarding request: {str(e)}")
  75.  
  76. @app.get("/api/forms/{form_id}/{user_id}/current-question")
  77. async def get_current_question(
  78.     form_id: str = Path(..., description="Form ID"),
  79.     user_id: str = Path(..., description="User ID")
  80. ):
  81.     """
  82.    Proxy endpoint that forwards requests to get the current question from the target service.
  83.    """
  84.     target_url = f"{TARGET_BASE_URL}/api/forms/{form_id}/{user_id}/current-question"
  85.    
  86.     try:
  87.         async with httpx.AsyncClient() as client:
  88.             response = await client.get(
  89.                 target_url,
  90.                 headers={
  91.                     "accept": "application/json"
  92.                 }
  93.             )
  94.            
  95.             # Return the response from the target service
  96.             return response.json()
  97.     except httpx.HTTPError as e:
  98.         raise HTTPException(status_code=500, detail=f"Error forwarding request: {str(e)}")
  99.  
  100. if __name__ == "__main__":
  101.     import uvicorn
  102.     uvicorn.run(app, host="0.0.0.0", port=8000)
  103.  
  104.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement