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

📚 Interview question

How do you design resource URIs for a REST API? Explain nouns vs verbs, plural collection names, how deep to nest sub-resources, when to use a sub-resource vs a top-level resource with a filter, and the naming conventions (casing, ids, trailing slashes, file extensions) you would standardise on.

URI design for REST APIs: noun-based plural collections, nesting depth and sub-resources, top-level resources with filters, identifiers, casing and other conventions worth standardising across an API.

Intermediate Theory Intermediate api-design aspnet-core rest routing uri-design web-api

🎯 Key points

  • URIs name resources with nouns; the HTTP method is the verb
  • Plural collections: /orders and /orders/{orderId}
  • Nest only for true containment/ownership, at most one level deep: /orders/{id}/lines
  • Top-level resource + filter when the child has its own identity: /shipments?orderId=42
  • Consistent casing (lowercase kebab-case paths, camelCase JSON), no trailing slash, no file extensions
  • If URL versioning is used, the version segment comes first and covers the whole surface: /v1/orders
  • Opaque, stable ids (GUIDs or non-sequential) rather than leaking database identities; never personal data in paths or query strings (logged everywhere; Privacy Act)
  • ASP.NET Core: MapGroup, route constraints ({id:guid}), LowercaseUrls

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"A URI identifies a resource, so it should be a noun, and the method carries the action. GET /orders lists orders, POST /orders creates one, GET /orders/{orderId} reads one. I use plural collection names everywhere so there's one rule to remember, and the id segment is the item.

Nesting is where most of the judgement is. I nest when the child is owned by the parent and has no meaning on its own: order lines belong to an order, so /orders/{orderId}/lines and /orders/{orderId}/lines/{lineId} are natural, and deleting the order deletes them. I stop at one level of nesting. If something has its own identity and lifecycle, like a shipment that can cover several orders, it becomes a top-level resource, /shipments/{id}, and I find the ones for an order with /shipments?orderId=42. Otherwise you end up with /customers/1/orders/2/shipments/3/items/4, where clients must know four ids to read one item and every authorisation check has to validate the whole chain. In ASP.NET Core I use MapGroup("/orders/{orderId:guid}") for the owned sub-resources and route constraints for the ids.

The mistake I see is verbs creeping into paths, like /getOrders or /orders/create, and inconsistent casing between teams. I write the conventions down: lowercase kebab-case paths, camelCase JSON, no trailing slashes, no .json extensions, opaque ids, and nothing personal like an email address in the path, because URLs land in proxy logs, Application Insights and browser history. A good URI scheme is boring and predictable, and that's the point."


Conventions worth standardising

Topic Convention Example
Resource names Plural nouns /orders, /customers
Casing Lowercase kebab-case paths /purchase-orders
JSON fields camelCase (System.Text.Json web defaults) orderDate
Ids Opaque, stable, typed in routes /orders/{orderId:guid}
Trailing slash None; redirect or treat as equal /orders not /orders/
Extensions None; use Accept not /orders.json
Actions that aren't CRUD Model as a resource or sub-resource POST /orders/{id}/cancellation
Personal data Never in path or query not /customers/[email protected]

Nest or go top-level?

Question Nest (/orders/{id}/lines) Top-level + filter (/shipments?orderId=)
Can the child exist without the parent? No Yes
Does it have its own id clients use directly? Rarely Yes
Many-to-many with the parent? No Yes
Need to query across parents? No Yes (/shipments?status=late)

Production example

An [inventory] API had routes four levels deep (/warehouses/{w}/zones/{z}/bins/{b}/items/{i}). Mobile scanners only knew the item barcode, so they made [3 extra lookups] per scan. Adding top-level /items/{barcode} with filters for warehouse and zone cut scan latency from [~800 ms to ~200 ms] and removed half the route handlers.

🔍 What the interviewer is checking

Checks whether the candidate designs URIs around resources and ownership, with consistent conventions and awareness of security and privacy.

Green flags

  • Nouns, plural collections, methods as verbs
  • Clear rule for nesting (ownership, max one level)
  • Mentions IDOR risk with nested routes
  • Keeps personal data out of URLs

Red flags

  • Verbs in paths as a default
  • Deep nesting "to show relationships"
  • No opinion on consistency or conventions

📚 Learn in depth

1. URIs identify, methods act

RFC 3986 defines URI syntax; RFC 9110 defines what methods do. Keeping actions out of URIs means the same uniform interface works for every resource and intermediaries can reason about requests (GET cacheable, PUT retryable).

