Skip to Content
Cloud Engineering Academy
4. API Development & Integration

OpenAPI contracts and contract testing

Design the Account Information API in OpenAPI, generate it from ASP.NET Core 10, import it into API Gateway, generate a typed C# client with Kiota, and stop breaking changes with contract tests, Pact and oasdiff.

intermediate⏱ 1 h 30 min🟢 FreeDVA-C03SAA-C03

Assumes: .NET 10 LTS · Microsoft.AspNetCore.OpenApi 10.0.x · Microsoft.OpenApi.Kiota 1.x · PactNet 5.0.x · oasdiff · AWS CLI v2 · Region us-east-1. Verified against official sources on 2026-11-17.

Learning objectives

By the end of this lesson you can:

  • Compare design-first and code-first API development and choose one for a team.
  • Generate OpenAPI documents with Microsoft.AspNetCore.OpenApi in .NET 10 (OpenAPI 3.1 by default) and customise them with transformers (OAuth2 security, required headers, AWS extensions).
  • Produce an OpenAPI 3.0 variant that API Gateway REST API import accepts, with x-amazon-apigateway-integration and a Cognito authorizer.
  • Generate a typed C# client with Kiota.
  • Write contract tests (document assertions with WebApplicationFactory, consumer-driven contracts with PactNet) and block breaking changes in CI with oasdiff.

This lesson includes Lab 4.1: design the Account Information API in OpenAPI and generate a typed client.

Prerequisites

Why this matters in banking

Harbourline's mobile team, two fintech partners and an internal statements service all call the Account Information API. A developer renames bookingDate to bookedOn in a "small refactor". Unit tests pass, the release goes out, and a partner's reconciliation job silently stops matching transactions. Nobody broke a test because nobody had a contract — a machine-checkable description of what the API promises.

OpenAPI is that contract. Banks also use it as evidence: a published, versioned API description is what partner onboarding teams, security reviewers and (for Open Banking) conformance testers look at first.

The idea in plain language

