🚪 API Gateway

api-gateway-ocelot-gateway-guide

Configuration d'Ocelot comme API Gateway en .NET — routing, aggregation, rate limiting, load balancing et intégration Consul/Kubernetes.

⚡ Installation & lancement en 1 commande

Copiez-collez dans votre terminal : le skill s'installe dans ~/.claude/skills et Claude Code se lance directement dessus.

macOS / Linux
curl -fsSL https://raw.githubusercontent.com/khalilbenaz/claude-skills-collection/main/install.sh | sh -s -- api-gateway-ocelot-gateway-guide --launch
Windows (PowerShell)
iex "& { $(iwr -useb https://raw.githubusercontent.com/khalilbenaz/claude-skills-collection/main/install.ps1) } api-gateway-ocelot-gateway-guide -Launch"

🚀 Déjà installé ?

claude "/api-gateway-ocelot-gateway-guide"

Ou tapez /api-gateway-ocelot-gateway-guide dans une session Claude Code, ou décrivez simplement votre besoin — le skill se déclenche automatiquement via le skill-router.

🔑 Déclencheurs automatiques

Le skill s'active automatiquement quand votre demande contient :

OcelotOcelot gatewayocelot.jsonAPI gateway Ocelotrouting Ocelotaggregation Ocelot

📦 Installation manuelle

git clone https://github.com/khalilbenaz/claude-skills-collection.git cp -r claude-skills-collection/skills/api-gateway-ocelot-gateway-guide ~/.claude/skills/

Payload du plugin : skills/api-gateway-ocelot-gateway-guide · source éditable : api-gateway-skills/ocelot-gateway-guide

📖 Manuel

Guide Ocelot API Gateway

Workflow — mise en place pas à pas

1. Installer les packages

dotnet add package Ocelot                          # Core — toujours requis
dotnet add package Ocelot.Provider.Consul          # Service Discovery Consul
dotnet add package Ocelot.Provider.Eureka          # Service Discovery Eureka
dotnet add package Ocelot.Cache.CacheManager       # Cache distribué
dotnet add package Ocelot.Tracing.OpenTracing      # Tracing distribué

2. Brancher Ocelot dans Program.cs

// Program.cs (.NET 8+)
var builder = WebApplication.CreateBuilder(args);

// Charge ocelot.json en priorité sur appsettings.json
builder.Configuration
    .AddJsonFile("ocelot.json", optional: false, reloadOnChange: true)
    .AddJsonFile($"ocelot.{builder.Environment.EnvironmentName}.json",
                 optional: true, reloadOnChange: true);

builder.Services
    .AddOcelot(builder.Configuration)
    .AddCacheManager(x => x.WithDictionaryHandle())  // cache en mémoire
    .AddConsul()                                      // si Consul utilisé
    ;

builder.Services.AddAuthentication()
    .AddJwtBearer("Bearer", options =>
    {
        options.Authority = builder.Configuration["Jwt:Authority"];
        options.Audience  = builder.Configuration["Jwt:Audience"];
    });

var app = builder.Build();
await app.UseOcelot();
app.Run();

3. Définir les routes dans ocelot.json

Chaque route = un objet dans "Routes". Minima obligatoires :

{
  "Routes": [
    {
      "DownstreamPathTemplate": "/api/payments/{everything}",
      "DownstreamScheme": "https",
      "DownstreamHostAndPorts": [
        { "Host": "payment-service", "Port": 8080 }
      ],
      "UpstreamPathTemplate": "/payments/{everything}",
      "UpstreamHttpMethod": ["GET", "POST", "PUT", "DELETE"],

      "AuthenticationOptions": {
        "AuthenticationProviderKey": "Bearer"
      },

      "RateLimitOptions": {
        "EnableRateLimiting": true,
        "Period": "1m",
        "PeriodTimespan": 60,
        "Limit": 100
      },

      "QoSOptions": {
        "ExceptionsAllowedBeforeBreaking": 3,
        "DurationOfBreak": 10000,
        "TimeoutValue": 5000
      },

      "FileCacheOptions": {
        "TtlSeconds": 30,
        "Region": "payments"
      }
    },
    {
      "DownstreamPathTemplate": "/api/orders/{everything}",
      "DownstreamScheme": "https",
      "DownstreamHostAndPorts": [
        { "Host": "order-svc-1", "Port": 8080 },
        { "Host": "order-svc-2", "Port": 8080 }
      ],
      "UpstreamPathTemplate": "/orders/{everything}",
      "UpstreamHttpMethod": ["GET", "POST"],
      "LoadBalancerOptions": { "Type": "RoundRobin" }
    }
  ],
  "GlobalConfiguration": {
    "BaseUrl": "https://api.company.com",
    "RateLimitOptions": {
      "DisableRateLimitHeaders": false,
      "QuotaExceededMessage": "Trop de requêtes, réessayez plus tard",
      "HttpStatusCode": 429
    }
  }
}

