Skip to content

Instantly share code, notes, and snippets.

@BlackHacked
Forked from walnutwaldo/README.md
Created March 24, 2025 08:49
Show Gist options
  • Save BlackHacked/116485650c8bb4a1a84acad33f626d68 to your computer and use it in GitHub Desktop.
Save BlackHacked/116485650c8bb4a1a84acad33f626d68 to your computer and use it in GitHub Desktop.
FastAPI Proxy

FastAPI HTTP Proxy Application

Introduction

This FastAPI application serves as an HTTP proxy, forwarding client requests to an upstream API server and relaying the server's response back to the client. It supports arbitrary paths and HTTP methods, providing a versatile proxy solution for various API interactions.

Requirements

  • Python 3.6 or higher
  • FastAPI
  • Uvicorn
  • HTTPX

Installation

  1. Clone the repository to your local machine.
  2. Navigate to the project directory.
  3. Create a virtual environment:
    python3 -m venv venv
    
  4. Activate the virtual environment:
    source venv/bin/activate
    
  5. Install the necessary packages:
    pip install fastapi uvicorn httpx
    

Usage

To launch the proxy server, execute the following command within the project directory:

uvicorn proxy_app:app --reload

The server will be accessible at http://127.0.0.1:8000. To route requests through the proxy, direct them to the proxy server, specifying the desired path and method. The proxy will then forward the request to the matching path on the upstream API server.

Troubleshooting

Should you encounter any problems, verify the following:

  • The virtual environment is active.
  • All required dependencies have been installed.
  • The server is operational and reachable.

For more specific error information, consult the server logs for detailed stack traces and error messages.

from fastapi import FastAPI, Request, HTTPException
import httpx
from starlette.responses import JSONResponse
app = FastAPI()
# Mock upstream API endpoint
@app.post('/mock-upstream-api/')
async def mock_upstream_api(request: Request):
request_data = await request.json()
# This is where you would add logic to handle the request and generate a response
# For now, we'll just return the request data as the response
return JSONResponse(content=request_data)
# Proxy endpoint to handle arbitrary paths
@app.api_route('/{proxy_path:path}', methods=['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'HEAD', 'PATCH', 'TRACE'])
async def proxy(request: Request, proxy_path: str):
try:
# Parse the incoming JSON request data if any
if request.method in ["POST", "PUT", "PATCH"]:
request_data = await request.json()
else:
request_data = None
# Define the mock upstream API URL
upstream_url = f'http://127.0.0.1:8000/{proxy_path}'
# Forward the request to the mock upstream API
async with httpx.AsyncClient() as client:
if request_data:
response = await client.request(request.method, upstream_url, json=request_data)
else:
response = await client.request(request.method, upstream_url)
# Return the response from the mock upstream API
return JSONResponse(content=response.json(), status_code=response.status_code)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment