Простой прокси на FastAPI для API OpenRouter

Это простой HTTP-прокси на FastAPI, который пересылает запросы в API OpenRouter практически без изменений.

Установка

pip install fastapi uvicorn httpx

Как выглядит поток

Код

from fastapi import FastAPI, Request
from fastapi.responses import Response
import httpx

app = FastAPI()

OPENROUTER_BASE = "https://openrouter.ai/api/v1"


@app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"])
async def proxy(path: str, request: Request):
    body = await request.body()

    headers = dict(request.headers)

    headers.pop("host", None)

    auth = request.headers.get("authorization")
    if auth:
        headers["authorization"] = auth

    url = f"{OPENROUTER_BASE}/{path}"

    async with httpx.AsyncClient() as client:
        response = await client.request(
            method=request.method,
            url=url,
            content=body,
            headers=headers,
            params=request.query_params,
            timeout=120
        )

    return Response(
        content=response.content,
        status_code=response.status_code,
        headers={
            k: v for k, v in response.headers.items()
            if k.lower() not in [
                "content-length",
                "transfer-encoding",
                "connection"
            ]
        },
        media_type=response.headers.get("content-type")
    )

Запуск

uvicorn proxy:app --host 0.0.0.0 --port 8000