MMLib.SwaggerForOcelot

repository·master·Indexed 18 days ago

https://github.com/burgyn/mmlib.swaggerforocelot

A library that integrates Swashbuckle.AspNetCore with Ocelot to aggregate and serve OpenAPI documentation from multiple downstream microservices through a single API Gateway. It provides a unified Swagger UI with paths automatically rewritten to match upstream gateway routes, support for Ocelot Request Aggregation documentation, and the ability to generate documentation for the gateway itself.

Tokens
5.1K
Snippets
18
Records
18
Agent score
13%

What's inside MMLib.SwaggerForOcelot

  1. Use Service Discovery for Swagger Configuration

    master

    If you use an Ocelot Service Discovery Provider, you can use the service name in your Swagger configuration instead of hardcoded hosts and ports. In the SwaggerEndPoints section, use the Service object containing the Name (matching the Ocelot ServiceName) and the Path to the swagger JSON.

    "Routes": [
      {
        "DownstreamPathTemplate": "/api/{everything}",
        "ServiceName": "projects",
        "UpstreamPathTemplate": "/api/project/{everything}",
        "UpstreamHttpMethod": [ "Get" ],
        "SwaggerKey": "projects"
      }
    ],
    "SwaggerEndPoints": [
        {
          "Key": "projects",
          "Config": [
            {
              "Name": "Projects API",
              "Version": "v1",
              "Service": {
                "Name": "projects",
                "Path": "/swagger/v1/swagger.json"
              }
            }
          ]
        }
    ]
  2. Get Started with SwaggerForOcelot

    master

    SwaggerForOcelot allows you to view and use Swagger documentation for downstream services directly through your Ocelot API Gateway. It aggregates downstream OpenAPI docs and modifies addresses to match the UpstreamPathTemplate defined in your Ocelot configuration.

    Prerequisites

    1. Ensure your downstream services have Swashbuckle.AspNetCore configured to generate Swagger JSON.
    2. Install the NuGet package in your ASP.NET Core Ocelot project: dotnet add package MMLib.SwaggerForOcelot
    dotnet add package MMLib.SwaggerForOcelot
  3. Configure SwaggerForOcelot in ocelot.json

    master

    To map downstream Swagger endpoints to Ocelot routes, you must configure both Routes and SwaggerEndPoints in your ocelot.json file.

    • Routes: Add a SwaggerKey to the route to link it to a specific Swagger endpoint definition.
    • SwaggerEndPoints: Define the Key (matching the SwaggerKey in routes), the Name (displayed in the UI), and the Url (the downstream service's swagger JSON path).
    • GlobalConfiguration: Use BaseUrl to define the gateway's base URL.
     {
      "Routes": [
        {
          "DownstreamPathTemplate": "/api/{everything}",
          "DownstreamScheme": "http",
          "DownstreamHostAndPorts": [
            {
              "Host": "localhost",
              "Port": 5100
            }
          ],
          "UpstreamPathTemplate": "/api/contacts/{everything}",
          "UpstreamHttpMethod": [ "Get" ],
          "SwaggerKey": "contacts"
        }
      ],
      "SwaggerEndPoints": [
        {
          "Key": "contacts",
          "Config": [
            {
              "Name": "Contacts API",
              "Version": "v1",
              "Url": "http://localhost:5100/swagger/v1/swagger.json"
            }
          ]
        }
      ],
      "GlobalConfiguration": {
        "BaseUrl": "http://localhost"
      }
    }
  4. Generate documentation for Ocelot Aggregates

    master

    If you use Ocelot's Request Aggregation feature, you can generate documentation for these aggregate endpoints by enabling the GenerateDocsForAggregates option in your AddSwaggerForOcelot configuration. The documentation will appear on a custom Aggregates page in the Swagger UI.

    services.AddSwaggerForOcelot(Configuration,
      (o) =>
      {
          o.GenerateDocsForAggregates = true;
      });
  5. Register and Use SwaggerForOcelot Middleware

    master

    In your ASP.NET Core application, you need to register the generator in ConfigureServices and use the middleware in Configure.

    Registration

    Use services.AddSwaggerForOcelot(Configuration) in Startup.cs.

    Middleware

    Use app.UseSwaggerForOcelotUI(...) to expose the interactive documentation. You can customize the PathToSwaggerGenerator (defaults to /swagger/docs).

    // In ConfigureServices
    services.AddSwaggerForOcelot(Configuration);
    
    // In Configure
    app.UseSwaggerForOcelotUI(opt => {
      opt.PathToSwaggerGenerator = "/swagger/docs";
    });
  6. Merge Ocelot configuration files

    master

    To load Ocelot configuration from multiple files (e.g., ocelot.exampleName.json), use the AddOcelotWithSwaggerSupport extension in your ConfigureAppConfiguration block.

    Key configuration options for the extension:

    • FileOfSwaggerEndPoints: Set the name of the file containing Swagger endpoint settings (default is ocelot.SwaggerEndPoints.json). Use the name without the .json extension.
    • Folder: Specify a directory where configuration files are located.
    • Environment: Pass the IWebHostEnvironment to support environment-specific files.
    • PrimaryOcelotConfigFile: Specify a name other than ocelot.json for the main configuration file.
    WebHost.CreateDefaultBuilder(args)
      .ConfigureAppConfiguration((hostingContext, config) =>
      {
         config.AddOcelotWithSwaggerSupport((o) => {
           o.Folder = "Configuration";
           o.Environment = hostingContext.HostingEnvironment;
         });
      })
      .UseStartup<Startup>();
  7. Generate security definitions from Ocelot configuration

    master

    You can automatically generate Swagger security definitions based on your Ocelot route configuration:

    1. Add AuthenticationOptions to your route in ocelot.json using an AuthenticationProviderKey.
    2. In Startup.cs, map that AuthenticationProviderKey to a specific security definition name using AddAuthenticationProviderKeyMapping.
    // ocelot.json
    "Routes": [
      {
        "DownstreamPathTemplate": "/api/{everything}",
        "ServiceName": "projects",
        "UpstreamPathTemplate": "/api/project/{everything}",
        "SwaggerKey": "projects",
        "AuthenticationOptions": {
          "AuthenticationProviderKey": "Bearer",
          "AllowedScopes": [ "scope" ]
        }
      }
    ]
    // Startup.cs
    services.AddSwaggerForOcelot(Configuration,
      (o) =>
      {
        o.AddAuthenticationProviderKeyMapping("Bearer", "appAuth");
      });
  8. Map parameter names for Ocelot Aggregations

    master

    When aggregating services where parameter names differ (e.g., {id} in one service and {buyerId} in another), use the ParametersMap property in your Ocelot configuration. The key is the parameter name used in the Ocelot configuration, and the value is the parameter name used in the downstream service.

    {
      "DownstreamPathTemplate": "/api/basket/{id}",
      "UpstreamPathTemplate": "/gateway/api/basket/{id}",
      "ParametersMap": {
        "id": "buyerId"
      },
      "ServiceName": "basket",
      "SwaggerKey": "basket",
      "Key": "basket"
    }
  9. Enable caching for downstream documentation

    master

    To improve performance when downstream documentation is large, enable caching by setting the DownstreamDocsCacheExpire property in the AddSwaggerForOcelot setup. The cache will automatically refresh if the downstream documentation changes.

    services.AddSwaggerForOcelot(Configuration,
                setup =>
                {
                    setup.DownstreamDocsCacheExpire = TimeSpan.FromMinutes(10);
                });
  10. Enable OpenAPI Servers from Downstream Services

    master

    If your downstream services define multiple servers or use server templating that you want to preserve on the gateway, set TakeServersFromDownstreamService to true in the SwaggerEndPoints configuration.

    Note: When this is enabled, the server path is not used to transform the paths of individual endpoints.

    "SwaggerEndPoints": [
        {
          "Key": "users",
          "TakeServersFromDownstreamService": true,
          "Config": [
            {
              "Name": "Users API",
              "Version": "v1",
              "Service": {
                "Name": "users",
                "Path": "/swagger/v1/swagger.json"
              }
            }
          ]
        }
    ]
  11. Customize Ocelot Aggregate descriptions

    master

    By default, descriptions are pulled from downstream documentation. To provide a custom description for an aggregate route, add a Description field to the aggregate object in your ocelot.json configuration.

    "Aggregates": [ 
      {
        "RouteKeys": [
          "user",
          "basket"
        ],
        "Description": "Custom description for this aggregate route.",
        "Aggregator": "BasketAggregator",
        "UpstreamPathTemplate": "/gateway/api/basketwithuser/{id}"
      }
    ]
  12. Configure Virtual Directories for Downstream Services

    master

    If a downstream service is hosted within a virtual directory (e.g., /project/api/...), you must set the VirtualDirectory property in the Ocelot route configuration to ensure paths are correctly replaced.

     {
      "DownstreamPathTemplate": "/project/api/{everything}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
          {
            "Host": "localhost",
            "Port": 5100
          }
      ],
      "UpstreamPathTemplate": "/api/project/{everything}",
      "UpstreamHttpMethod": [ "Get" ],
      "SwaggerKey": "project",
      "VirtualDirectory":"/project"
    }