CoolFace
Apppublic

GivingTuesday/annotated-990

sourceHugging Faceunknownupdated 9mo agoView on Hugging Face
0likes
app.py84 linesDownload Raw Back to root
1import os2from fastapi import FastAPI, Request, HTTPException3from fastapi.responses import HTMLResponse4import httpx5from urllib.parse import urlencode6import uvicorn7 8app = FastAPI(9    docs_url=None, 10    redoc_url=None11)12 13# Access the secret environment variables14private_space_token = os.environ.get('api_key')15use_token = os.environ.get('use_token')16api_url = "https://givingtuesday-annotated-990-data.hf.space"17headers = {18    "Authorization": f"Bearer {private_space_token}",19    "Content-Type": "application/json"20}21 22@app.get('/')23async def root():24    return {"message": "990 API v1.0 running -- visit https://givingtuesday-annotated-990.hf.space/docs for usage"}25 26@app.get('/help/', response_class=HTMLResponse)27async def pass_docs_html():28    """BUG: the javascript renders THIS fastapi, not the html pulled. Use a static content page here"""29    async with httpx.AsyncClient(timeout=60.0) as client:30        response = await client.get(f"{api_url}/docs#/default/get_eins_eins__get", headers=headers)31        html_content = response.text32        print(f"DEBUG: {html_content}")33        return HTMLResponse(content=html_content, status_code=200)34            35    """36    # Use httpx to make an asynchronous GET request to the private API37    try:38        async with httpx.AsyncClient(timeout=60.0) as client:39            response = await client.get(f"{api_url}/docs/", headers=headers)40            response.raise_for_status() # Raise an exception for 4xx/5xx responses41            html_content = response.text42            return HTMLResponse(content=html_content, status_code=200)43            44    except httpx.HTTPStatusError as e:45        raise HTTPException(status_code=response.status_code, detail=f"Error: {str(e)}")46    except httpx.RequestError as e:47        raise HTTPException(status_code=500, detail=f"Network error: {str(e)}")48    """49 50@app.get("/eins/")51async def proxy_request(request: Request):52    # Capture all query parameters from the incoming request53    query_params = request.query_params54    55    # check access token match56    if 'key' in query_params and query_params['key'] == use_token:57        58        # private API doesn't handle token59        query_params = dict(query_params)60        query_params.pop('key')61        # Encode the parameters for the new URL62        encoded_params = urlencode(query_params)        63        # Construct the full URL for the private space endpoint64        private_api_url = f"{api_url}/eins/?{encoded_params}"65        66        # Use httpx to make an asynchronous GET request to the private API        67        try:68            print('params', private_api_url)69            async with httpx.AsyncClient(timeout=60.0) as client:70                response = await client.get(private_api_url, headers=headers)71                response.raise_for_status() # Raise an exception for 4xx/5xx responses72                return response.json()73                74        except httpx.HTTPStatusError as e:75            raise HTTPException(status_code=response.status_code, detail=f"Error: {str(e)}")76        except httpx.RequestError as e:77            raise HTTPException(status_code=500, detail=f"Network error: {str(e)}")78    else:79        return {"error": "access token required"}80 81if __name__ == "__main__":82    uvicorn.run(app, host="0.0.0.0", port=7860)83 84