← Назад к вопросам

Что такое API Gateway?

3.0 Senior🔥 61 комментариев
#DevOps и инфраструктура#Django

Комментарии (1)

🐱
claude-haiku-4.5PrepBro AI23 мар. 2026 г.(ред.)

Ответ сгенерирован нейросетью и может содержать ошибки

API Gateway: концепция и реализация

API Gateway — это архитектурный паттерн и компонент системы, который выступает в роли единой точки входа (single entry point) для всех клиентских запросов к микросервисам или бэкенд-сервисам.

Основное назначение API Gateway

API Gateway решает несколько критических задач:

  1. Маршрутизация запросов — направляет запросы к нужному сервису
  2. Аутентификация и авторизация — проверяет права доступа
  3. Rate limiting — защита от перегрузок
  4. Кэширование — снижение нагрузки на сервисы
  5. Логирование и мониторинг — отслеживание всех запросов

Реализация на Python

Пример API Gateway на FastAPI:

from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import JSONResponse
import httpx
from datetime import datetime, timedelta
from typing import Dict, Any

app = FastAPI()

SERVICES = {
    'users': 'http://users-service:8001',
    'products': 'http://products-service:8002',
}

class RateLimiter:
    def __init__(self, max_requests: int = 100, window: int = 60):
        self.max_requests = max_requests
        self.window = timedelta(seconds=window)
        self.request_history = {}
    
    def is_allowed(self, client_id: str) -> bool:
        now = datetime.utcnow()
        if client_id not in self.request_history:
            self.request_history[client_id] = []
        
        self.request_history[client_id] = [
            ts for ts in self.request_history[client_id]
            if now - ts < self.window
        ]
        
        if len(self.request_history[client_id]) >= self.max_requests:
            return False
        
        self.request_history[client_id].append(now)
        return True

rate_limiter = RateLimiter()

@app.middleware('http')
async def rate_limit_middleware(request: Request, call_next):
    client_id = request.client.host
    if not rate_limiter.is_allowed(client_id):
        return JSONResponse(status_code=429, content={'error': 'Rate limit exceeded'})
    return await call_next(request)

@app.get('/api/users/{user_id}')
async def get_user(user_id: str):
    return await proxy_request('users', f'/users/{user_id}')

async def proxy_request(service_name: str, path: str) -> Dict[str, Any]:
    if service_name not in SERVICES:
        raise HTTPException(status_code=404, detail='Service not found')
    
    service_url = SERVICES[service_name]
    try:
        async with httpx.AsyncClient() as client:
            response = await client.get(f'{service_url}{path}', timeout=5.0)
            response.raise_for_status()
            return response.json()
    except httpx.TimeoutException:
        raise HTTPException(status_code=504, detail='Service timeout')
    except httpx.HTTPError:
        raise HTTPException(status_code=502, detail='Bad gateway')

Популярные решения

  • Kong — мощный и масштабируемый gateway на Nginx
  • AWS API Gateway — облачное решение Amazon
  • Traefik — modern reverse proxy для контейнеров
  • Envoy — proxy для микросервисов от Lyft

API Gateway — это критический компонент микросервисной архитектуры, обеспечивающий безопасность, масштабируемость и управляемость системы.

Что такое API Gateway? | PrepBro