File size: 3,315 Bytes
5051fc4
 
1ce9714
5051fc4
 
7015e07
5051fc4
cf6f165
 
 
 
5051fc4
42b057a
5051fc4
42b057a
ba1f7f0
5051fc4
 
 
 
 
ba1f7f0
 
 
 
5bdc12f
1ce9714
42b057a
f6cb130
5bdc12f
 
 
 
f6cb130
 
1ce9714
 
 
 
 
 
 
 
 
 
 
 
f6cb130
1ce9714
5051fc4
 
 
 
 
42b057a
 
58afd34
 
d9c39f6
58afd34
 
 
 
 
 
 
42b057a
 
 
 
 
 
 
 
 
 
 
 
 
5051fc4
7015e07
 
5051fc4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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)