An OpenAPI document is a JSON or YAML file that lists every path, method, parameter, request body, response, status code and security requirement of an HTTP API. Tools read it to generate documentation, client libraries, server stubs, gateway configuration and tests.

  • Design-first: write the OpenAPI file, review it like code, then implement the server to match it.
  • Code-first: write the server, let the framework generate the OpenAPI document from your endpoints, and treat the generated file as the contract.
  • Contract testing: automated checks that the implementation and the contract (and the consumers' expectations) still agree.

Analogy: The OpenAPI document is the product terms and conditions for your API. Design-first means legal drafts the terms before the product is built; code-first means the product team writes down what they built. Either way, once customers rely on the terms, changing them needs notice — and a contract test is the compliance check that catches an unannounced change.

What problem the AWS service solves

Amazon API Gateway can import an OpenAPI document to create or update a REST API — resources, methods, request validators, models (JSON Schema draft 4), authorizers and integrations — and can export one. That turns the contract into infrastructure.

Know the limits before you rely on it (checked 2026-11-17):

  • API Gateway supports most of OpenAPI 2.0 and 3.0. It does not list 3.1. ASP.NET Core in .NET 10 emits 3.1 by default, so you generate a separate 3.0 document for the gateway.
  • Not supported or ignored on import include discriminator, example, nullable, exclusiveMinimum, default, readOnly, deprecated, $ref to other files, format: decimal, and oneOf/anyOf/allOf that $ref a definition in the same schema in 3.0.
  • Root-level security is ignored: put security on each operation.
  • A securitySchemes entry must be of type apiKey; OAuth2/JWT validation is expressed with the x-amazon-apigateway-authorizer vendor extension (cognito_user_pools, token, request or jwt).
  • The definition file can be up to 6 MB; imports are rate-limited (one every 3 seconds per account for Regional APIs).
  • HTTP APIs also import OpenAPI 3.0, but have no request validation, so models matter less there.

Microsoft / Azure comparison

You know (Microsoft/Azure)AWS equivalentWhat's different
Swashbuckle / NSwag in older templatesMicrosoft.AspNetCore.OpenApi (built in since .NET 9).NET 10 defaults to OpenAPI 3.1 and supports YAML output
APIM "Import OpenAPI" with policies in XMLAPI Gateway import-rest-api with x-amazon-apigateway-* vendor extensionsIntegration, authorizer and validator settings live inside the OpenAPI file
APIM developer portalAPI Gateway developer portal (REST APIs) or your own docs siteMany teams publish the spec with Scalar or Redoc instead
NSwag-generated C# clientsKiota (Microsoft) or NSwag; API Gateway can also generate SDKs for REST APIsKiota builds fluent, path-based clients
Azure DevOps breaking-change checks with custom scriptsoasdiff in GitHub Actions or any CISame idea, open-source tool
Pact in .NETSame: PactNetUnchanged

Architecture

Security-boundary view: the OpenAPI document describes your attack surface. Publish the client-facing v1 document to partners; keep the gateway variant (which contains ARNs) internal. Expose /openapi/* at runtime only when OpenApi:Expose=true — off in production, where the build-time file is the published artefact.

Step-by-step implementation

Choose design-first or code-first

Design-firstCode-first
Source of truthHand-written YAMLC# endpoints + transformers
Best whenMany consumers, partner negotiation, regulatory review before buildOne team owns API and main client; fast iteration
RiskSpec and code drift unless tests enforce itAccidental contract changes from refactors
GuardrailContract tests: generated doc must match the designBreaking-change check on the generated doc

Harbourline uses a hybrid: the first version of a new API is designed in YAML and reviewed by the partner team and security (Lab 4.1, below). Once implemented, the generated document becomes the source of truth, is committed to Git on every build, and oasdiff guards it.

Lab 4.1, part 1 — design the contract

Write the design in openapi/account-information.design.yaml. An excerpt:

openapi: 3.0.3
info:
  title: Harbourline Account Information API
  version: "1.0.0"
paths:
  /v1/accounts/{accountId}:
    get:
      operationId: getAccount
      security:
        - oauth2: [harbourline-accounts/accounts.read]
      parameters:
        - name: accountId
          in: path
          required: true
          schema: { type: string, pattern: "^ACC-[0-9]{10}$" }
      responses:
        "200":
          description: The account, if it belongs to the caller
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Account" }
        "404":
          description: Not found or not owned by the caller (indistinguishable by design)
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }
  /v1/accounts/{accountId}/statement-requests:
    post:
      operationId: createStatementRequest
      security:
        - oauth2: [harbourline-accounts/statements.write]
      parameters:
        - name: accountId
          in: path
          required: true
          schema: { type: string, pattern: "^ACC-[0-9]{10}$" }
        - name: Idempotency-Key
          in: header
          required: true
          schema: { type: string, minLength: 8, maxLength: 128 }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/StatementRequestBody" }
      responses:
        "202":
          description: Accepted; poll the Location header
        "409": { description: Same key still in progress }
        "422": { description: Key reused with a different body, or invalid date range }
components:
  securitySchemes:
    oauth2:
      type: oauth2
      flows:
        authorizationCode:
          authorizationUrl: https://auth.harbourline.example/oauth2/authorize
          tokenUrl: https://auth.harbourline.example/oauth2/token
          scopes:
            harbourline-accounts/accounts.read: Read your own accounts
            harbourline-accounts/statements.write: Request statements
  schemas:
    Money:
      type: object
      required: [amount, currency]
      properties:
        amount: { type: string, pattern: "^-?[0-9]+\\.[0-9]{2}$", description: Decimal string }
        currency: { type: string, enum: [GBP, EUR] }
    Account:
      type: object
      required: [accountId, status, balance]
      properties:
        accountId: { type: string }
        status: { type: string, enum: [open, frozen, closed] }
        balance: { $ref: "#/components/schemas/Money" }
    StatementRequestBody:
      type: object
      additionalProperties: false
      required: [fromDate, toDate, format]
      properties:
        fromDate: { type: string, format: date }
        toDate: { type: string, format: date }
        format: { type: string, enum: [pdf, csv] }
    Problem:
      type: object
      properties:
        type: { type: string }
        title: { type: string }
        status: { type: integer }
        detail: { type: string }
        traceId: { type: string }
        correlationId: { type: string }

Review it in a pull request with the consumers. Things reviewers should check: every operation has security; error responses use application/problem+json; money is a string; additionalProperties: false on request bodies (mass-assignment defence, see request validation); no customer id anywhere in paths or bodies.

Generate the documents from code

Microsoft.AspNetCore.OpenApi 10.0.x generates OpenAPI 3.1 with JSON Schema draft 2020-12 by default, at runtime (MapOpenApi() serves /openapi/{documentName}.json) and, with the Microsoft.Extensions.ApiDescription.Server package, at build time. Transformers let you change the document: document transformers see everything, operation transformers see one path+method (with endpoint metadata), schema transformers see each schema. The complete code below registers two documents: v1 (3.1, for clients) and gateway (3.0, for API Gateway).

To write the files on every build, add to the API project:

<ItemGroup>
  <PackageReference Include="Microsoft.Extensions.ApiDescription.Server" Version="10.0.15" PrivateAssets="all" />
</ItemGroup>
<PropertyGroup>
  <OpenApiDocumentsDirectory>../../openapi</OpenApiDocumentsDirectory>
</PropertyGroup>

Build-time generation starts your app's entry point to discover endpoints, so keep startup free of network calls (create AWS clients lazily, as AddAWSService does).

Lab 4.1, part 2 — generate a typed client with Kiota

dotnet tool install --global Microsoft.OpenApi.Kiota
kiota generate -l CSharp -c AccountInformationClient -n Harbourline.AccountInformation.Client \
  -d ./openapi/Harbourline.AccountInformation.Api_gateway.json -o ./src/Harbourline.AccountInformation.Client/Generated
dotnet add ./src/Harbourline.AccountInformation.Client package Microsoft.Kiota.Bundle

Generating from the 3.0 document is the safe choice because Kiota's handling of every OpenAPI 3.1 construct is not something this lesson verified (⚠ VERIFY against the Kiota release notes for your version). The gateway file contains AWS extensions; generators ignore x- extensions. File names follow <ProjectName>_<documentName>.json unless you set --file-name ⚠ VERIFY the exact name your build emits. NSwag (NSwag.ConsoleCore 14.x) is a valid alternative if your team already uses it.

Import the gateway document into API Gateway (optional)

The gateway document adds x-amazon-apigateway-integration (Lambda proxy, aws_proxy) to each operation and a Cognito user pool authorizer whose scopes come from each operation's security entry. Importing it creates the REST API's resource tree, methods, authorizer and integrations in one call. The CLI section shows the commands; the module project's CDK stack is the production path.

Write contract tests

Three layers, cheapest first:

  1. Document assertions (provider side): start the API in memory with WebApplicationFactory<Program>, fetch /openapi/v1.json, and assert the things that must never regress — every /v1 operation has a security requirement, the POST declares a required Idempotency-Key header and a 202 response, the 404 uses application/problem+json. Fast, no network.
  2. Consumer-driven contracts with PactNet (MIT licence, version 5.x): the consumer team writes a test describing the requests it makes and the fields it reads; PactNet runs a mock server and records a pact file. The provider pipeline replays the pact against the real API and fails if a field the consumer uses has changed. PactNet's provider verifier needs a real TCP socket, not the in-memory TestServer; in .NET 10 WebApplicationFactory can run Kestrel via UseKestrel(), or you start the app on a local port. PactNet uses a native library: Windows x64, Linux glibc x64/ARM64 and macOS are supported, Alpine (musl) is not.
  3. Breaking-change detection with oasdiff (Apache-2.0): compare the committed document on main with the one built from the pull request and fail on ERR-level breaking changes.

AWS Console instructions

Console → API Gateway → Create API → REST API → Import. Paste or choose gateway.json, select API endpoint type: Regional, choose Create API. Review warnings, then inspect Resources, Authorizers and Models. Do not deploy a stage for this exercise — an undeployed API cannot be invoked. Delete it afterwards: APIs → select → Actions → Delete.

AWS CLI

# 1. Import the 3.0 gateway document as a new Regional REST API (fileb:// sends the file as-is).
aws apigateway import-rest-api \
  --parameters endpointConfigurationTypes=REGIONAL \
  --body fileb://openapi/Harbourline.AccountInformation.Api_gateway.json \
  --profile learn-sandbox --region us-east-1
# Note the "id" in the output (for example a1b2c3d4e5) and read any "warnings".

# 2. Tag the API (import cannot set tags).
aws apigateway tag-resource \
  --resource-arn arn:aws:apigateway:us-east-1::/restapis/a1b2c3d4e5 \
  --tags Project=cea-lab,Lab=m04-openapi,Environment=learn,Owner=your-name \
  --profile learn-sandbox --region us-east-1

# 3. Inspect what was created.
aws apigateway get-resources --rest-api-id a1b2c3d4e5 --profile learn-sandbox --region us-east-1
aws apigateway get-authorizers --rest-api-id a1b2c3d4e5 --profile learn-sandbox --region us-east-1

# 4. Export it again to compare with what you imported (format is chosen in the path).
aws apigateway get-export --rest-api-id a1b2c3d4e5 --stage-name prod --export-type oas30 exported.json \
  --profile learn-sandbox --region us-east-1   # only works after a stage exists; skip if you did not deploy

The first import usually reports warnings for unsupported keywords (for example nullable or example). Fix the gateway document transformer until the import is clean, then add --fail-on-warnings so CI rejects regressions. The authorizer references a Cognito user pool ARN from configuration; use the pool created by the module project, because whether import validates that the pool exists was not verified here (⚠ VERIFY).

Infrastructure as Code

The module project's CDK stack builds the REST API with constructs rather than importing OpenAPI. If you prefer the contract-driven route, CDK can create a REST API from a file with SpecRestApi and ApiDefinition.FromAsset("openapi/gateway.json"); Terraform's aws_api_gateway_rest_api accepts the document in its body argument. Either way, the same gateway.json your CI checks is what gets deployed.

using Amazon.CDK;
using Amazon.CDK.AWS.APIGateway;
using Constructs;

namespace Harbourline.AccountInformation.Infra;

public sealed class ContractDrivenApi : Construct
{
    public ContractDrivenApi(Construct scope, string id) : base(scope, id)
    {
        var api = new SpecRestApi(this, "AccountInformationApi", new SpecRestApiProps
        {
            RestApiName = "hl-m04-account-information",
            ApiDefinition = ApiDefinition.FromAsset("../../openapi/Harbourline.AccountInformation.Api_gateway.json"),
            EndpointTypes = [EndpointType.REGIONAL],
            DeployOptions = new StageOptions { StageName = "prod", ThrottlingRateLimit = 50, ThrottlingBurstLimit = 100 }
        });
        Tags.Of(api).Add("Project", "cea-lab");
        Tags.Of(api).Add("Lab", "m04-openapi");
    }
}

Complete code

OpenApi/OpenApiSetup.cs
using System.Text.Json.Nodes;
using Harbourline.AccountInformation.Api.Idempotency;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.OpenApi;
using Microsoft.OpenApi;

namespace Harbourline.AccountInformation.Api.OpenApi;

public static class OpenApiSetup
{
    // Maps ASP.NET Core policy names to Cognito resource-server scopes.
    private static readonly Dictionary<string, string> PolicyScopes = new()
    {
        ["accounts:read"] = "harbourline-accounts/accounts.read",
        ["statements:write"] = "harbourline-accounts/statements.write",
    };

    public static IServiceCollection AddHarbourlineOpenApi(this IServiceCollection services, IConfiguration config)
    {
        // Client-facing contract: OpenAPI 3.1 (the .NET 10 default) with an OAuth2 scheme.
        services.AddOpenApi("v1", options =>
        {
            var authority = config["OpenApi:AuthorizationServer"] ?? "https://auth.harbourline.example";
            options.AddDocumentTransformer((document, _, _) =>
            {
                document.Info = new OpenApiInfo { Title = "Harbourline Account Information API", Version = "1.0.0" };
                document.Components ??= new OpenApiComponents();
                document.Components.SecuritySchemes = new Dictionary<string, IOpenApiSecurityScheme>
                {
                    ["oauth2"] = new OpenApiSecurityScheme
                    {
                        Type = SecuritySchemeType.OAuth2,
                        Flows = new OpenApiOAuthFlows
                        {
                            AuthorizationCode = new OpenApiOAuthFlow
                            {
                                AuthorizationUrl = new Uri($"{authority}/oauth2/authorize"),
                                TokenUrl = new Uri($"{authority}/oauth2/token"),
                                Scopes = PolicyScopes.Values.ToDictionary(s => s, s => s),
                            },
                        },
                    },
                };
                return Task.CompletedTask;
            });
            options.AddOperationTransformer((operation, context, _) =>
            {
                AddSecurity(operation, context, "oauth2");
                AddIdempotencyHeader(operation, context);
                return Task.CompletedTask;
            });
        });

        // Gateway variant: OpenAPI 3.0, apiKey-typed scheme with a Cognito authorizer, Lambda proxy integrations.
        services.AddOpenApi("gateway", options =>
        {
            options.OpenApiVersion = OpenApiSpecVersion.OpenApi3_0;
            var userPoolArn = config["Gateway:UserPoolArn"] ?? "arn:aws:cognito-idp:us-east-1:111122223333:userpool/us-east-1_EXAMPLE";
            var lambdaArn = config["Gateway:LambdaArn"] ?? "arn:aws:lambda:us-east-1:111122223333:function:hl-m04-account-information";
            var invokeUri = $"arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/{lambdaArn}/invocations";

            options.AddDocumentTransformer((document, _, _) =>
            {
                document.Components ??= new OpenApiComponents();
                document.Components.SecuritySchemes = new Dictionary<string, IOpenApiSecurityScheme>
                {
                    ["cognito"] = new OpenApiSecurityScheme
                    {
                        Type = SecuritySchemeType.ApiKey,
                        Name = "Authorization",
                        In = ParameterLocation.Header,
                        Extensions = new Dictionary<string, IOpenApiExtension>
                        {
                            ["x-amazon-apigateway-authtype"] = new JsonNodeExtension(JsonValue.Create("cognito_user_pools")),
                            ["x-amazon-apigateway-authorizer"] = new JsonNodeExtension(new JsonObject
                            {
                                ["type"] = "cognito_user_pools",
                                ["providerARNs"] = new JsonArray(userPoolArn),
                            }),
                        },
                    },
                };
                return Task.CompletedTask;
            });
            options.AddOperationTransformer((operation, context, _) =>
            {
                AddSecurity(operation, context, "cognito");
                AddIdempotencyHeader(operation, context);
                operation.Extensions ??= new Dictionary<string, IOpenApiExtension>();
                operation.Extensions["x-amazon-apigateway-integration"] = new JsonNodeExtension(new JsonObject
                {
                    ["type"] = "aws_proxy",
                    ["httpMethod"] = "POST",          // Lambda is always invoked with POST
                    ["uri"] = invokeUri,
                    ["passthroughBehavior"] = "when_no_match",
                });
                return Task.CompletedTask;
            });
        });

        return services;
    }

    private static void AddSecurity(OpenApiOperation operation, OpenApiOperationTransformerContext context, string scheme)
    {
        var metadata = context.Description.ActionDescriptor.EndpointMetadata;
        if (metadata.OfType<IAllowAnonymous>().Any())
        {
            return;
        }

        var scopes = metadata.OfType<IAuthorizeData>()
            .Select(a => a.Policy)
            .Where(p => p is not null && PolicyScopes.ContainsKey(p))
            .Select(p => PolicyScopes[p!])
            .ToList();

        operation.Security ??= [];
        operation.Security.Add(new OpenApiSecurityRequirement
        {
            [new OpenApiSecuritySchemeReference(scheme, context.Document)] = scopes,
        });
    }

    private static void AddIdempotencyHeader(OpenApiOperation operation, OpenApiOperationTransformerContext context)
    {
        if (!context.Description.ActionDescriptor.EndpointMetadata.OfType<RequiresIdempotencyKey>().Any())
        {
            return;
        }

        operation.Parameters ??= [];
        operation.Parameters.Add(new OpenApiParameter
        {
            Name = IdempotencyFilter.HeaderName,
            In = ParameterLocation.Header,
            Required = true,
            Description = "Client-generated UUID, unique per intended operation; kept 24 hours per customer.",
            Schema = new OpenApiSchema { Type = JsonSchemaType.String, MinLength = 8, MaxLength = 128 },
        });
    }
}

/// <summary>Endpoint metadata marker: this endpoint requires the Idempotency-Key header.</summary>
public sealed class RequiresIdempotencyKey;

public static class IdempotencyEndpointExtensions
{
    public static RouteHandlerBuilder RequireIdempotencyKey(this RouteHandlerBuilder builder) =>
        builder.AddEndpointFilter<IdempotencyFilter>().WithMetadata(new RequiresIdempotencyKey());
}
Program.cs (excerpt)
builder.Services.AddHarbourlineOpenApi(builder.Configuration);
// ...
if (app.Configuration.GetValue<bool>("OpenApi:Expose"))
{
    app.MapOpenApi().AllowAnonymous();   // serves /openapi/v1.json and /openapi/gateway.json
}

app.MapPost("/v1/accounts/{accountId}/statement-requests", StatementEndpoints.CreateAsync)
    .RequireAuthorization("statements:write")
    .RequireIdempotencyKey()
    .Produces(StatusCodes.Status202Accepted)
    .ProducesProblem(StatusCodes.Status409Conflict)
    .ProducesProblem(StatusCodes.Status422UnprocessableEntity);

public partial class Program;   // lets WebApplicationFactory<Program> find the entry point
tests/.../OpenApiContractTests.cs
using System.Text.Json;
using Microsoft.AspNetCore.Mvc.Testing;

namespace Harbourline.AccountInformation.Api.Tests;

public sealed class OpenApiContractTests(WebApplicationFactory<Program> factory)
    : IClassFixture<WebApplicationFactory<Program>>
{
    private async Task<JsonElement> GetDocumentAsync(string name)
    {
        var client = factory.WithWebHostBuilder(b => b.UseSetting("OpenApi:Expose", "true")).CreateClient();
        var json = await client.GetStringAsync($"/openapi/{name}.json", TestContext.Current.CancellationToken);
        return JsonDocument.Parse(json).RootElement.Clone();
    }

    [Fact]
    public async Task Client_document_is_openapi_31_and_every_v1_operation_is_secured()
    {
        var doc = await GetDocumentAsync("v1");

        Assert.StartsWith("3.1", doc.GetProperty("openapi").GetString());
        foreach (var path in doc.GetProperty("paths").EnumerateObject().Where(p => p.Name.StartsWith("/v1/")))
        {
            foreach (var op in path.Value.EnumerateObject())
            {
                var secured = op.Value.TryGetProperty("security", out var security) && security.GetArrayLength() > 0;
                Assert.True(secured, $"{op.Name.ToUpperInvariant()} {path.Name} has no security requirement");
            }
        }
    }

    [Fact]
    public async Task Statement_request_requires_idempotency_key_and_returns_202()
    {
        var doc = await GetDocumentAsync("v1");
        var post = doc.GetProperty("paths").GetProperty("/v1/accounts/{accountId}/statement-requests").GetProperty("post");

        Assert.Contains(post.GetProperty("parameters").EnumerateArray(), p =>
            p.GetProperty("name").GetString() == "Idempotency-Key"
            && p.GetProperty("in").GetString() == "header"
            && p.GetProperty("required").GetBoolean());
        Assert.True(post.GetProperty("responses").TryGetProperty("202", out _));
    }

    [Fact]
    public async Task Gateway_document_is_openapi_30_with_lambda_proxy_integrations()
    {
        var doc = await GetDocumentAsync("gateway");

        Assert.StartsWith("3.0", doc.GetProperty("openapi").GetString());
        var get = doc.GetProperty("paths").GetProperty("/v1/accounts/{accountId}").GetProperty("get");
        Assert.Equal("aws_proxy", get.GetProperty("x-amazon-apigateway-integration").GetProperty("type").GetString());
    }
}
Consumer pact test (in the mobile BFF repository)
using System.Net;
using System.Net.Http.Json;
using PactNet;

namespace Harbourline.MobileBff.ContractTests;

public sealed class AccountInformationPactTests
{
    [Fact]
    public async Task Gets_an_owned_account_with_a_string_balance()
    {
        var pact = Pact.V4("harbourline-mobile-bff", "harbourline-account-information-api",
                new PactConfig { PactDir = Path.Combine("..", "..", "..", "pacts") })
            .WithHttpInteractions();

        pact.UponReceiving("a request for an account the customer owns")
            .Given("customer CUS-00012345 owns account ACC-0000012345")
            .WithRequest(HttpMethod.Get, "/v1/accounts/ACC-0000012345")
            .WithHeader("Authorization", "Bearer test-token")
            .WillRespond()
            .WithStatus(HttpStatusCode.OK)
            .WithJsonBody(new
            {
                accountId = "ACC-0000012345",
                status = "open",
                balance = new { amount = "1250.50", currency = "GBP" },
            });

        await pact.VerifyAsync(async ctx =>
        {
            using var http = new HttpClient { BaseAddress = ctx.MockServerUri };
            http.DefaultRequestHeaders.Authorization = new("Bearer", "test-token");
            var account = await http.GetFromJsonAsync<AccountView>("/v1/accounts/ACC-0000012345");
            Assert.Equal("1250.50", account!.Balance.Amount);
        });
    }

    private sealed record MoneyView(string Amount, string Currency);
    private sealed record AccountView(string AccountId, string Status, MoneyView Balance);
}
.github/workflows/api-contract.yml (excerpt)
- name: Build (emits openapi/*.json)
  run: dotnet build labs/m04-account-information-api/Harbourline.AccountInformation.slnx -c Release
- name: Get the contract from main
  run: git show origin/main:openapi/Harbourline.AccountInformation.Api_v1.json > base-v1.json
- name: Fail on breaking changes
  run: >
    docker run --rm -v "${{ github.workspace }}:/specs:ro" tufin/oasdiff
    breaking --fail-on ERR /specs/base-v1.json /specs/openapi/Harbourline.AccountInformation.Api_v1.json

Code explained line by line

  1. PolicyScopes is the single place that maps ASP.NET Core authorization policy names to Cognito scopes, so the document, the gateway and the code cannot disagree silently.
  2. AddOpenApi("v1", ...) registers a document named v1, served at /openapi/v1.json; it keeps the .NET 10 default of OpenAPI 3.1.
  3. The v1 document transformer sets Info and an oauth2 scheme with the authorization-code flow and both scopes — what a client generator or a docs UI needs.
  4. AddOpenApi("gateway", ...) sets options.OpenApiVersion = OpenApiSpecVersion.OpenApi3_0, because API Gateway import supports OpenAPI 2.0 and 3.0.
  5. The gateway scheme is apiKey in the Authorization header with x-amazon-apigateway-authtype and x-amazon-apigateway-authorizer of type cognito_user_pools — the shape API Gateway requires. JsonNodeExtension wraps a JsonNode as an OpenAPI extension in Microsoft.OpenApi 2.x.
  6. The gateway operation transformer adds x-amazon-apigateway-integration with type: aws_proxy and httpMethod: POST (Lambda invocations always use POST, whatever the client's method).
  7. AddSecurity skips endpoints that allow anonymous access, reads the policy names from IAuthorizeData metadata (added by RequireAuthorization), converts them to scopes and adds an operation-level security requirement — API Gateway ignores root-level security.
  8. AddIdempotencyHeader documents the header only for endpoints marked with RequiresIdempotencyKey, which RequireIdempotencyKey() adds together with the filter, so the filter and the documentation travel together.
  9. app.MapOpenApi().AllowAnonymous() exposes the documents only when configuration allows it.
  10. public partial class Program; makes the top-level-statements entry point visible to WebApplicationFactory<Program>.
  11. The contract tests parse the document with System.Text.Json and assert invariants (3.1 for clients, 3.0 for the gateway, security everywhere, idempotency header present). They run in milliseconds without AWS.
  12. The Pact consumer test describes one interaction, verifies the BFF's HTTP code against PactNet's mock server, and writes a pact JSON file the provider pipeline replays.
  13. The workflow compares the document on main with the freshly built one; --fail-on ERR makes oasdiff exit non-zero on breaking changes.

Security considerations

  • Do not expose OpenAPI in production by default. It is not secret, but it maps your attack surface; publish the client document deliberately (developer portal, partner pack) instead.
  • The gateway document contains ARNs and account ids. Keep it in the private repository and pipeline artefacts.
  • Contract tests are security tests too: the "every operation is secured" assertion catches a forgotten RequireAuthorization() before deployment.
  • Generated clients still need resilience and token handling; Kiota's BaseBearerTokenAuthenticationProvider with an IAccessTokenProvider supplies tokens, and an HttpClient from IHttpClientFactory with Microsoft.Extensions.Http.Resilience handles timeouts and retries (see calling partner APIs).
  • Spec review is where privacy review starts: every response field in the document is data you disclose. Data protection review (UK GDPR data minimisation) is easiest at the YAML stage.

⚠ Learning shortcut — not for production

The gateway transformer falls back to placeholder ARNs from code when configuration is missing, and the pact file is shared through the file system. In production, fail the build if Gateway:UserPoolArn or Gateway:LambdaArn are missing, inject them from the deployment pipeline (CDK outputs or SSM Parameter Store), and exchange pacts through a Pact Broker or PactFlow with "can-i-deploy" checks.

Banking use case

Harbourline onboards a fintech partner for business-account data. The partner receives the v1 document, generates a Kiota client in a day, and writes Pact tests for the four fields its reconciliation uses. Harbourline's pipeline replays the partner's pact on every merge. Six months later a developer tries to change balance.amount from a string to a number "for convenience": oasdiff marks it as a breaking change, the partner's pact fails, and the change goes into a /v2 proposal instead of production. The API governance board keeps the oasdiff report as evidence of change control — supporting evidence, not a substitute for the bank's own change-management obligations.

Common mistakes

  • Importing the .NET 10 default (3.1) document into API Gateway → unsupported version errors or silent omissions → emit a separate 3.0 document.
  • Root-level security only → looks tidy → API Gateway ignores it; operations end up unauthenticated. Put security on each operation.
  • Using type: oauth2 or http schemes in the gateway document → valid OpenAPI but API Gateway requires apiKey plus x-amazon-apigateway-authorizer.
  • Treating generated clients as untouchable magic → no retries, no timeouts → wrap them with IHttpClientFactory and resilience handlers.
  • Running Pact provider tests on TestServer → PactNet needs a real socket → use UseKestrel() or a local port.
  • Running PactNet on Alpine images → musl is unsupported → use Debian/Ubuntu-based images.
  • No baseline for oasdiff → nothing to compare → commit the generated document to Git.

Troubleshooting

SymptomLikely causeFix
import-rest-api returns warnings about ignored keywordsnullable, example, default, readOnly, exclusiveMinimum in schemasRemove them in a gateway schema transformer, then use --fail-on-warnings
Imported methods have authorizationType: NONESecurity only at document rootAdd per-operation security (the AddSecurity helper)
Invalid base64 or garbled body on importfile:// with CLI v2 binary handlingUse fileb://
Build-time generation fails with connection errorsApp startup calls AWS or a databaseMake clients lazy; guard startup work with configuration
/openapi/v1.json returns 404 in testsOpenApi:Expose false, or MapOpenApi() behind authUse UseSetting("OpenApi:Expose", "true"); AllowAnonymous()
Pact verification: connection refusedProvider not listening on a real portUseKestrel() on the factory or start the app with a URL
oasdiff reports changes you consider safeDifferent generator versions reorder or rename schemasPin Microsoft.AspNetCore.OpenApi; review and accept intentionally

Cost and cleanup

Cost: $0. Document generation, Kiota, contract tests, Pact and oasdiff run locally or in CI. Importing an API into API Gateway without deploying a stage creates no billable requests.

# Delete the imported API (one delete every 30 seconds per account is allowed).
aws apigateway delete-rest-api --rest-api-id a1b2c3d4e5 --profile learn-sandbox --region us-east-1

# Confirm nothing tagged for the course remains.
aws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=cea-lab --profile learn-sandbox --region us-east-1

Exercises

  • 🟢 Guided (Lab 4.1): Write the design YAML for all five Account Information endpoints, generate a Kiota client from it, and write a console app that calls GET /v1/accounts against the module project running locally with a token minted by LocalTestTokenIssuer.
  • 🟡 Challenge: Add a schema transformer to the gateway document that removes keywords API Gateway does not support (nullable, example, default, readOnly) and adds x-amazon-apigateway-request-validators with a body-and-params validator applied to the POST. Import with --fail-on-warnings.
  • 🔴 Live problem: A partner reports that since Tuesday their generated client throws when deserialising GET /v1/accounts. Your oasdiff job passed. The diff shows status gained a new enum value dormant. Decide whether this is breaking, explain why the tool did or did not flag it, and propose a policy.

Assignment

Commit openapi/account-information.design.yaml, the generated v1 and gateway documents, a Kiota client project, the three contract tests and a CI workflow with the oasdiff gate to your portfolio repository. Add a docs/api-contract.md explaining your design-first/code-first policy and what counts as a breaking change.

Solutions

Knowledge check

Interview questions

  • "Design-first or code-first?" — Design-first for new, multi-consumer or partner APIs where review comes before build; code-first with a committed, diff-checked generated document for fast-moving internal APIs; contract tests either way.
  • "How do you prevent breaking changes?" — A written definition of breaking, oasdiff in CI against main, consumer-driven contracts for key consumers, and major versions (/v2) for intentional breaks with a deprecation period.
  • "What goes wrong importing OpenAPI into API Gateway?" — Unsupported keywords and versions (3.1), root-level security ignored, non-apiKey security schemes, missing integration extensions; fix with a gateway-specific document and --fail-on-warnings.
  • "How do you generate a .NET client today?" — Kiota (dotnet tool install --global Microsoft.OpenApi.Kiota, kiota generate -l CSharp ...) or NSwag; wrap with IHttpClientFactory and resilience.

Certification practice

Completion checklist

  • I wrote the Account Information API design in OpenAPI and had it reviewed (Lab 4.1)
  • My API emits v1 (3.1) and gateway (3.0) documents with transformers
  • I generated a Kiota client and called the local API with it
  • My contract tests run in CI, and oasdiff blocks breaking changes
  • I deleted any imported API and confirmed nothing tagged Project=cea-lab remains

Key takeaways

  • OpenAPI is the API's contract; treat it as code — reviewed, versioned and tested.
  • .NET 10 generates OpenAPI 3.1 by default; API Gateway import supports 2.0 and 3.0, so emit a 3.0 gateway variant with AWS vendor extensions.
  • In the gateway document, security goes on every operation, using an apiKey scheme plus x-amazon-apigateway-authorizer.
  • Kiota generates typed C# clients; wrap them with resilience and token providers.
  • Document assertions, Pact consumer contracts and oasdiff together catch breaking changes before partners do.

Further reading

Independent learning resource — not affiliated with, endorsed or sponsored by Amazon Web Services. AWS and related marks are trademarks of Amazon.com, Inc. or its affiliates. All banking data in examples is fictional. Sample architectures are for learning and are not automatically compliant with GDPR, PCI DSS or any banking regulation.

On this page