4. Aggregation de requêtes

Agrège plusieurs appels downstream en une seule réponse upstream. Utiliser la clé "Key" sur chaque route participante :

{
  "Routes": [
    {
      "DownstreamPathTemplate": "/api/users/{userId}",
      "UpstreamPathTemplate": "/users/{userId}",
      "DownstreamHostAndPorts": [{ "Host": "user-svc", "Port": 8080 }],
      "Key": "user"
    },
    {
      "DownstreamPathTemplate": "/api/orders?userId={userId}",
      "UpstreamPathTemplate": "/users/{userId}/orders",
      "DownstreamHostAndPorts": [{ "Host": "order-svc", "Port": 8080 }],
      "Key": "orders"
    }
  ],
  "Aggregates": [
    {
      "RouteKeys": ["user", "orders"],
      "UpstreamPathTemplate": "/users/{userId}/profile"
    }
  ]
}
Limite : l'agrégation ne supporte que GET. Pour des cas complexes (POST, transformation de payload), implémenter un custom IDefinedAggregator.

5. Service Discovery avec Consul

builder.Services.AddOcelot().AddConsul();
{
  "Routes": [
    {
      "DownstreamPathTemplate": "/api/{everything}",
      "UpstreamPathTemplate": "/payments/{everything}",
      "ServiceName": "payment-service",
      "LoadBalancerOptions": { "Type": "LeastConnection" }
    }
  ],
  "GlobalConfiguration": {
    "ServiceDiscoveryProvider": {
      "Scheme": "http",
      "Host": "consul",
      "Port": 8500,
      "Type": "Consul",
      "PollingInterval": 5000
    }
  }
}

6. Headers et claims transformation

{
  "AddHeadersToRequest": {
    "X-Tenant-Id": "Claims[tenant_id] > value"
  },
  "AddClaimsToRequest": {
    "sub": "Claims[sub] > value"
  },
  "AddQueriesToRequest": {
    "clientId": "Claims[client_id] > value"
  },
  "UpstreamHeaderTransform": {
    "X-Forwarded-For": "{RemoteIpAddress}"
  },
  "DownstreamHeaderTransform": {
    "Location": "{DownstreamBaseUrl}/{UpstreamBaseUrl}"
  }
}

7. Middleware personnalisé

// Middleware de corrélation avant Ocelot
app.Use(async (ctx, next) =>
{
    ctx.Request.Headers["X-Correlation-Id"] =
        ctx.Request.Headers.TryGetValue("X-Correlation-Id", out var existing)
            ? existing.ToString()
            : Guid.NewGuid().ToString("N");
    await next();
});

await app.UseOcelot();

Critères de décision — Ocelot vs YARP

CritèreOcelotYARP
ConfigurationJSON déclaratifCode + config
Aggregation intégréeOuiNon (custom)
Service DiscoveryConsul, EurekaCustom
PerformanceBonneExcellente (Microsoft)
MaintenanceCommunautéMicrosoft officiel
Courbe d'apprentissageFaibleMoyenne
Cas d'usageÉquipes petites/moyennes, config déclarativeProxy haute performance, finops

Choisir Ocelot si : config JSON suffisante, aggregation native requise, équipe habituée au routing déclaratif. Choisir YARP si : throughput critique (>50k req/s), besoin de transformations complexes en code.

Garde-fous et anti-patterns

Ne pas faire :

Pièges courants :

Bonnes pratiques 2026