import os from fastapi import FastAPI, Request, HTTPException from fastapi.responses import HTMLResponse import httpx from urllib.parse import urlencode import uvicorn app = FastAPI( docs_url=None, redoc_url=None ) # Access the secret environment variables private_space_token = os.environ.get('api_key') use_token = os.environ.get('use_token') api_url = "https://givingtuesday-annotated-990-data.hf.space" headers = { "Authorization": f"Bearer {private_space_token}", "Content-Type": "application/json" } @app.get('/') async def root(): return {"message": "990 API v1.0 running -- visit https://givingtuesday-annotated-990.hf.space/docs for usage"} @app.get('/help/', response_class=HTMLResponse) async def pass_docs_html(): """BUG: the javascript renders THIS fastapi, not the html pulled. Use a static content page here""" async with httpx.AsyncClient(timeout=60.0) as client: response = await client.get(f"{api_url}/docs#/default/get_eins_eins__get", headers=headers) html_content = response.text print(f"DEBUG: {html_content}") return HTMLResponse(content=html_content, status_code=200) """ # Use httpx to make an asynchronous GET request to the private API try: async with httpx.AsyncClient(timeout=60.0) as client: response = await client.get(f"{api_url}/docs/", headers=headers) response.raise_for_status() # Raise an exception for 4xx/5xx responses html_content = response.text return HTMLResponse(content=html_content, status_code=200) except httpx.HTTPStatusError as e: raise HTTPException(status_code=response.status_code, detail=f"Error: {str(e)}") except httpx.RequestError as e: raise HTTPException(status_code=500, detail=f"Network error: {str(e)}") """ @app.get("/eins/") async def proxy_request(request: Request): # Capture all query parameters from the incoming request query_params = request.query_params # check access token match if 'key' in query_params and query_params['key'] == use_token: # private API doesn't handle token query_params = dict(query_params) query_params.pop('key') # Encode the parameters for the new URL encoded_params = urlencode(query_params) # Construct the full URL for the private space endpoint private_api_url = f"{api_url}/eins/?{encoded_params}" # Use httpx to make an asynchronous GET request to the private API try: print('params', private_api_url) async with httpx.AsyncClient(timeout=60.0) as client: response = await client.get(private_api_url, headers=headers) response.raise_for_status() # Raise an exception for 4xx/5xx responses return response.json() except httpx.HTTPStatusError as e: raise HTTPException(status_code=response.status_code, detail=f"Error: {str(e)}") except httpx.RequestError as e: raise HTTPException(status_code=500, detail=f"Network error: {str(e)}") else: return {"error": "access token required"} if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=7860)