Skip to content

Instantly share code, notes, and snippets.

@umit
Last active January 5, 2026 15:48
Show Gist options
  • Select an option

  • Save umit/ee6a060991e909df8c6344cb9f8c6f08 to your computer and use it in GitHub Desktop.

Select an option

Save umit/ee6a060991e909df8c6344cb9f8c6f08 to your computer and use it in GitHub Desktop.
from fastapi import FastAPI, Request, HTTPException, Depends
from fastapi.responses import JSONResponse
import httpx
import jwt
import os
app = FastAPI()
# Backend servis URL'leri
SERVICES = {
'users': 'https://users-service.com',
'products': 'https://products-service.com',
'orders': 'https://orders-service.com'
}
# JWT Doğrulama
async def verify_token(request: Request):
auth_header = request.headers.get('Authorization')
if not auth_header or not auth_header.startswith('Bearer '):
raise HTTPException(status_code=401, detail='Missing token')
token = auth_header.replace('Bearer ', '')
try:
decoded = jwt.decode(token, os.environ['JWT_SECRET'], algorithms=['HS256'])
return decoded
except jwt.ExpiredSignatureError:
raise HTTPException(status_code=401, detail='Token expired')
except jwt.InvalidTokenError:
raise HTTPException(status_code=401, detail='Invalid token')
# Proxy tüm requestleri backend'e yönlendir
@app.api_route("/{service}/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
async def gateway_proxy(
service: str,
path: str,
request: Request,
user: dict = Depends(verify_token)
):
# Servis kontrolü
if service not in SERVICES:
raise HTTPException(status_code=404, detail='Service not found')
# Backend URL oluştur
backend_url = f"{SERVICES[service]}/{path}"
# Request body'yi al
body = await request.body()
# Headers'ı hazırla (user bilgisi ekle)
headers = dict(request.headers)
headers['X-User-Id'] = str(user['user_id'])
headers['X-User-Email'] = user['email']
# Backend'e istek at
async with httpx.AsyncClient() as client:
try:
response = await client.request(
method=request.method,
url=backend_url,
content=body,
headers=headers,
params=request.query_params
)
return JSONResponse(
content=response.json(),
status_code=response.status_code
)
except Exception as e:
raise HTTPException(status_code=502, detail=f'Backend error: {str(e)}')
# Public endpoints (auth gerektirmeyen)
@app.post("/auth/login")
async def login(request: Request):
body = await request.json()
# Kullanıcı doğrulama (database)
# ... user verification logic
# JWT üret
token = jwt.encode(
{
'user_id': 123,
'email': body['email'],
'exp': datetime.utcnow() + timedelta(hours=1)
},
os.environ['JWT_SECRET'],
algorithm='HS256'
)
return {'token': token}
@app.get("/health")
async def health():
return {'status': 'ok'}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment