Spaces:
Running
Running
from fastapi import FastAPI, Request, Header, HTTPException | |
import httpx | |
app = FastAPI() | |
# Replace with your actual backend API key and base URL | |
API_KEY = "sk-qO9N6kQEEULMWtF4YGVlTTSjIPllEm1h1wfEBzSmnSbxiXwe" | |
BASE_URL = "https://fast.typegpt.net" | |
# Public API key for users to use | |
PUBLIC_API_KEY = "TypeGPT-Free4ALL" | |
async def proxy(request: Request, path: str, x_api_key: str = Header(None)): | |
# Check if the public API key matches the expected value | |
if x_api_key != PUBLIC_API_KEY: | |
raise HTTPException(status_code=401, detail="Invalid API key. Please use 'TypeGPT-Free4ALL'.") | |
# Reconstruct full URL to target endpoint | |
target_url = f"{BASE_URL}/{path}" | |
# Prepare headers from the incoming request | |
headers = dict(request.headers) | |
headers["Authorization"] = f"Bearer {API_KEY}" # Add your secret API key here | |
headers.pop("host", None) # Remove host header to avoid conflicts | |
# Get the body of the request if present | |
body = await request.body() | |
# Make the actual request to the backend API | |
async with httpx.AsyncClient() as client: | |
response = await client.request( | |
request.method, | |
target_url, | |
content=body, | |
headers=headers | |
) | |
# Return the response back to the user | |
return response.json() | |