📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

You're asked to design a public REST API that external partners will integrate with for years. How do you approach the resource model, naming and consistency, versioning and evolution, errors, pagination, security, documentation and SDKs, and which published guidelines (such as Microsoft's REST API guidelines) would you base your standards on?

Designing a long-lived partner-facing REST API: domain-driven resource model, consistent conventions, a guideline baseline (Azure / Microsoft Graph REST API guidelines, Google AIP, Zalando), evolution and versioning policy, errors, paging, security, and the documentation and SDK experience, on ASP.NET Core 10 and Azure API Management.

Senior Architecture Advanced api-design api-guidelines architecture azure-api-management rest web-api

🎯 Key points

  • Start from partner use cases and the domain: resources map to stable business concepts (aggregates), not database tables
  • Adopt a current published baseline and write a short house style: the Azure REST API guidelines or Microsoft Graph guidelines (Microsoft's original general guidelines are deprecated), Google AIP; Zalando's guidelines as a pragmatic extra reference
  • Consistency rules: plural nouns, camelCase JSON, ISO 8601 with offsets, decimal money with currency, opaque string ids, one paging and error shape everywhere
  • Evolution: additive optional changes only within a version (a new required field or stricter validation is breaking), tolerant readers, Deprecation/Sunset headers, major versions rarely
  • Errors: RFC 9457 ProblemDetails with stable machine-readable error codes; paging: cursor-based with nextLink and max page size
  • Security and limits: OAuth 2.0 client credentials (Entra ID), per-partner scopes, documented rate limits with 429 + Retry-After, idempotency keys on POST, signed webhooks
  • Developer experience: OpenAPI as the contract, examples, sandbox, changelog, generated SDKs (Kiota/NSwag), developer portal in Azure API Management
  • Governance: design reviews, Spectral linting in CI, breaking-change detection (OpenAPI diff), consumer contract tests, proactive change communication to partners

⏱ 30-second answer

I start from partner use cases and the domain, modelling resources around stable business concepts rather than tables. I adopt a published baseline (the Azure or Microsoft Graph REST API guidelines, which replaced Microsoft's original general guidelines; Google AIP or Zalando are good alternatives) and write a short house style: naming, JSON conventions, dates with offsets, money as decimal plus currency, opaque ids, one error shape (RFC 9457 ProblemDetails with error codes) and one paging shape (cursor plus nextLink).

Then I design for evolution: additive changes only, tolerant readers, a written deprecation policy with Sunset headers, and rare major versions. Security is OAuth 2.0 client credentials with scopes, rate limits and idempotency keys. Partners experience the API through OpenAPI, examples, a sandbox, SDKs and a changelog. The trade-off is upfront design and governance effort versus years of breaking partner integrations.

🗣 Full answer (senior)

How I would answer this in an interview

"For a partner API that has to last years, the expensive mistakes are the ones you can't take back: names, identifiers, the shape of errors and paging, and how you change things. So I front-load those decisions. I start with the partner use cases, for example 'a retailer submits orders, tracks fulfilment and gets notified of changes', and map them to resources that reflect stable business concepts: orders, shipments, products. Not our database tables, because the schema will change long before the contract can.

Rather than inventing standards, I adopt a published baseline. Microsoft's original general REST API Guidelines have been deprecated and split into the Azure REST API guidelines and the Microsoft Graph guidelines; the Azure ones are very good for things like long-running operations, paging with nextLink and error shapes. Google's AIPs and Zalando's guidelines are also solid. On top of that I write a short house style: plural nouns, camelCase JSON, ISO 8601 timestamps with offsets, money as a decimal string plus currency, opaque string ids, ProblemDetails with stable error codes, cursor-based paging with a maximum page size. For example, at [company] we [had three teams exposing partner endpoints with three error formats]; I [wrote a two-page style guide and a Spectral ruleset], and [partner integration time dropped from about six weeks to two].

Evolution is the other half. Within a version I allow only additive changes, I tell partners to be tolerant readers, especially of new enum values, and I publish a deprecation policy: at least [12] months' notice, Deprecation and Sunset headers, usage tracking per partner in API Management so we know who's still calling the old thing. Security is OAuth 2.0 client credentials through Entra ID with per-partner scopes, rate limits returning 429 with Retry-After, and idempotency keys on POSTs. And the developer experience counts as much as the design: OpenAPI as the source of truth, real examples, a sandbox, generated SDKs and a changelog. The mistake I see is treating a partner API like an internal one and fixing consistency later; for a public API, consistency is the design."


Decisions to make early (hard to change later)

Area Decision My default
Resource model Business concepts and ownership Aggregates as top-level resources, owned entities nested one level
Identifiers Format and exposure Opaque strings (e.g. ord_01J...), never database ints
JSON conventions Casing, nulls, dates, money camelCase; omit vs null documented; ISO 8601 with offset; {"amount":"12.50","currency":"AUD"}
Errors One shape RFC 9457 ProblemDetails + code + traceId + field errors
Paging One shape Cursor, nextLink, maxPageSize cap
Versioning Scheme and policy Major version in URL or header; additive changes within a version
Async work Pattern 202 + Operation-Location
Events Push model Signed webhooks (HMAC), retries, event ids for dedup
Security Auth model OAuth 2.0 client credentials, scopes per capability

Guideline baselines

Guideline Strength
Azure REST API guidelines LROs, paging, errors, versioning by api-version
Microsoft Graph REST API guidelines Large multi-team consistency, OData conventions
Google AIP Resource-oriented design, standard methods
Zalando RESTful API guidelines Pragmatic, well-reasoned MUST/SHOULD rules

Production example

A [logistics] partner API was launched with a style guide, Spectral linting and an OpenAPI diff check in CI. Over [18 months] it shipped [40+] additive releases with [no] breaking changes, and the number of partner support tickets about "unexpected responses" fell [by about 70%] compared with the previous API.

🔍 What the interviewer is checking

Checks whether the candidate can set direction for a long-lived external API: domain-driven resources, consistent conventions grounded in current published guidelines and applied in practice, a credible evolution policy, security and partner experience.

Green flags

  • Starts from partner use cases and the domain, not tables
  • Names real guideline sources, knows their current state, and explains how they turned them into enforced rules (linting, reviews) on a real project
  • Has concrete conventions for dates, money, ids, errors and paging
  • Explains additive evolution, tolerant readers and deprecation with telemetry and partner communication
  • Covers OAuth scopes, rate limits, idempotency and developer experience

Red flags

  • Jumps straight to controllers and code
  • No versioning or deprecation policy
  • Inconsistent conventions "to be fixed later"
  • Shared API keys in URLs, money as double

📚 Learn in depth

1. Contract-first architecture

Partner use cases -> resource model -> OpenAPI draft -> design review + Spectral lint
                                          |                     |
                                   mock server / sandbox    breaking-change check (oasdiff)
                                          |
                         ASP.NET Core implementation (validated against the spec)
                                          |
                    Azure API Management (auth, rate limits, analytics, dev portal)

The OpenAPI document is reviewed like code. Implementation can be code-first with the built-in Microsoft.AspNetCore.OpenApi generator, as long as CI compares the generated document with the approved one.

2. Consistency is the product

Partners integrate many endpoints. If one returns created_at and another createdDate, or paging differs per resource, every SDK and client needs special cases. Consistency rules worth enforcing with linting:

  • casing, plural nouns, max nesting depth;
  • every list endpoint uses the shared paging schema;
  • every 4xx/5xx response references the shared ProblemDetails schema;
  • every operation has an operationId, a summary and examples.

3. Data conventions that bite later

Topic Pitfall Convention
Dates DateTime without offset is ambiguous across AEST/AEDT DateTimeOffset, ISO 8601 with offset or UTC Z
Money double rounding; missing currency Decimal (often as string) + ISO 4217 currency
Enums New values break strict clients Document as extensible; clients must handle unknown
Ids Sequential ints leak volume Opaque prefixed strings
Nulls Absent vs null ambiguity Document; avoid meaning differences except in PATCH

4. Evolution mechanics

  • Non-breaking: new optional fields, new endpoints, new optional query parameters, new enum values (if documented as extensible).
  • Breaking: removing or renaming fields, changing types, making validation stricter, changing defaults, changing error codes.
  • Deprecation: Deprecation header (RFC 9745) and Sunset header (RFC 8594) on old endpoints; APIM analytics by subscription to find remaining callers; direct outreach before the sunset date.

5. Security and fairness

  • OAuth 2.0 client credentials via Entra ID; scopes per capability (orders.read, orders.write); certificate credentials or federated identity rather than shared secrets where possible.
  • Rate limits per partner subscription in APIM (rate-limit-by-key), returning 429 + Retry-After.
  • Idempotency keys on POST; signed webhooks with timestamps to stop replay.
  • Australian context: if partner data includes personal information, the Privacy Act 1988 and APPs apply; keep personal data out of URLs, log minimally, and host in Australia East / Southeast if data residency is promised.

6. Developer experience

Portal with interactive docs, copy-paste examples per language, a sandbox with seeded data, a changelog with dates, SDKs generated by Kiota or NSwag, and a status page. Measure time-to-first-successful-call for new partners.

Try it yourself

  1. Write a one-page style guide for a sample domain and encode three rules as a Spectral ruleset; run it against an ASP.NET Core-generated OpenAPI document.
  2. Run oasdiff breaking between two versions of a spec where you rename a field and add an enum value; compare results.
  3. Configure an APIM product with rate-limit-by-key on subscription id and test the 429 + Retry-After.
  4. Generate a client with Kiota from your spec and write a tiny partner integration against the sandbox.

💻 Code

Shared conventions enforced in code: one ProblemDetails shape with error codes and trace ids, a standard paged response with nextLink, money and date types, and a deprecation header.

// Program.cs (.NET 10)
using System.Diagnostics;
using System.Text.Json;
using System.Text.Json.Serialization;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenApi();
builder.Services.ConfigureHttpJsonOptions(o =>
{
    o.SerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
    o.SerializerOptions.Converters.Add(new JsonStringEnumConverter());   // enums as strings, documented as extensible
    o.SerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
});
// One error shape everywhere (RFC 9457) with a stable code and the trace id for support.
builder.Services.AddProblemDetails(o => o.CustomizeProblemDetails = ctx =>
{
    ctx.ProblemDetails.Extensions["traceId"] = Activity.Current?.Id ?? ctx.HttpContext.TraceIdentifier;
    ctx.ProblemDetails.Extensions.TryAdd("code", "error");
});
var app = builder.Build();
app.MapOpenApi();

const int MaxPageSize = 100;

var v1 = app.MapGroup("/v1");
v1.MapGet("/orders", (string? cursor, int? pageSize, HttpContext ctx) =>
{
    var size = Math.Clamp(pageSize ?? 25, 1, MaxPageSize);       // never unbounded
    var (items, next) = OrderQueries.Page(cursor, size);
    var nextLink = next is null ? null : $"/v1/orders?cursor={Uri.EscapeDataString(next)}&pageSize={size}";
    return TypedResults.Ok(new Page<OrderDto>(items, nextLink));
});

v1.MapGet("/orders/{id}", (string id) =>
    OrderQueries.Find(id) is { } o
        ? Results.Ok(o)
        : Results.Problem(statusCode: 404, title: "Order not found",
            extensions: new Dictionary<string, object?> { ["code"] = "order_not_found" }));

// An endpoint being retired: tell clients in-band, months ahead.
v1.MapGet("/order-summaries", (HttpResponse res) =>
{
    res.Headers["Deprecation"] = "@1767225600";                    // RFC 9745: deprecated since 2026-01-01
    res.Headers["Sunset"] = "Thu, 31 Dec 2026 23:59:59 GMT";       // RFC 8594
    res.Headers.Link = "</v1/orders>; rel=\"successor-version\"";
    return Results.Ok(Array.Empty<object>());
});

app.Run();

public sealed record Money(decimal Amount, string Currency);                       // never double
public sealed record OrderDto(string Id, string Status, Money Total, DateTimeOffset CreatedAt);
public sealed record Page<T>(IReadOnlyList<T> Items, string? NextLink);

static class OrderQueries
{
    static readonly List<OrderDto> Orders =
        [new("ord_01JD8Y3K", "Pending", new(120.50m, "AUD"), DateTimeOffset.Parse("2026-11-02T09:15:00+11:00"))];
    public static (IReadOnlyList<OrderDto> Items, string? Next) Page(string? cursor, int size) =>
        (Orders.Where(o => cursor is null || string.CompareOrdinal(o.Id, cursor) > 0).Take(size).ToList(), null);
    public static OrderDto? Find(string id) => Orders.FirstOrDefault(o => o.Id == id);
}

⚠ Common mistakes

  • Mistake: Exposing the database schema as the resource model. Why it is wrong: Every schema refactor becomes a breaking change for partners. Instead: Model stable business concepts and map with DTOs.
  • Mistake: Inventing conventions per team or per endpoint. Why it is wrong: Partners hit different error, paging and naming styles, and SDKs need special cases. Instead: Adopt a current published baseline plus a short house style, enforced with Spectral.
  • Mistake: Treating new enum values, new required fields or stricter validation as non-breaking without telling anyone. Why it is wrong: Strict clients crash on unknown values, and requests that worked yesterday start failing. Instead: Only add optional fields within a version, document enums as extensible, and treat new required inputs and stricter validation as breaking.
  • Mistake: Removing endpoints without telemetry or notice. Why it is wrong: You break partners you didn't know were still calling them. Instead: Deprecation/Sunset headers, APIM analytics per subscription, changelog entries and direct outreach.
  • Mistake: Undocumented or surprising rate limits. Why it is wrong: Partners discover limits in production as unexplained 429s or, worse, 503s, and retry aggressively, making it worse. Instead: Publish limits per plan, return 429 with Retry-After and a ProblemDetails body, expose remaining quota headers, and give partners a way to request higher limits.
  • Mistake: Shared API keys in query strings. Why it is wrong: They leak in logs and can't be scoped or rotated cleanly. Instead: OAuth 2.0 client credentials with scopes, keys only in headers if used at all.
  • Mistake: DateTime without offset and money as double. Why it is wrong: Time zone bugs (AEST vs AEDT) and rounding errors in financial data. Instead: DateTimeOffset in ISO 8601 and decimal amounts with currency.
  • Mistake: Unbounded list endpoints. Why it is wrong: One partner can request everything and hurt every other partner. Instead: Cursor paging with a maximum page size, plus rate limits.

🏛 Senior insight: trade-offs

For a public API, the design artefact that matters most is the set of conventions and the evolution policy, not any single endpoint. Endpoints are cheap to add; inconsistency and breaking changes are expensive forever, because partners integrate once and resist changing. I therefore invest in a baseline guideline, linting and breaking-change detection in CI, and usage analytics so that decisions about deprecation are based on who actually calls what. Backward compatibility is the default promise; when a break is unavoidable, it goes into a new major version with a published migration guide, a long overlap period and direct contact with every affected partner.

I default to simplicity (no hypermedia framework, no GraphQL layer, one major version for as long as additive evolution works) but I let partner needs override that: if large partners need bulk endpoints, webhooks with replay, or field selection to cut payload sizes, those are worth the added complexity because they remove real integration pain. I'd measure time-to-first-call for new partners, support tickets per partner, the number of breaking-change exceptions granted, and traffic on deprecated endpoints.

Choice When it fits Cost When not
Adopt Azure / Graph guideline as-is Small team, quick start Some rules won't fit your domain You already have a mature internal standard
Baseline + short house style Most partner APIs Writing and maintaining the style guide Never really wrong
URL major versioning (/v1) Partners prefer visible versions Version proliferation if overused Internal APIs released with their clients
Header / api-version query versioning Azure-style, many independent resources Less visible, needs tooling Simple partner APIs
Generated SDKs Many partners, several languages Maintaining generators and releases One or two partners
Extra capabilities (bulk, webhooks, field selection) Partners demonstrably need them More surface to secure and support Speculative "nice to have"

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions naming and resource conventions Why: Checks URI conventions and nesting decisions in detail
    How to answer

    URIs name resources, so use nouns, and let the HTTP method be the verb: GET /orders, POST /orders, GET /orders/{orderId}. Use plural collection names consistently. Nest only when the child is owned by and meaningless without the parent (/orders/{id}/lines), and keep it to one level; if the child has its own identity, make it top-level and filter (/shipments?orderId=42). Standardise lowercase kebab-case paths, no trailing slashes or file extensions, and opaque, stable ids. Keep personal data out of URLs because they end up in logs.

    The trade-off: deep nesting reads nicely but couples clients to a hierarchy and multiplies routes; flat resources with filters are more flexible but lose the visible ownership.

  2. When: Candidate mentions asynchronous operations or Operation-Location Why: Checks how long-running partner operations are modelled
    How to answer

    Treat state transitions with business rules as commands: POST /orders/{id}/cancellation (a sub-resource, or /cancel if you prefer verbs for actions) makes intent explicit, lets you validate and authorise that transition, and returns 409 Conflict when it isn't allowed. PATCH {"status":"Cancelled"} looks RESTful but hides intent and invites invalid transitions.

    For long-running work, use the asynchronous request-reply pattern: return 202 Accepted with a Location (or Operation-Location) pointing at a status resource and a Retry-After header; a background worker does the job and updates the status (Running, Succeeded, Failed), and the finished status links to the result. The trade-off is extra state and polling versus holding HTTP requests open and hitting gateway timeouts.

  3. When: Candidate mentions webhooks or alternative API styles Why: Checks whether REST is the right style for each partner need (events, bulk)
    How to answer

    REST is the default for public and partner APIs: universal client support, HTTP caching and simple tooling. gRPC suits internal service-to-service calls: protobuf contracts, HTTP/2, binary payloads and streaming, but weak browser support. GraphQL fits varied front ends that need different shapes of the same data, at the cost of HTTP caching, resolver N+1 problems and query cost limits. Asynchronous messaging (Azure Service Bus, Event Grid) is for decoupling in time: events, long-running work and load levelling, with at-least-once delivery and eventual consistency.

    Most real systems mix them: REST or GraphQL at the edge, gRPC or REST between services, messaging for events. The trade-off is always coupling and simplicity vs efficiency and flexibility.

🛠 Real-world problems: how you handle them

Three teams, three error formats: standardising a partner API
Situation
A [logistics platform] exposed partner endpoints built by [three] teams over [two] years. [~60] partners integrated, each taking [~6 weeks]. Leadership wanted to open the API to [200+] partners within a year.
Signals
Partner support tickets about inconsistent responses ([~40] a month); three error formats and two paging styles in the OpenAPI documents; SDK generation produced awkward per-endpoint special cases; APIM analytics showed partners still calling endpoints teams believed unused.
Investigation
Ran Spectral with a draft ruleset over the three OpenAPI documents and counted violations per rule; reviewed support tickets by category; used APIM analytics by subscription to see which endpoints and versions each partner used; interviewed [five] partner developers about integration pain.
Resolution
Wrote a two-page house style on top of the Azure REST API guidelines (ProblemDetails with codes, cursor paging with nextLink, DateTimeOffset, money objects, opaque ids). New endpoints had to comply immediately; existing inconsistent endpoints got compliant replacements alongside, with `Deprecation`/`Sunset` headers and a 12-month migration window tracked per partner. Added Kiota-generated SDKs and a sandbox in the APIM developer portal.
Prevention
Spectral and oasdiff breaking-change checks in every API pipeline; an API design review for new resources; a changelog; dashboards for deprecated endpoint traffic per partner and time-to-first-call for new partners.

How to tell it (STAR)

**S:** At [company], our partner API had been built by three teams, with three error formats and two paging styles, and each partner took about [six weeks] to integrate. **T:** We needed to scale to [200+] partners, and I was asked to lead the API standards work. **A:** I measured the inconsistencies with a Spectral ruleset and APIM analytics, wrote a short house style based on the Azure REST API guidelines, and got the three teams to agree it in a design review. We shipped compliant replacements next to the old endpoints with Sunset headers, tracked migration per partner, and added generated SDKs and a sandbox. **R:** New partner integration time fell to [about two weeks], consistency-related tickets dropped [~70%], and we retired the old endpoints on schedule with [no] partner outages.

↩ Usually asked after

More in REST

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me