Good:  GET    /orders/42
       DELETE /orders/42
Bad:   POST   /orders/42/delete
       GET    /getOrder?id=42

2. Hierarchy expresses ownership

/orders/{orderId}                 aggregate root
/orders/{orderId}/lines/{lineId}  owned entity (same lifecycle)
/shipments/{shipmentId}           separate aggregate

This lines up with DDD aggregates: nest entities inside an aggregate, keep aggregates top-level. It also helps authorisation: checking access to the order covers its lines, but you must still verify the line belongs to that order (otherwise /orders/1/lines/999 might return another order's line, an IDOR bug).

3. Identifiers

  • Sequential integers leak volume ("order 100234" tells competitors your sales) and invite enumeration.
  • GUIDs are opaque; .NET 9+ Guid.CreateVersion7() gives time-ordered values that index well in SQL Server.
  • Natural keys (SKU, ABN) are fine when stable and not personal.

4. Encoding and length

Reserved characters must be percent-encoded. Path segments with / encoded as %2F are handled inconsistently by proxies and IIS, so avoid ids that contain slashes. Keep URLs well under ~2,000 characters for older proxies and browsers.

5. ASP.NET Core routing support

  • MapGroup("/orders/{orderId:guid}/lines") shares a prefix, filters and metadata.
  • Route constraints (:guid, :int, :minlength(3)) reject malformed ids with 404 before your code runs. Don't use constraints for validation that should return 400.
  • builder.Services.Configure<RouteOptions>(o => { o.LowercaseUrls = true; }) makes generated links lowercase.

Try it yourself

  1. Draw the resource model for a small domain (customers, orders, lines, shipments) and decide which resources nest.
  2. Implement /orders/{orderId}/lines/{lineId} and write a test that requesting a line from another order returns 404.
  3. Generate a link with LinkGenerator with and without LowercaseUrls and compare.
  4. Search an Application Insights requests table for URLs containing @ to find personal data in paths.

💻 Code

Route groups for an aggregate and its owned sub-resource, plus a top-level resource with a filter.

// Program.cs (.NET 10)
var builder = WebApplication.CreateBuilder(args);
builder.Services.Configure<RouteOptions>(o => o.LowercaseUrls = true);
var app = builder.Build();

var orders = app.MapGroup("/orders").WithTags("Orders");
orders.MapGet("/", () => Results.Ok(Array.Empty<OrderDto>()));
orders.MapGet("/{orderId:guid}", (Guid orderId) => Results.Ok(new OrderDto(orderId, "Open")));

// Owned sub-resource: one level deep. Always check the line belongs to this order.
var lines = orders.MapGroup("/{orderId:guid}/lines");
lines.MapGet("/{lineId:guid}", (Guid orderId, Guid lineId) =>
    LineStore.Find(orderId, lineId) is { } line ? Results.Ok(line) : Results.NotFound());

// Separate aggregate: top-level, filtered by the related id.
app.MapGet("/shipments", (Guid? orderId, string? status) =>
    Results.Ok(ShipmentStore.Query(orderId, status)));

app.Run();

public sealed record OrderDto(Guid Id, string Status);
public sealed record LineDto(Guid Id, Guid OrderId, string Sku, int Quantity);
public sealed record ShipmentDto(Guid Id, string Status, IReadOnlyList<Guid> OrderIds);

static class LineStore
{
    static readonly List<LineDto> Lines = [];
    // Filtering by both ids prevents /orders/A/lines/{line of B} (IDOR).
    public static LineDto? Find(Guid orderId, Guid lineId) =>
        Lines.FirstOrDefault(l => l.Id == lineId && l.OrderId == orderId);
}

static class ShipmentStore
{
    static readonly List<ShipmentDto> Shipments = [];
    public static IEnumerable<ShipmentDto> Query(Guid? orderId, string? status) =>
        Shipments.Where(s => (orderId is null || s.OrderIds.Contains(orderId.Value))
                          && (status is null || s.Status == status));
}

⚠ Common mistakes

  • Mistake: Verbs in paths (/getOrders, /orders/create). Why it is wrong: It duplicates what the method already says and leads to RPC-style APIs. Instead: Nouns in paths, methods for actions; model genuine actions as resources (/orders/{id}/cancellation).
  • Mistake: Nesting three or four levels deep. Why it is wrong: Clients need every parent id, routes multiply, and authorisation must validate the whole chain. Instead: Nest one level for owned entities; make independent things top-level with filters.
  • Mistake: Not checking that a nested child belongs to its parent. Why it is wrong: /orders/1/lines/999 can return another order's line, an insecure direct object reference. Instead: Query by both ids.
  • Mistake: Mixing singular and plural or different casing across teams. Why it is wrong: Clients guess wrong and SDK generators produce inconsistent names. Instead: Write a style guide and lint the OpenAPI document.
  • Mistake: Putting emails, names or tokens in URLs. Why it is wrong: URLs are logged by proxies, CDNs, Application Insights and browsers, a Privacy Act exposure. Instead: Use opaque ids and put sensitive values in the body or headers.
  • Mistake: Exposing sequential database ids. Why it is wrong: They leak business volume and invite enumeration. Instead: Use GUIDs (v7 for index locality) or other opaque public ids.
  • Mistake: Using route constraints as validation. Why it is wrong: A failed constraint returns 404, not a helpful 400. Instead: Use constraints to disambiguate routes and validate values in the handler.

🏛 Senior insight: trade-offs

URI design is a long-lived public contract, so I optimise for predictability over cleverness. The real decision is where aggregate boundaries are: owned entities nest, independent aggregates stand alone. That aligns URIs with transactional boundaries in the domain model and keeps authorisation checks local.

URI shape also has a performance cost that shows up on the client. Deep hierarchies force clients to resolve parent ids first, so a mobile screen that needs one item can cost three or four sequential round trips; at 150 ms each on a 4G connection that is half a second before rendering. Flat, cacheable item URIs (/items/{id} with Cache-Control and an ETag) let a CDN or the client cache serve repeat reads, and a single canonical URI per resource means one cache entry rather than several aliases that must be invalidated together. If the API is versioned in the path, put the version first (/v1/...) and version the whole surface, not individual resources, so URIs stay consistent.

I enforce conventions with tooling rather than review comments: a Spectral ruleset on the generated OpenAPI document in CI (plural nouns, kebab-case, no verbs, max nesting depth) catches drift across teams.

Option When it fits Cost When not
Nested sub-resource Owned entity, same lifecycle Parent id always required; extra lookups for clients Child has its own identity or many parents
Top-level + filter Independent aggregate, cross-parent queries Ownership less visible Child meaningless alone
Action as sub-resource (/cancellation) State transitions with their own data More resources to document Simple field updates (use PATCH)
Alias URIs for the same resource Rarely Duplicate cache entries, invalidation bugs Almost always: prefer one canonical URI

🔗 Follow-ups the interviewer may ask

  1. When: Candidate suggests a top-level resource with filters Why: Checks how filters, arrays and ranges are expressed in the query string
    How to answer

    The query string shapes a collection: filters, sorting, paging and field selection, while the path holds identity. Pick conventions and apply them everywhere: repeated keys for arrays (?status=open&status=held, which ASP.NET Core binds to string[] natively), explicit range names (createdFrom, createdTo) with ISO 8601 values, and allow-listed sort and filter fields so nothing raw reaches SQL.

    Values must be percent-encoded, and URLs have practical limits: Kestrel caps the request line at 8 KB, IIS defaults maxQueryString to 2,048 characters, and proxies vary. URLs are logged everywhere, so never put personal data or secrets in them. When criteria get large, complex or sensitive, use POST /orders/search with a body. The trade-off: GET is cacheable and bookmarkable; POST handles big or private criteria but loses caching.

  2. When: Candidate mentions avoiding verbs in URLs Why: Checks whether they can spot RPC-style URIs and redesign them
    How to answer

    Ranked by severity:

    1. State change on GET: crawlers, link previews, prefetchers and caches will cancel orders, and an <img src> on any site becomes a CSRF attack.
    2. 200 with success: false: failures are invisible to monitoring, SLOs, retry policies and gateways; clients must parse every body.
    3. POST for everything: no caching, no safe retries, no idempotency signal.
    4. Verbs in URLs: duplicate the method and fragment the resource model.

    The redesign: resources (/orders, /orders/{id}), proper methods (GET, POST with 201 + Location, PATCH, DELETE), state transitions as POST /orders/{id}/cancellation returning 409 when not allowed, and ProblemDetails errors. Migrate by running new routes alongside old ones with Deprecation/Sunset headers, rather than breaking clients.

↩ Usually asked after

More in REST

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me