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.
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-integrationand 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
- REST API design for banking and Idempotency keys
- Tools: .NET 10 SDK, Docker, AWS CLI v2 with the
learn-sandboxprofile (only for the optional import step)
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,$refto other files,format: decimal, andoneOf/anyOf/allOfthat$refa definition in the same schema in 3.0. - Root-level
securityis ignored: put security on each operation. - A
securitySchemesentry must be of typeapiKey; OAuth2/JWT validation is expressed with thex-amazon-apigateway-authorizervendor extension (cognito_user_pools,token,requestorjwt). - 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 equivalent | What's different |
|---|---|---|
| Swashbuckle / NSwag in older templates | Microsoft.AspNetCore.OpenApi (built in since .NET 9) | .NET 10 defaults to OpenAPI 3.1 and supports YAML output |
| APIM "Import OpenAPI" with policies in XML | API Gateway import-rest-api with x-amazon-apigateway-* vendor extensions | Integration, authorizer and validator settings live inside the OpenAPI file |
| APIM developer portal | API Gateway developer portal (REST APIs) or your own docs site | Many teams publish the spec with Scalar or Redoc instead |
| NSwag-generated C# clients | Kiota (Microsoft) or NSwag; API Gateway can also generate SDKs for REST APIs | Kiota builds fluent, path-based clients |
| Azure DevOps breaking-change checks with custom scripts | oasdiff in GitHub Actions or any CI | Same idea, open-source tool |
| Pact in .NET | Same: PactNet | Unchanged |
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-first | Code-first | |
|---|---|---|
| Source of truth | Hand-written YAML | C# endpoints + transformers |
| Best when | Many consumers, partner negotiation, regulatory review before build | One team owns API and main client; fast iteration |
| Risk | Spec and code drift unless tests enforce it | Accidental contract changes from refactors |
| Guardrail | Contract tests: generated doc must match the design | Breaking-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.BundleGenerating 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:
- 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/v1operation has a security requirement, the POST declares a requiredIdempotency-Keyheader and a 202 response, the 404 usesapplication/problem+json. Fast, no network. - 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 10WebApplicationFactorycan run Kestrel viaUseKestrel(), 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. - Breaking-change detection with oasdiff (Apache-2.0): compare the committed document on
mainwith 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 deployThe 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
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());
}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 pointusing 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());
}
}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);
}- 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.jsonCode explained line by line
PolicyScopesis 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.AddOpenApi("v1", ...)registers a document namedv1, served at/openapi/v1.json; it keeps the .NET 10 default of OpenAPI 3.1.- The
v1document transformer setsInfoand anoauth2scheme with the authorization-code flow and both scopes — what a client generator or a docs UI needs. AddOpenApi("gateway", ...)setsoptions.OpenApiVersion = OpenApiSpecVersion.OpenApi3_0, because API Gateway import supports OpenAPI 2.0 and 3.0.- The gateway scheme is
apiKeyin theAuthorizationheader withx-amazon-apigateway-authtypeandx-amazon-apigateway-authorizerof typecognito_user_pools— the shape API Gateway requires.JsonNodeExtensionwraps aJsonNodeas an OpenAPI extension in Microsoft.OpenApi 2.x. - The gateway operation transformer adds
x-amazon-apigateway-integrationwithtype: aws_proxyandhttpMethod: POST(Lambda invocations always use POST, whatever the client's method). AddSecurityskips endpoints that allow anonymous access, reads the policy names fromIAuthorizeDatametadata (added byRequireAuthorization), converts them to scopes and adds an operation-level security requirement — API Gateway ignores root-level security.AddIdempotencyHeaderdocuments the header only for endpoints marked withRequiresIdempotencyKey, whichRequireIdempotencyKey()adds together with the filter, so the filter and the documentation travel together.app.MapOpenApi().AllowAnonymous()exposes the documents only when configuration allows it.public partial class Program;makes the top-level-statements entry point visible toWebApplicationFactory<Program>.- The contract tests parse the document with
System.Text.Jsonand assert invariants (3.1 for clients, 3.0 for the gateway, security everywhere, idempotency header present). They run in milliseconds without AWS. - 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.
- The workflow compares the document on
mainwith the freshly built one;--fail-on ERRmakes 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
BaseBearerTokenAuthenticationProviderwith anIAccessTokenProvidersupplies tokens, and anHttpClientfromIHttpClientFactorywithMicrosoft.Extensions.Http.Resiliencehandles 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
securityonly → looks tidy → API Gateway ignores it; operations end up unauthenticated. Put security on each operation. - Using
type: oauth2orhttpschemes in the gateway document → valid OpenAPI but API Gateway requiresapiKeyplusx-amazon-apigateway-authorizer. - Treating generated clients as untouchable magic → no retries, no timeouts → wrap them with
IHttpClientFactoryand resilience handlers. - Running Pact provider tests on
TestServer→ PactNet needs a real socket → useUseKestrel()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
| Symptom | Likely cause | Fix |
|---|---|---|
import-rest-api returns warnings about ignored keywords | nullable, example, default, readOnly, exclusiveMinimum in schemas | Remove them in a gateway schema transformer, then use --fail-on-warnings |
Imported methods have authorizationType: NONE | Security only at document root | Add per-operation security (the AddSecurity helper) |
Invalid base64 or garbled body on import | file:// with CLI v2 binary handling | Use fileb:// |
| Build-time generation fails with connection errors | App startup calls AWS or a database | Make clients lazy; guard startup work with configuration |
/openapi/v1.json returns 404 in tests | OpenApi:Expose false, or MapOpenApi() behind auth | Use UseSetting("OpenApi:Expose", "true"); AllowAnonymous() |
| Pact verification: connection refused | Provider not listening on a real port | UseKestrel() on the factory or start the app with a URL |
| oasdiff reports changes you consider safe | Different generator versions reorder or rename schemas | Pin 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-1Exercises
- 🟢 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/accountsagainst the module project running locally with a token minted byLocalTestTokenIssuer. - 🟡 Challenge: Add a schema transformer to the
gatewaydocument that removes keywords API Gateway does not support (nullable,example,default,readOnly) and addsx-amazon-apigateway-request-validatorswith abody-and-paramsvalidator 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 showsstatusgained a new enum valuedormant. 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
Generate with kiota generate -l CSharp -c AccountInformationClient -n Harbourline.AccountInformation.Client -d account-information.design.yaml -o ./Client. Create the client with an HttpClientRequestAdapter whose authentication provider is a BaseBearerTokenAuthenticationProvider wrapping a small IAccessTokenProvider that returns the locally minted token, and set adapter.BaseUrl = "http://localhost:5000". Calls look like await client.V1.Accounts.GetAsync() and await client.V1.Accounts["ACC-0000012345"].GetAsync(); exact member names follow your document's paths and operationIds. Why: generating from the reviewed design proves the design is complete enough to build a client before (or while) the server is written.
options.AddSchemaTransformer((schema, _, _) => { schema.Example = null; schema.Default = null; schema.ReadOnly = false; return Task.CompletedTask; }) on the gateway document (property names in Microsoft.OpenApi 2.x may differ slightly — let the compiler guide you). In the document transformer add document.Extensions["x-amazon-apigateway-request-validators"] with a JsonObject containing "body-and-params": { "validateRequestBody": true, "validateRequestParameters": true }, and in the operation transformer set operation.Extensions["x-amazon-apigateway-request-validator"] = new JsonNodeExtension(JsonValue.Create("body-and-params")) for POST operations. Why: a clean, warning-free import makes --fail-on-warnings a useful CI gate.
Adding an enum value to a response is backward-compatible by the letter of most rules (no field removed or retyped), so oasdiff classifies it below ERR; but strict generated clients that map enums to closed types fail on unknown values. Policy: (1) document that response enums are open — clients must tolerate unknown values; (2) configure oasdiff to fail on WARN for response enum changes, or review WARN-level findings in PRs; (3) announce new enum values to partners before release. Why: "breaking" depends on what consumers actually do — which is exactly what consumer-driven contracts capture.
Knowledge check
Answer: OpenAPI 3.1. API Gateway import documents support for OpenAPI 2.0 and 3.0, so you generate a separate document with OpenApiVersion = OpenApiSpecVersion.OpenApi3_0 for import.
Answer: Define a securitySchemes entry of type apiKey (header Authorization) with x-amazon-apigateway-authtype: cognito_user_pools and an x-amazon-apigateway-authorizer of type cognito_user_pools listing providerARNs; then list the required scopes in each operation's security entry.
Answer: A document test checks the provider's own OpenAPI output against rules the provider sets. A consumer-driven contract (Pact) records what a specific consumer sends and reads, and the provider replays it — catching changes that matter to real consumers even if the document looks fine.
Answer: OpenAPI describes the interface, not the backend. The extension tells API Gateway how to integrate each method — for example aws_proxy to a Lambda function's invocation URI with httpMethod: POST.
Answer: It compares a base and a revised OpenAPI document and exits non-zero if it finds ERR-level breaking changes (for example removed paths, removed response fields, new required parameters), failing the build.
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 withIHttpClientFactoryand resilience.
Certification practice
A team maintains an OpenAPI 3.0 file for a REST API and wants every deployment to create API Gateway resources, methods and Lambda integrations from that file. What should they do?
A. Upload the file to Amazon S3 and enable static website hosting
B. Add x-amazon-apigateway-integration extensions to each operation and import or put the definition with API Gateway (or reference it from AWS CloudFormation/CDK)
C. Use the API Gateway console's Test feature with the file attached
D. Convert the file to an AWS Lambda layer
Answer: B. API Gateway creates integrations from vendor extensions during import, and infrastructure as code can reference the same file. A only hosts documentation. C tests methods that already exist. D is unrelated.
After importing an OpenAPI definition, a developer finds that every method in the REST API has authorization type NONE, although the document declares an OAuth2 security scheme and a root-level security requirement. What change fixes this?
A. Redeploy the stage
B. Define an apiKey-type security scheme with an x-amazon-apigateway-authorizer (for example cognito_user_pools) and add security to each operation
C. Enable AWS WAF on the stage
D. Require API keys in a usage plan
Answer: B. API Gateway ignores root-level security and expects authorizers described through its vendor extension on an apiKey-type scheme. A redeploys the same configuration. C and D add protections but do not authenticate users.
Several internal teams consume a payments API. Releases frequently break consumers because response fields change unexpectedly. Which approach most directly reduces these failures without slowing all releases?
A. Add Amazon CloudWatch alarms on 5xx errors B. Introduce consumer-driven contract tests and an automated OpenAPI breaking-change check in the provider's pipeline C. Move the API from REST to HTTP API type D. Enable API Gateway caching
Answer: B. Contract tests and breaking-change detection catch incompatible changes before deployment. A detects failures after they hit users. C and D change performance and cost characteristics, not compatibility.
Completion checklist
- I wrote the Account Information API design in OpenAPI and had it reviewed (Lab 4.1)
- My API emits
v1(3.1) andgateway(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-labremains
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
apiKeyscheme plusx-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
- Generate OpenAPI documents in ASP.NET Core (.NET 10)
- Customize OpenAPI documents (transformers)
- Amazon API Gateway important notes (OpenAPI import limitations)
- x-amazon-apigateway-integration object
- x-amazon-apigateway-authorizer object
- Import a Regional API into API Gateway and import-rest-api CLI reference
- Install Kiota and Build API clients for .NET with Kiota
- PactNet on GitHub
- oasdiff on GitHub
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.
Idempotency keys: making POST safe to retry
Implement the Idempotency-Key header in ASP.NET Core 10 with an endpoint filter and a DynamoDB store that uses conditional writes and TTL, so retries never create duplicate statements or payments.
Amazon API Gateway: REST vs HTTP vs WebSocket APIs
Choose the right API Gateway API type for a banking workload using a verified feature matrix, real prices, quotas and a decision table, then build and tear down an HTTP API from the CLI.