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

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.

intermediate⏱ 1 h 15 min🟢 FreeDVA-C03SAA-C03SCS-C03

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 traceId and correlationId, 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:

  1. Nouns in the URI, verbs in the method. POST /v1/accounts/ACC-0000012345/statement-requests creates a statement request; there is no /generateStatement endpoint.
  2. 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.
  3. 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 /v1 to 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. Putting prod in a public URL is a leak of internal structure; a custom domain with a /v1 base 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 Location to 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 equivalentWhat'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 rulesAPIM models versions and revisions explicitly; in API Gateway you compose them from APIs, stages and domain mappings
APIM revisionsAPI 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 CoreUnchanged — your code returns them; API Gateway's own errors are customised with gateway responsesGateway errors (throttling, auth) default to {"message": ...} unless you customise them
[ApiController] automatic 400ASP.NET Core 10 minimal API AddValidation() or explicit validatorsCovered in request validation
Asp.Versioning packageSame package works; or plain /v1 route groupsChoose one scheme and keep it stable
Azure Front Door caching with ETagsCloudFront / API Gateway REST API cacheDo 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):

ResourceURIMethods
Account collection (caller's own)/v1/accountsGET
Account/v1/accounts/{accountId}GET
Transactions of an account/v1/accounts/{accountId}/transactionsGET
Statement requests of an account/v1/accounts/{accountId}/statement-requestsPOST
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

SituationCodeNotes
Read succeeded200 OKBody is the resource or page
Created synchronously201 CreatedInclude Location of the new resource
Accepted for asynchronous processing202 AcceptedPOST .../statement-requests; include Location: /v1/statement-requests/{id} to poll
Success, no body204 No ContentDELETE, or PUT that returns nothing
Malformed syntax, missing required header, bad query parameter400 Bad RequestIncludes a missing Idempotency-Key; validation errors list each field
No or invalid token401 UnauthorizedSend WWW-Authenticate: Bearer; usually returned by API Gateway's authorizer before your code runs
Token valid but lacks the scope for this operation403 Forbiddene.g. token has accounts.read but calls the POST that needs statements.write
Resource does not exist or belongs to another customer404 Not FoundDeliberately indistinguishable — see below
State conflict: duplicate in-flight request, wrong state transition409 Conflicte.g. same idempotency key still processing
If-Match ETag does not match current version412 Precondition FailedOptimistic concurrency
Wrong Content-Type (e.g. XML to a JSON endpoint)415 Unsupported Media Type
Syntactically valid but semantically wrong422 Unprocessable ContenttoDate before fromDate; idempotency key reused with a different body
Rate limit exceeded429 Too Many RequestsAlways send Retry-After
Unexpected failure500 Internal Server ErrorNever leak stack traces; return traceId
Dependency down or overloaded (core banking unavailable)503 Service UnavailableRetry-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 8601 YYYY-MM-DD (DateOnly in C#). Instants are UTC with an offset: 2026-11-17T09:30:00Z (DateTimeOffset).

Version deliberately

StrategyExampleProsCons
URI path/v1/accountsVisible, cache-friendly, trivial to route in API Gateway (resource tree or base path mapping)URIs change on a major version
Custom headerApi-Version: 2026-11-01Clean URIsInvisible in logs and browser tools; REST API routing rules can match headers, but HTTP APIs cannot
Media typeAccept: application/vnd.harbourline.v2+jsonVery "pure" RESTHardest 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-1

Infrastructure 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.

Program.cs
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+json

Code explained line by line

  1. AddProblemDetails(options => ...) registers the default IProblemDetailsService; CustomizeProblemDetails runs for every problem response, including those created by UseExceptionHandler and UseStatusCodePages.
  2. ctx.ProblemDetails.Extensions["traceId"] adds an RFC 9457 extension member. Activity.Current?.TraceId is the W3C trace id OpenTelemetry propagates; the fallback is ASP.NET Core's request id.
  3. The correlation middleware accepts a caller's X-Correlation-Id only if it is short (to stop log injection and bloat), otherwise generates a UUID v7 with Guid.CreateVersion7(), and echoes it on the response.
  4. app.MapGroup("/v1") is the URI version prefix; every route in the group inherits it.
  5. Results<Ok<AccountDto>, ProblemHttpResult, StatusCodeHttpResult> declares every possible response type, which also feeds the OpenAPI document.
  6. The account lookup filters by both AccountId and CustomerId. Another customer's account and a non-existent account produce the identical 404 problem.
  7. etag is a strong validator derived from a row version; If-None-Match returns 304, saving bandwidth on mobile networks.
  8. The transactions endpoint validates pageSize against an upper bound and returns 400 with a stable type URI.
  9. PageCursor.TryDecode rejects any cursor that is not valid base64url JSON, so a tampered cursor becomes a 400, not a 500.
  10. 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.
  11. Take(size + 1) fetches one extra row to learn whether a next page exists without a COUNT(*).
  12. MoneyDto.From rounds with banker's rounding to the currency's minor unit and formats with InvariantCulture, so a server running in a de-DE culture never emits "1250,50".

Security considerations

  • Object-level authorisation in the query, not in an if after loading — a forgotten if is 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. detail is for the client; logs (with the same traceId) 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/..., /v1 stage) → 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 AddProblemDetails configuration for the whole API.

Troubleshooting

SymptomLikely causeFix
Errors come back as an empty body with a status codeUseStatusCodePages or AddProblemDetails missingRegister both; check middleware order (UseExceptionHandler first)
API Gateway returns {"message":"Missing Authentication Token"} for a valid pathPath or method not deployed, or wrong stage in the URLRedeploy the API; check the stage and resource tree (get-resources)
Client sees 1250.5 instead of 1250.50Amount serialised as a numberUse the MoneyDto string format
Page 2 repeats rows from page 1Offset pagination with new inserts, or non-unique sort keyKeyset on (bookingDate, transactionId)
"1250,50" in production onlyCulture-sensitive ToString()Always format with CultureInfo.InvariantCulture
304 never returnedETag header missing quotes, or weak/strong mismatchEmit 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-1

Exercises

  • 🟢 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 fromBookingDate and toBookingDate filters (typed DateOnly?), reject toBookingDate before fromBookingDate with 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

Knowledge check

Interview questions

  • "How do you design error responses for a public API?" — One RFC 9457 shape for every error, stable type URIs that clients branch on, human title/detail, and extension members for traceId and 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; decimal in C#.
  • "When do you return 202?" — When work continues after the response, such as statement generation; return a Location to 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

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 traceId and correlationId

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 traceId and correlationId.
  • Stages are environments; versions live in the path or in custom-domain mappings.

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