AGI-FORWARD / app.py
AEUPH's picture
Create app.py
4ca46dc verified
raw
history blame
1.37 kB
from fastapi import FastAPI, Request
import httpx
from starlette.responses import RedirectResponse
app = FastAPI()
@app.get("/forward/")
async def forward(request: Request):
# Extract query parameters as a dictionary
query_params = dict(request.query_params)
# Extract the URL to forward to (param1)
forward_url = query_params.pop('param1', None)
# Check if the forward URL is present
if not forward_url:
return {"error": "param1 (forward URL) is required"}
# Prepare the new URL with remaining query parameters
# This assumes that the forward URL does not already have query parameters.
if query_params: # If there are other parameters to forward
params_as_str = "&".join([f"{key}={value}" for key, value in query_params.items()])
forward_url_with_params = f"{forward_url}?{params_as_str}"
else:
forward_url_with_params = forward_url
# Forward the request to the new URL using httpx for asynchronous HTTP requests
async with httpx.AsyncClient() as client:
response = await client.get(forward_url_with_params)
# For simplicity, we're directly returning the response from the forwarded URL
# In a real application, you might want to handle different response scenarios
return response.json()
# To run the server:
# uvicorn app:app --reload