REST API design for banking
Design resource URIs, status codes, pagination, money fields, versioning and RFC 9457 problem details for a banking API, and implement them in ASP.NET Core 10.
Assumes: .NET 10 LTS · ASP.NET Core 10 minimal APIs · AWS SDK for .NET v4 · 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:
- Model a banking domain as REST resources (accounts, transactions, statement requests) with predictable URIs.
- Pick the right HTTP method and status code using the safe and idempotent method properties from RFC 9110, including why a bank returns 404 instead of 403 for another customer's account.
- Implement cursor (keyset) pagination with an opaque cursor, plus filtering and sorting that cannot be abused.
- Represent money as a decimal string plus an ISO 4217 currency code, and dates as ISO 8601.
- Choose a versioning strategy and explain what an API Gateway stage is — and is not.
- Return RFC 9457 problem details from ASP.NET Core 10 with
traceIdandcorrelationId, and use ETags for optimistic concurrency.
Prerequisites
- Module 3: .NET on AWS — minimal APIs, configuration and structured logging
- Tools: .NET 10 SDK, an HTTP client (
curl, the VS Code REST Client or Bruno) - No AWS resources are created in this lesson
Why this matters in banking
A mobile banking app shows "Payment failed" after a timeout, the customer taps Retry, and two standing orders are created. A partner integration treats every 400 as "try again later" and hammers the API all night. An auditor asks why a penetration tester could tell which account numbers exist by comparing 403 and 404 responses. A reconciliation job reports a one-penny difference because a JSON parser turned 0.1 + 0.2 into 0.30000000000000004.
None of these are AWS problems. They are contract problems: the shape of URIs, the meaning of status codes, how numbers travel in JSON. API Gateway, Lambda and WAF sit in front of that contract; they cannot repair it. That is why the module starts here.
The idea in plain language
REST means you expose things (resources) at stable addresses (URIs) and act on them with a small set of standard verbs (HTTP methods). The response status code tells the client, in a machine-readable way, what happened and whether trying again could help.
Three ideas carry most of the weight:
- Nouns in the URI, verbs in the method.
POST /v1/accounts/ACC-0000012345/statement-requestscreates a statement request; there is no/generateStatementendpoint. - Method properties are promises. A safe method (GET, HEAD, OPTIONS, TRACE) promises not to change state. An idempotent method (PUT, DELETE and all safe methods) promises that sending it twice has the same intended effect as sending it once. POST promises neither — which is why the next lesson adds idempotency keys.
- Errors are data. Every failure returns the same JSON shape (problem details), so clients write one error handler, not fifty.
Analogy: A REST API is a well-run bank branch. Every counter has a sign (the URI), every form has a type (the method), and every rejection slip uses the same template with a reference number (problem details with
traceId). A teller never tells a stranger "that account exists but you can't see it" — they say "I can't find that account".
What problem the AWS service solves
This lesson is mostly service-agnostic, but the AWS pieces you meet later make assumptions about your design:
- Amazon API Gateway routes on method and path, validates requests against JSON Schema models (REST APIs only), throttles, and can map a custom domain path such as
/v1to a specific API stage. It does not invent status codes for your business logic. - Stages in API Gateway are named snapshots of a deployment (
dev,test,prod) with their own settings — throttling, logging, stage variables. They are an environment concept, not a versioning scheme. Puttingprodin a public URL is a leak of internal structure; a custom domain with a/v1base path mapping hides it. - AWS Lambda and ECS run your ASP.NET Core code, which owns status codes, pagination and error bodies.
Sharp edges to keep in mind:
- REST API integrations time out at 29 seconds by default (Regional APIs can request more at the cost of account throttle quota), and HTTP APIs at 30 seconds. Long work such as PDF statement generation must be asynchronous: return 202 Accepted with a
Locationto poll. - The maximum payload for both REST and HTTP APIs is 10 MB, and a synchronous Lambda invocation is limited to 6 MB each way. Paginate; never return "all transactions".
Microsoft / Azure comparison
| You know (Microsoft/Azure) | AWS equivalent | What's different |
|---|---|---|
| Azure API Management versions (path, header or query-string scheme) | API Gateway custom domain + API mappings (/v1 → API A stage prod), or /v1 resources inside one API; REST APIs also support header-based routing rules | APIM models versions and revisions explicitly; in API Gateway you compose them from APIs, stages and domain mappings |
| APIM revisions | API Gateway deployments + stages (and canary settings on REST API stages) | A stage points at one deployment snapshot; redeploy to publish changes |
ProblemDetails / ValidationProblemDetails in ASP.NET Core | Unchanged — your code returns them; API Gateway's own errors are customised with gateway responses | Gateway errors (throttling, auth) default to {"message": ...} unless you customise them |
[ApiController] automatic 400 | ASP.NET Core 10 minimal API AddValidation() or explicit validators | Covered in request validation |
Asp.Versioning package | Same package works; or plain /v1 route groups | Choose one scheme and keep it stable |
| Azure Front Door caching with ETags | CloudFront / API Gateway REST API cache | Do not cache per-customer banking data at the edge |
Architecture
Security-boundary view: the custom domain and API Gateway are the public trust boundary; they authenticate the token and throttle. Everything about which customer owns which account is enforced inside the API, in the data query. The URI never carries a customer_id: the API derives it from the token.
Step-by-step implementation
Model the resources
Start from the nouns the customer sees, not from database tables. For the Harbourline Account Information API (the module project):
| Resource | URI | Methods |
|---|---|---|
| Account collection (caller's own) | /v1/accounts | GET |
| Account | /v1/accounts/{accountId} | GET |
| Transactions of an account | /v1/accounts/{accountId}/transactions | GET |
| Statement requests of an account | /v1/accounts/{accountId}/statement-requests | POST |
| Statement request | /v1/statement-requests/{statementRequestId} | GET |
Rules of thumb: plural nouns, kebab-case, identifiers that are opaque to the client (ACC-0000012345, not a database integer), and no customer id in the path. A statement is generated asynchronously, so the client creates a statement request resource and polls it — the "request as a resource" pattern.
Choose methods by their semantics
RFC 9110 defines the properties you rely on. GET must never move money or change state, because browsers, proxies, prefetchers and retry libraries assume they can repeat it. PUT and DELETE are idempotent: PUT /v1/accounts/ACC-0000012345/nickname with the same body twice leaves the same result. POST is neither safe nor idempotent, so any POST that creates something valuable needs an Idempotency-Key header — the next lesson.
PATCH is not idempotent by definition either. If you use it (for example, JSON Merge Patch to change an account nickname), combine it with If-Match so that a replay of an old patch fails instead of overwriting newer data.
Decide status codes with a table, not by feel
| Situation | Code | Notes |
|---|---|---|
| Read succeeded | 200 OK | Body is the resource or page |
| Created synchronously | 201 Created | Include Location of the new resource |
| Accepted for asynchronous processing | 202 Accepted | POST .../statement-requests; include Location: /v1/statement-requests/{id} to poll |
| Success, no body | 204 No Content | DELETE, or PUT that returns nothing |
| Malformed syntax, missing required header, bad query parameter | 400 Bad Request | Includes a missing Idempotency-Key; validation errors list each field |
| No or invalid token | 401 Unauthorized | Send WWW-Authenticate: Bearer; usually returned by API Gateway's authorizer before your code runs |
| Token valid but lacks the scope for this operation | 403 Forbidden | e.g. token has accounts.read but calls the POST that needs statements.write |
| Resource does not exist or belongs to another customer | 404 Not Found | Deliberately indistinguishable — see below |
| State conflict: duplicate in-flight request, wrong state transition | 409 Conflict | e.g. same idempotency key still processing |
If-Match ETag does not match current version | 412 Precondition Failed | Optimistic concurrency |
Wrong Content-Type (e.g. XML to a JSON endpoint) | 415 Unsupported Media Type | |
| Syntactically valid but semantically wrong | 422 Unprocessable Content | toDate before fromDate; idempotency key reused with a different body |
| Rate limit exceeded | 429 Too Many Requests | Always send Retry-After |
| Unexpected failure | 500 Internal Server Error | Never leak stack traces; return traceId |
| Dependency down or overloaded (core banking unavailable) | 503 Service Unavailable | Retry-After when you can estimate it |
Teams argue about 400 versus 422. A workable rule: 400 when the request cannot be parsed or a required element is missing; 422 when every element parses but the combination breaks a business rule. Whatever you pick, document it in the OpenAPI contract (next-but-one lesson) and keep it consistent.
Why 404 and not 403 for someone else's account? OWASP lists Broken Object Level Authorization (API1:2023) as the top API risk. If GET /v1/accounts/ACC-0000099999 returns 403 when the account exists and 404 when it does not, an attacker can enumerate valid account numbers. The API therefore runs the query as "find this account for this customer" (IAccountStore.GetAccountAsync(customerId, accountId)); a miss is a miss, whoever owns it. Use 403 only for operation-level refusals (missing scope), where the answer leaks nothing about specific objects.
Paginate with cursors
Offset pagination (?page=3&pageSize=50 → OFFSET 100) is simple but has two banking problems: new transactions arriving while the customer scrolls shift every page (duplicates or gaps), and deep offsets make the database scan and discard rows.
Cursor (keyset) pagination remembers the last row seen and asks for "rows after this key". For transactions, the natural key is (booking_date DESC, transaction_id DESC); transaction_id is a UUID v7, which is time-ordered, so it also breaks ties. The response contains nextCursor, an opaque base64url string that encodes that key. Opaque matters: clients cannot construct cursors, so you can change the encoding later, and you can sign or encrypt it if it carries anything sensitive.
Rules: cap pageSize (for example max 100), return nextCursor only when more data exists, reject a cursor that was issued for different filters (encode the filter hash inside it), and never put a customer_id in a cursor — the customer comes from the token every time.
Filter and sort through an allow-list
Expose only filters you have indexed and need: status, currency, fromBookingDate, toBookingDate. Parse them into typed values (DateOnly, an enum) and reject unknown values with 400. Never pass a client-supplied sort or filter string into SQL or a DynamoDB expression. If you need sorting, accept a fixed set (sort=bookingDate or sort=-bookingDate) and map it in code.
Get money and dates right
JSON numbers are usually parsed into IEEE 754 doubles. RFC 8259 warns that numbers beyond double precision are not interoperable, and even small decimals such as 0.1 cannot be represented exactly. In C# you use decimal; the risk is the other side — a JavaScript or Python client.
Harbourline's rule: money travels as an object with a decimal string and an ISO 4217 currency code:
{ "amount": "1250.50", "currency": "GBP" }- The number of decimals follows the currency's minor unit (2 for GBP and EUR; 0 for JPY; 3 for some, such as BHD).
- Debits are negative (
"-42.10"), matching the dataset convention. - Dates without time (
bookingDate,valueDate) are ISO 8601YYYY-MM-DD(DateOnlyin C#). Instants are UTC with an offset:2026-11-17T09:30:00Z(DateTimeOffset).
Version deliberately
| Strategy | Example | Pros | Cons |
|---|---|---|---|
| URI path | /v1/accounts | Visible, cache-friendly, trivial to route in API Gateway (resource tree or base path mapping) | URIs change on a major version |
| Custom header | Api-Version: 2026-11-01 | Clean URIs | Invisible in logs and browser tools; REST API routing rules can match headers, but HTTP APIs cannot |
| Media type | Accept: application/vnd.harbourline.v2+json | Very "pure" REST | Hardest for clients, gateways and caches |
Harbourline uses URI major versions (/v1) and makes only additive, backward-compatible changes inside a version (new optional fields, new endpoints). Breaking changes (removing a field, changing a type, tightening validation) mean /v2, run side by side, with a deprecation notice. The CI breaking-change check in the OpenAPI lesson enforces this.
Standardise errors with RFC 9457
RFC 9457, Problem Details for HTTP APIs (July 2023), obsoletes RFC 7807. The media type stays application/problem+json and the standard members are type, title, status, detail and instance. You may add extension members; Harbourline adds traceId (the W3C trace id, for X-Ray/OpenTelemetry) and correlationId (the X-Correlation-Id header that crosses system boundaries). Use stable type URIs that point to documentation, such as https://api.harbourline.example/problems/account-not-found, because clients branch on type, not on title text.
Use ETags for optimistic concurrency and caching
An ETag is a version tag for a representation. On GET, return ETag: "v7". A client that wants to change the resource sends If-Match: "v7"; if someone else changed it in between, return 412. For reads, If-None-Match lets the client receive 304 Not Modified instead of the full body. RFC 6585 also defines 428 Precondition Required, which you can return when a client omits If-Match on an update that requires it.
HATEOAS, an opinion. Hypermedia links in every response (_links.self, _links.transactions) are elegant, but most banking clients are generated from OpenAPI and never follow links dynamically. Harbourline returns the links that save real work — the Location header after 202, and nextCursor — and documents the rest in the contract. Open Banking standards take a similar pragmatic view (see Open Banking / PSD2).
AWS Console instructions
Nothing to create. To see how API Gateway represents the design ideas, browse an existing REST API (or the example API that the console offers): Console → API Gateway → APIs → (your API) → Resources shows the resource tree with /v1/accounts/{accountId}; Stages shows that a stage is a named deployment with its own settings; Custom domain names → API mappings shows how a path such as v1 maps to an API and stage; Gateway responses shows the default error bodies API Gateway itself returns.
AWS CLI
Read-only commands, useful when you inherit an API and want to see how it is versioned:
# List REST APIs in the sandbox (read-only).
aws apigateway get-rest-apis --profile learn-sandbox --region us-east-1
# Show the resource tree (paths) of one API — look for /v1 prefixes.
aws apigateway get-resources --rest-api-id a1b2c3d4e5 --profile learn-sandbox --region us-east-1
# Show stages: names, deployment ids, throttling and logging settings.
aws apigateway get-stages --rest-api-id a1b2c3d4e5 --profile learn-sandbox --region us-east-1
# Show which API/stage each path of a custom domain points to (v2 API covers REST and HTTP mappings).
aws apigatewayv2 get-api-mappings --domain-name api.harbourline.example --profile learn-sandbox --region us-east-1Infrastructure as Code
Not needed in this lesson; the module project's CDK stack (labs/m04-account-information-api/infra/cdk/Harbourline.AccountInformation.Infra) creates the /v1 resource tree in a REST API.
Complete code
A single runnable Program.cs that demonstrates resource URIs, the 404-for-other-customers rule, cursor pagination, money as strings, ETags and RFC 9457 errors. Create it with dotnet new web -n Harbourline.ApiDesignDemo and replace Program.cs. It uses a fake caller header instead of real JWT authentication so you can run it in seconds; the module project does the real thing.
using System.Diagnostics;
using System.Globalization;
using System.Text;
using System.Text.Json;
using Microsoft.AspNetCore.Http.HttpResults;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails(options =>
{
options.CustomizeProblemDetails = ctx =>
{
var http = ctx.HttpContext;
ctx.ProblemDetails.Instance ??= http.Request.Path;
ctx.ProblemDetails.Extensions["traceId"] = Activity.Current?.TraceId.ToString() ?? http.TraceIdentifier;
if (http.Items.TryGetValue("CorrelationId", out var cid) && cid is string correlationId)
{
ctx.ProblemDetails.Extensions["correlationId"] = correlationId;
}
};
});
var app = builder.Build();
app.UseExceptionHandler();
app.UseStatusCodePages();
app.Use(async (http, next) =>
{
var correlationId = http.Request.Headers["X-Correlation-Id"].FirstOrDefault();
if (string.IsNullOrWhiteSpace(correlationId) || correlationId.Length > 64)
{
correlationId = Guid.CreateVersion7().ToString();
}
http.Items["CorrelationId"] = correlationId;
http.Response.Headers["X-Correlation-Id"] = correlationId;
await next(http);
});
var v1 = app.MapGroup("/v1");
v1.MapGet("/accounts/{accountId}", Results<Ok<AccountDto>, ProblemHttpResult, StatusCodeHttpResult> (
string accountId, HttpContext http) =>
{
var customerId = DemoAuth.CustomerIdFrom(http);
var account = DemoData.Accounts.SingleOrDefault(a => a.AccountId == accountId && a.CustomerId == customerId);
if (account is null)
{
return TypedResults.Problem(
type: "https://api.harbourline.example/problems/account-not-found",
title: "Account not found",
statusCode: StatusCodes.Status404NotFound,
detail: "No account with this identifier is available to you.");
}
var etag = $"\"v{account.Version}\"";
if (http.Request.Headers.IfNoneMatch.Contains(etag))
{
return TypedResults.StatusCode(StatusCodes.Status304NotModified);
}
http.Response.Headers.ETag = etag;
return TypedResults.Ok(AccountDto.From(account));
});
v1.MapGet("/accounts/{accountId}/transactions", Results<Ok<Page<TransactionDto>>, ProblemHttpResult> (
string accountId, HttpContext http, int? pageSize, string? cursor) =>
{
var customerId = DemoAuth.CustomerIdFrom(http);
if (!DemoData.Accounts.Any(a => a.AccountId == accountId && a.CustomerId == customerId))
{
return TypedResults.Problem(title: "Account not found", statusCode: StatusCodes.Status404NotFound,
type: "https://api.harbourline.example/problems/account-not-found");
}
var size = pageSize ?? 50;
if (size is < 1 or > 100)
{
return TypedResults.Problem(title: "Invalid pageSize", detail: "pageSize must be between 1 and 100.",
statusCode: StatusCodes.Status400BadRequest, type: "https://api.harbourline.example/problems/invalid-parameter");
}
PageCursor? after = null;
if (cursor is not null && !PageCursor.TryDecode(cursor, out after))
{
return TypedResults.Problem(title: "Invalid cursor", statusCode: StatusCodes.Status400BadRequest,
type: "https://api.harbourline.example/problems/invalid-cursor");
}
var query = DemoData.Transactions
.Where(t => t.AccountId == accountId)
.OrderByDescending(t => t.BookingDate).ThenByDescending(t => t.TransactionId, StringComparer.Ordinal);
var filtered = after is null ? query.AsEnumerable() : PageCursor.After(query, after);
var rows = filtered.Take(size + 1).ToList();
var hasMore = rows.Count > size;
var items = rows.Take(size).Select(TransactionDto.From).ToList();
var next = hasMore ? new PageCursor(rows[size - 1].BookingDate, rows[size - 1].TransactionId).Encode() : null;
return TypedResults.Ok(new Page<TransactionDto>(items, next));
});
app.Run();
public sealed record Account(string AccountId, string CustomerId, string Currency, decimal Balance, string Status, int Version);
public sealed record Transaction(string TransactionId, string AccountId, DateOnly BookingDate, decimal Amount, string Currency, string Reference);
public sealed record MoneyDto(string Amount, string Currency)
{
private static readonly Dictionary<string, int> MinorUnits = new() { ["GBP"] = 2, ["EUR"] = 2, ["JPY"] = 0 };
public static MoneyDto From(decimal amount, string currency)
{
var decimals = MinorUnits.TryGetValue(currency, out var d) ? d : 2;
var rounded = decimal.Round(amount, decimals, MidpointRounding.ToEven);
return new MoneyDto(rounded.ToString("F" + decimals, CultureInfo.InvariantCulture), currency);
}
}
public sealed record AccountDto(string AccountId, string Status, MoneyDto Balance)
{
public static AccountDto From(Account a) => new(a.AccountId, a.Status, MoneyDto.From(a.Balance, a.Currency));
}
public sealed record TransactionDto(string TransactionId, DateOnly BookingDate, MoneyDto Amount, string Reference)
{
public static TransactionDto From(Transaction t) => new(t.TransactionId, t.BookingDate, MoneyDto.From(t.Amount, t.Currency), t.Reference);
}
public sealed record Page<T>(IReadOnlyList<T> Items, string? NextCursor);
public sealed record PageCursor(DateOnly BookingDate, string TransactionId)
{
public string Encode()
{
var json = JsonSerializer.SerializeToUtf8Bytes(this);
return Convert.ToBase64String(json).TrimEnd('=').Replace('+', '-').Replace('/', '_');
}
// Keyset condition matching ORDER BY BookingDate DESC, TransactionId DESC.
public static IEnumerable<Transaction> After(IEnumerable<Transaction> source, PageCursor c) =>
source.Where(t => t.BookingDate < c.BookingDate
|| (t.BookingDate == c.BookingDate && string.CompareOrdinal(t.TransactionId, c.TransactionId) < 0));
public static bool TryDecode(string value, out PageCursor? cursor)
{
cursor = null;
try
{
var base64 = value.Replace('-', '+').Replace('_', '/');
base64 = base64.PadRight(base64.Length + (4 - base64.Length % 4) % 4, '=');
cursor = JsonSerializer.Deserialize<PageCursor>(Encoding.UTF8.GetString(Convert.FromBase64String(base64)));
return cursor is not null && !string.IsNullOrEmpty(cursor.TransactionId);
}
catch (Exception e) when (e is FormatException or JsonException)
{
return false;
}
}
}
public static class DemoAuth
{
// ⚠ Demo only: the real API derives the customer from the validated JWT "sub" claim.
public static string CustomerIdFrom(HttpContext http) =>
http.Request.Headers["X-Demo-Customer"].FirstOrDefault() ?? "CUS-00012345";
}
public static class DemoData
{
public static readonly List<Account> Accounts =
[
new("ACC-0000012345", "CUS-00012345", "GBP", 1250.50m, "open", 7),
new("ACC-0000099999", "CUS-00067890", "EUR", 980.00m, "open", 3),
];
public static readonly List<Transaction> Transactions = Enumerable.Range(1, 120)
.Select(i => new Transaction(
TransactionId: $"0192f0a0-0000-7000-8000-{i:D12}",
AccountId: "ACC-0000012345",
BookingDate: new DateOnly(2026, 10, 1).AddDays(i % 31),
Amount: i % 3 == 0 ? 2500.00m : -(i * 1.10m),
Currency: "GBP",
Reference: $"Card payment {i}"))
.ToList();
}Try it:
dotnet run
curl -i http://localhost:5000/v1/accounts/ACC-0000012345 # 200 + ETag
curl -i http://localhost:5000/v1/accounts/ACC-0000099999 # 404 (exists, but not yours)
curl -i "http://localhost:5000/v1/accounts/ACC-0000012345/transactions?pageSize=2"
curl -i "http://localhost:5000/v1/accounts/ACC-0000012345/transactions?pageSize=500" # 400 problem+jsonCode explained line by line
AddProblemDetails(options => ...)registers the defaultIProblemDetailsService;CustomizeProblemDetailsruns for every problem response, including those created byUseExceptionHandlerandUseStatusCodePages.ctx.ProblemDetails.Extensions["traceId"]adds an RFC 9457 extension member.Activity.Current?.TraceIdis the W3C trace id OpenTelemetry propagates; the fallback is ASP.NET Core's request id.- The correlation middleware accepts a caller's
X-Correlation-Idonly if it is short (to stop log injection and bloat), otherwise generates a UUID v7 withGuid.CreateVersion7(), and echoes it on the response. app.MapGroup("/v1")is the URI version prefix; every route in the group inherits it.Results<Ok<AccountDto>, ProblemHttpResult, StatusCodeHttpResult>declares every possible response type, which also feeds the OpenAPI document.- The account lookup filters by both
AccountIdandCustomerId. Another customer's account and a non-existent account produce the identical 404 problem. etagis a strong validator derived from a row version;If-None-Matchreturns 304, saving bandwidth on mobile networks.- The transactions endpoint validates
pageSizeagainst an upper bound and returns 400 with a stabletypeURI. PageCursor.TryDecoderejects any cursor that is not valid base64url JSON, so a tampered cursor becomes a 400, not a 500.- The keyset condition "booking date earlier, or same date and smaller id" matches the descending sort, so a new transaction arriving between pages cannot cause duplicates.
Take(size + 1)fetches one extra row to learn whether a next page exists without aCOUNT(*).MoneyDto.Fromrounds with banker's rounding to the currency's minor unit and formats withInvariantCulture, so a server running in ade-DEculture never emits"1250,50".
Security considerations
- Object-level authorisation in the query, not in an
ifafter loading — a forgottenifis the classic BOLA bug. - Opaque identifiers do not replace authorisation; they only slow enumeration.
- No sensitive data in URIs. Paths and query strings end up in API Gateway access logs, CloudFront logs and browser history. Never put IBANs, names or tokens in a query string.
- Error bodies must not leak stack traces, SQL, or internal hostnames.
detailis for the client; logs (with the sametraceId) are for you. - Rate limits and 429 belong to the contract; see throttling.
⚠ Learning shortcut — not for production
The demo identifies the caller with an X-Demo-Customer header, so any client can impersonate any customer. Production APIs authenticate a JWT access token (Cognito in this module) and map the token sub to a customer_id server-side through ICustomerDirectory. The cursor is also unsigned; if it ever carries data you would not show the client, sign it with HMAC or encrypt it with a key held in AWS KMS or Secrets Manager.
Banking use case
Harbourline's mobile app shows the last 90 days of transactions with infinite scroll. It calls GET /v1/accounts/ACC-0000012345/transactions?fromBookingDate=2026-08-19&pageSize=50, then follows nextCursor until the user stops scrolling. A business customer's accountant downloads an October statement with POST /v1/accounts/ACC-0000012345/statement-requests and receives 202 Accepted plus Location: /v1/statement-requests/{id}; the app polls that URI until the status is ready. The support desk asks customers for the traceId shown in the app's error dialog and finds the matching logs in CloudWatch in seconds. Data shown in errors and logs is still personal data under UK GDPR, so retention and access to those logs need sign-off from the bank's data protection team.
Common mistakes
- Verbs in URIs (
/getAccounts,/accounts/123/delete) → habit from RPC/WCF services → use methods on nouns. - Returning 200 with
"success": false→ hides failures from gateways, monitors and retry logic → use real status codes. - 403 for another customer's object → feels "more accurate" → enables enumeration; return 404.
- Offset pagination on transactions → easy in SQL → duplicates and slow deep pages; use keyset cursors.
- Money as JSON numbers or
double→ default serialisers → precision loss on clients; use decimal strings + ISO 4217. - Using the API Gateway stage name as the version (
/prod/...,/v1stage) → stages look like versions → stages are environments; version in the path or base path mapping. - A different error shape per endpoint → each developer improvises → one
AddProblemDetailsconfiguration for the whole API.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Errors come back as an empty body with a status code | UseStatusCodePages or AddProblemDetails missing | Register both; check middleware order (UseExceptionHandler first) |
API Gateway returns {"message":"Missing Authentication Token"} for a valid path | Path or method not deployed, or wrong stage in the URL | Redeploy the API; check the stage and resource tree (get-resources) |
Client sees 1250.5 instead of 1250.50 | Amount serialised as a number | Use the MoneyDto string format |
| Page 2 repeats rows from page 1 | Offset pagination with new inserts, or non-unique sort key | Keyset on (bookingDate, transactionId) |
"1250,50" in production only | Culture-sensitive ToString() | Always format with CultureInfo.InvariantCulture |
| 304 never returned | ETag header missing quotes, or weak/strong mismatch | Emit quoted strong ETags and compare exact strings |
Cost and cleanup
Cost: $0. Everything runs locally; no AWS resources are created. The read-only CLI commands are free. Cleanup: stop dotnet run (Ctrl+C). If you ever created resources while exploring, 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: Run the demo, call each endpoint, and page through all 120 transactions with
pageSize=50. Record how many calls it takes and confirm no transaction appears twice. - 🟡 Challenge: Add
fromBookingDateandtoBookingDatefilters (typedDateOnly?), rejecttoBookingDatebeforefromBookingDatewith 422, and make the cursor carry a hash of the filters so a cursor reused with different filters returns 400. - 🔴 Live problem: A partner complains: "Your API returns 403 for some account ids and 404 for others; our pen test flagged it as an information leak." You find that one older endpoint (
GET /v1/accounts/{accountId}/balances) loads the account first, then checks ownership. Write the fix, a regression test, and a two-paragraph incident note.
Assignment
Write docs/api-design.md for your portfolio repository: the resource table for the Account Information API, your status-code decision table, the money and date conventions, the versioning policy (what counts as breaking), and three example problem-details responses (404, 422, 429) with traceId and correlationId.
Solutions
With 120 transactions and pageSize=50 you need three calls: 50, 50 and 20 items; the third response has "nextCursor": null. No duplicates appear because each cursor encodes the last (bookingDate, transactionId) pair and the next query asks strictly for rows after it in the same sort order. Why: keyset pagination is stable even if rows are inserted between calls, which offset pagination is not.
Add DateOnly? fromBookingDate, DateOnly? toBookingDate parameters; minimal APIs parse YYYY-MM-DD automatically and return 400 for malformed dates. If both are present and toBookingDate < fromBookingDate, return TypedResults.Problem(statusCode: 422, type: ".../problems/invalid-date-range"). Extend PageCursor with string FilterHash (for example the first 16 hex characters of SHA-256 over from|to), and when decoding compare it with the hash of the current filters; a mismatch is 400. Why: without the hash, a client can combine a cursor from one query with filters from another and receive a confusing or inconsistent page.
Replace "load by id, then compare owner" with a single lookup scoped by customer, GetAccountAsync(customerId, accountId), and return the same 404 problem whether the row is missing or owned by someone else. Add a test that calls the endpoint as customer A for customer B's account and asserts 404 with the same type and title as a non-existent id. The incident note states impact (existence of account ids could be inferred; no balances leaked), root cause (ownership check after load), fix, and the follow-up: a shared helper or repository method so no endpoint can load an account without a customer id. Why: BOLA is fixed by making the safe path the only path.
Knowledge check
Answer: Safe: GET, HEAD, OPTIONS, TRACE. Idempotent: PUT, DELETE and all safe methods. POST and PATCH are neither, so retries of POST need an idempotency key.
Answer: 404 Not Found, identical to a non-existent account. Returning 403 would confirm the account exists and allow enumeration (OWASP API1:2023 Broken Object Level Authorization).
Answer: It is stable when new rows arrive (no duplicates or gaps), it performs well at any depth because it seeks by key instead of skipping rows, and an opaque cursor lets you change the implementation without breaking clients.
Answer: RFC 9457 (July 2023), which obsoletes RFC 7807. Members: type, title, status, detail, instance; extensions such as traceId are allowed. Media type application/problem+json.
Answer: No. A stage is a named deployment snapshot with environment settings (throttling, logging, variables). Version with a /v1 path — inside the API or via a custom domain base path mapping — and keep stages for environments.
Interview questions
- "How do you design error responses for a public API?" — One RFC 9457 shape for every error, stable
typeURIs that clients branch on, humantitle/detail, and extension members fortraceIdand a correlation id; no internals leaked; documented in OpenAPI. - "Offset or cursor pagination?" — Cursor/keyset for large or fast-changing collections (transactions); offset only for small, stable lists where jumping to page N matters.
- "How do you send money amounts in JSON?" — As a decimal string with an ISO 4217 currency, formatted to the currency's minor units with invariant culture;
decimalin C#. - "When do you return 202?" — When work continues after the response, such as statement generation; return a
Locationto a status resource that the client polls. - "What makes a change breaking?" — Removing or renaming fields, changing types or formats, making optional inputs required, tightening validation, or changing status codes for existing behaviour.
Certification practice
A developer exposes POST /statements through an Amazon API Gateway REST API with a Lambda proxy integration. Generating a statement takes up to 90 seconds, and clients receive 504 errors. What should the developer do?
A. Increase the Lambda function timeout to 15 minutes
B. Return 202 Accepted with a status resource, and generate the statement asynchronously (for example by sending a message to Amazon SQS)
C. Switch to an HTTP API, which has no integration timeout
D. Enable API caching on the stage
Answer: B. The REST API integration timeout (29 seconds by default) ends the HTTP request regardless of the Lambda timeout, so A does not help. C is wrong: HTTP APIs have a 30-second maximum integration timeout. D caches responses but does not shorten the first request. Asynchronous processing with 202 and polling is the standard pattern.
A penetration test shows that a banking API returns 403 for account identifiers that exist but belong to other customers, and 404 for identifiers that do not exist. Which change best addresses the finding?
A. Add an AWS WAF rate-based rule to the API stage
B. Return 404 in both cases by scoping the data query to the authenticated customer
C. Replace sequential account ids with UUIDs
D. Require an API key on the method
Answer: B. The leak is the differing response. A slows the attack but still leaks. C makes guessing harder but does not fix authorisation or the oracle. D identifies a client application, not a customer, and API keys are not an authorisation control.
A company runs version 1 and version 2 of an API as two separate Amazon API Gateway REST APIs. Clients must call https://api.example.com/v1/... and https://api.example.com/v2/.... What is the simplest configuration?
A. One stage named v1 and one named v2 on the same API
B. A custom domain name with two API mappings: v1 to the first API's prod stage and v2 to the second API's prod stage
C. An Application Load Balancer with path-based routing in front of both APIs
D. Two Amazon CloudFront distributions
Answer: B. API mappings route base paths of a custom domain to API stages and strip the base path before invoking the API. A misuses stages and still exposes stage names unless a mapping is added. C and D add components without need.
Completion checklist
- I can explain safe vs idempotent methods and why POST needs an idempotency key
- I can justify 404 vs 403 for another customer's resource
- I ran the demo and paged through transactions with a cursor
- I can describe what an API Gateway stage is and why it is not a version
- My error responses follow RFC 9457 with
traceIdandcorrelationId
Key takeaways
- Nouns in URIs, semantics in methods; never put a customer id in the path — derive it from the token.
- A status-code table, agreed and documented, prevents most client/server misunderstandings; 404 hides other customers' objects.
- Keyset cursors are the right default for transaction history; keep cursors opaque and bounded.
- Money is a decimal string plus ISO 4217; dates are ISO 8601.
- RFC 9457 (which obsoletes RFC 7807) gives every error one shape; add
traceIdandcorrelationId. - Stages are environments; versions live in the path or in custom-domain mappings.
Further reading
- RFC 9110 — HTTP Semantics (method properties, status codes, conditional requests)
- RFC 9457 — Problem Details for HTTP APIs
- Handle errors in ASP.NET Core APIs
- OWASP API Security Top 10 2023 — API1 Broken Object Level Authorization
- Use API mappings to connect API stages to a custom domain name for REST APIs
- Quotas for configuring and running a REST API in API Gateway
- Gateway responses for REST APIs
- Module 4 overview · DVA-C03 exam guide page
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.
Module 4: API Development & Integration
Design, publish, secure and operate APIs on AWS, and integrate safely with partners, AWS services and on-premises banking systems. You finish by building an Account Information API where each customer can see only their own accounts, protected by Cognito, WAF and throttling.
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.