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

📚 Interview question

Code review: a customer API returns its EF Core entities directly. The response includes internal database ids and a PasswordHash, property names mix PascalCase and snake_case, dates are DateTime with no offset, money is a double, and the list endpoint has no page-size limit. What problems do you find, ranked by severity, and how would you redesign the DTOs?

Code review of API response contracts: data exposure from returning entities, over-posting, unbounded lists, money as double, dates without offsets, inconsistent naming and internal ids, with a DTO-based rewrite.

Senior CodeReview Advanced api-design code-review dto security system-text-json web-api

🎯 Key points

  • Returning entities leaks sensitive fields (PasswordHash, internal flags): a security and Privacy Act issue
  • Binding entities from requests enables over-posting (mass assignment)
  • Unbounded list is a denial-of-service and memory risk; cap page size and paginate
  • Money as double loses precision; use decimal and send amount as string or minor units plus ISO 4217 currency
  • DateTime without offset is ambiguous across time zones; use DateTimeOffset, ISO 8601 with offset or UTC
  • Inconsistent naming breaks generated clients; one JSON naming policy (camelCase)
  • Sequential internal ids enable enumeration and couple clients to the database; consider public ids
  • Purpose-built request and response DTOs, explicit mapping, projection in the query

⏱ 30-second answer

Ranked by severity:

  1. Data exposure: returning entities serialises everything, including PasswordHash and internal flags. That's a security finding and, for personal data, a Privacy Act issue. Binding entities from requests also enables over-posting.
  2. Unbounded list: no page-size limit means one call can load the table: a denial-of-service and memory risk.
  3. Wrong data: double money loses precision (use decimal, send amounts as strings or minor units with an ISO 4217 currency); DateTime without an offset is ambiguous across Australian time zones (use DateTimeOffset).
  4. Contract hygiene: mixed naming breaks generated clients; sequential database ids enable enumeration and couple clients to storage.

The fix is purpose-built request and response DTOs, projected in the query, with one JSON naming policy and cursor pagination. The trade-off is mapping code, which is cheap next to an incident.

🗣 Full answer (senior)

How I would answer this in an interview

"I'd rank these by blast radius. The worst is returning EF Core entities directly. The serialiser writes every public property, so PasswordHash, IsFraudFlagged, internal notes and anything added to the entity later go to every client. That's a security finding on day one and, because it's personal information, a potential notifiable data breach under the Privacy Act. The same entity used as a request body enables over-posting: a client sends isAdmin: true and model binding happily sets it. Second is the list endpoint with no page-size limit. One request for all customers loads the table into memory, serialises it, and can take the instance down, so that's an availability problem anyone can trigger.

Then the wrong-data issues. Money as double is binary floating point, so 0.1 plus 0.2 isn't 0.3, and totals drift by cents, which finance will find. Use decimal in C#, and on the wire send the amount as a string or as integer minor units with an ISO 4217 currency code, because JavaScript clients parse JSON numbers as doubles anyway. Dates as DateTime with no offset are ambiguous: is 9:00 Sydney time, Perth time or UTC? Use DateTimeOffset and ISO 8601 with an offset. For example, at [company] we [had an order cut-off bug where Western Australian customers saw times three hours off] because [the API emitted unspecified DateTime values], which took [a week] to untangle.

Finally the contract hygiene: mixed PascalCase and snake_case means generated clients get ugly, inconsistent models, so pick camelCase via JsonSerializerDefaults.Web and stick to it. Sequential int ids let anyone enumerate /customers/1, /customers/2 and couple clients to your database; I'd expose a public id and always authorise per resource anyway. The rewrite is purpose-built DTOs, projected in the query with Select so we never load what we don't return, plus cursor pagination with a capped page size."


Code under review

// Customer entity used directly as the API contract
public class Customer
{
    public int Id { get; set; }                       // 5 sequential DB id exposed
    public string FullName { get; set; } = "";
    public string email_address { get; set; } = "";  // 4 inconsistent naming
    public string PasswordHash { get; set; } = "";    // 1 sensitive field serialised
    public bool IsAdmin { get; set; }                 // 1 over-posting target
    public double CreditLimit { get; set; }           // 3 money as double
    public DateTime CreatedAt { get; set; }           // 3 no offset
    public List<Order> Orders { get; set; } = [];     // 1 lazy graph, cycles
}

app.MapGet("/customers", async (AppDb db) =>
    await db.Customers.Include(c => c.Orders).ToListAsync());   // 2 unbounded, whole graph

app.MapPut("/customers/{id}", async (int id, Customer input, AppDb db) =>
{
    db.Update(input);                                            // 1 over-posting: IsAdmin, PasswordHash
    await db.SaveChangesAsync();
    return Results.Ok(input);
});

Findings by severity

# Severity Finding Impact
1 Security Entity returned and bound: PasswordHash, IsAdmin exposed and writable Credential exposure, privilege escalation, Privacy Act breach
2 Availability ToListAsync() with no limit, Include of whole graph Memory blow-up, timeouts, easy denial of service
3 Wrong data double money, DateTime without offset Rounding errors in totals; wrong times across time zones
4 Contract Mixed naming (FullName, email_address) Inconsistent generated clients, frequent client bugs
5 Design Sequential DB ids, no per-resource authorisation shown Enumeration (BOLA), coupling to storage

The rewrite

Separate DTOs, projection, capped cursor pagination and a narrow update command. Full code in the code example section.

How I'd close the review

  • Blocking: findings 1 and 2. No merge until entities are no longer serialised or bound and the list is paginated with a cap.
  • Blocking for a public API: finding 3, because changing money or date formats later is a breaking change.
  • Suggested: naming policy and public ids, with an ADR.
  • Prevent recurrence: an architecture test (NetArchTest) that fails if an endpoint returns a type from the Domain or Data namespace; Spectral rules for camelCase and format: date-time; a checklist item for page-size limits.

Production example

In a similar review, the customer endpoint was returning [about 40] properties per record including a password hash; after the rewrite the response had [9] fields, payload size dropped by [80]%, and p95 latency on the list fell from [1.2 s] to [90 ms] because projection stopped loading the orders graph.

🔍 What the interviewer is checking

Checks that the candidate can review an API contract for security, availability and correctness issues, rank them sensibly and propose a robust DTO design.

Green flags

  • Ranks data exposure and over-posting first, then unbounded queries
  • Explains why double and unspecified DateTime are wrong, with the fix
  • Uses projection, request DTOs and capped pagination
  • Proposes automated prevention (architecture tests, linting)

Red flags

  • Fixes exposure with [JsonIgnore] only
  • Ranks naming above security
  • Treats opaque ids as authorisation

📚 Learn in depth

1. Why entities make bad contracts

EF Core entity  ──────►  System.Text.Json  ──────►  client
 (every public property,      (serialises all       (now depends on all of it,
  navigation properties,       public properties)     including fields you'll
  fields added next sprint)                           want to remove)

An entity is shaped for persistence and the domain; a DTO is shaped for one client use case. Coupling them means every schema change is an API change, and every sensitive column added later is exposed by default. OWASP API Security Top 10 calls this Broken Object Property Level Authorization (excessive data exposure plus mass assignment).

2. Over-posting

Model binding sets any property present in the JSON. With an entity as input:

PUT /customers/42
{ "fullName": "Jane", "isAdmin": true, "passwordHash": "..." }

db.Update(input) marks every property modified, so it also overwrites columns the client didn't send with defaults. The fix is a request DTO containing only editable fields, and applying them to a loaded entity.

3. Money on the wire

Representation Precision Client safety
double / JSON number from double Binary floating point; 0.1 not exact Rounding errors
decimal as JSON number Exact in .NET JavaScript parses into a double: risk above 2^53 or with many decimals
Amount as string "120.50" + currency Exact Safe everywhere
Minor units 12050 + currency Exact integer Safe; clients must know the exponent (AUD 2, JPY 0)

Always include the ISO 4217 currency code, even if you only deal in AUD today.

4. Dates and time zones

DateTime has a Kind (Utc, Local, Unspecified). System.Text.Json writes Unspecified without an offset, so 2026-11-20T09:00:00 reaches clients as an ambiguous local time. Australia has several offsets (AEST/AEDT, ACST/ACDT, AWST), and Queensland has no daylight saving, so ambiguity causes real bugs. Use DateTimeOffset for instants, DateOnly for dates like a birthday, and send IANA time zone ids (Australia/Perth) when a local time matters.

5. Identifiers

Sequential ids leak volume ("order 10,482 means they've had ten thousand orders") and invite enumeration. A public id (GUID v7 or a prefixed opaque id like cus_8f3k...) avoids that, but it is not authorisation. Every request must still check the caller can access that resource (OWASP API1: Broken Object Level Authorization).

6. Projection

Select into a DTO lets EF Core generate SQL for only the needed columns and no Include. That's both safer and faster than loading entities and mapping in memory.

Try it yourself

  1. Return an entity with a PasswordHash from a Minimal API and look at the JSON; then switch to a DTO.
  2. Post isAdmin: true to an endpoint bound to the entity and observe it saved.
  3. Sum 0.1 ten times as double and as decimal and compare.
  4. Serialise DateTime.Now, DateTime.UtcNow and DateTimeOffset.Now with System.Text.Json and compare the output.
  5. Write a NetArchTest rule that fails when an endpoint returns a type from the Data namespace.

💻 Code

The rewrite: response and request DTOs, projection, safe money and dates, capped pagination and a narrow update.

// Customers/CustomerContracts.cs
namespace Shop.Api.Customers;

public sealed record MoneyDto(string Amount, string Currency);        // "5000.00", "AUD"

public sealed record CustomerDto(
    string Id,                    // public id, not the database key
    string FullName,
    string Email,
    MoneyDto CreditLimit,
    DateTimeOffset CreatedAt);    // ISO 8601 with offset

public sealed record UpdateCustomerRequest(string FullName, string Email); // only editable fields

public sealed record CustomerPage(IReadOnlyList<CustomerDto> Items, string? NextCursor);
// Customers/CustomerEndpoints.cs
using System.Globalization;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.EntityFrameworkCore;

namespace Shop.Api.Customers;

public static class CustomerEndpoints
{
    private const int MaxLimit = 100;

    public static void MapCustomers(this IEndpointRouteBuilder app)
    {
        var group = app.MapGroup("/v1/customers").RequireAuthorization("customers:read");

        group.MapGet("/", async (int? limit, string? after, AppDb db, CancellationToken ct) =>
        {
            var take = Math.Clamp(limit ?? 25, 1, MaxLimit);            // capped page size
            var afterId = CursorCodec.Decode(after);                     // opaque cursor -> internal key

            var rows = await db.Customers.AsNoTracking()
                .Where(c => afterId == null || c.Id > afterId)
                .OrderBy(c => c.Id)
                .Take(take + 1)
                // Projection: only these columns are queried; PasswordHash never leaves the database.
                .Select(c => new { c.Id, c.PublicId, c.FullName, c.Email, c.CreditLimit, c.CreatedAt })
                .ToListAsync(ct);

            var hasMore = rows.Count > take;
            var page = rows.Take(take).Select(c => new CustomerDto(
                c.PublicId, c.FullName, c.Email,
                new MoneyDto(c.CreditLimit.ToString("0.00", CultureInfo.InvariantCulture), "AUD"),
                c.CreatedAt)).ToList();

            return TypedResults.Ok(new CustomerPage(page, hasMore ? CursorCodec.Encode(rows[take - 1].Id) : null));
        });

        group.MapPut("/{publicId}", async Task<Results<NoContent, NotFound>> (
            string publicId, UpdateCustomerRequest req, AppDb db, CancellationToken ct) =>
        {
            var customer = await db.Customers.SingleOrDefaultAsync(c => c.PublicId == publicId, ct);
            if (customer is null) return TypedResults.NotFound();
            // Per-resource authorisation check would go here (caller owns or may manage this customer).

            // Apply only editable fields: no IsAdmin, no PasswordHash, no over-posting.
            customer.FullName = req.FullName;
            customer.Email = req.Email;
            await db.SaveChangesAsync(ct);
            return TypedResults.NoContent();
        }).RequireAuthorization("customers:write");
    }
}
// Data/Customer.cs - the entity stays internal to persistence.
namespace Shop.Api.Data;

public sealed class Customer
{
    public int Id { get; set; }
    public string PublicId { get; set; } = "";
    public string FullName { get; set; } = "";
    public string Email { get; set; } = "";
    public string PasswordHash { get; set; } = "";
    public bool IsAdmin { get; set; }
    public decimal CreditLimit { get; set; }            // decimal(18,2) in SQL Server
    public DateTimeOffset CreatedAt { get; set; }       // datetimeoffset
}

⚠ Common mistakes

  • Mistake: Returning EF Core entities from endpoints. Why it is wrong: Every property, including sensitive ones added later, is serialised to clients. Instead: Purpose-built response DTOs with projection.
  • Mistake: Using [JsonIgnore] on the entity as the fix. Why it is wrong: It's opt-out security: the next sensitive column is exposed by default. Instead: Opt-in DTOs that list exactly what is returned.
  • Mistake: Binding entities from request bodies and calling db.Update. Why it is wrong: Over-posting sets fields like IsAdmin and overwrites unsent columns. Instead: Request DTOs with only editable fields, applied to a loaded entity.
  • Mistake: double for money. Why it is wrong: Binary floating point can't represent most decimal fractions. Instead: decimal in C#, string or minor units plus currency on the wire.
  • Mistake: DateTime with Kind = Unspecified in responses. Why it is wrong: Clients guess the time zone, and Australia has several. Instead: DateTimeOffset and ISO 8601 with an offset.
  • Mistake: No page-size cap. Why it is wrong: One request can exhaust memory and the database. Instead: Default and maximum limits, cursor pagination.
  • Mistake: Projecting by loading entities and mapping in a loop, or calling a method per row that queries again. Why it is wrong: It reintroduces N+1 round trips or loads full entities, losing the benefit of projection. Instead: Do the whole Select inside the LINQ query so EF Core emits one SQL statement; for nested collections in the DTO, check the generated SQL and consider AsSplitQuery.
  • Mistake: Treating opaque public ids as access control. Why it is wrong: Ids leak through logs and links. Instead: Authorise every resource access; public ids only reduce enumeration and coupling.

🏛 Senior insight: trade-offs

Contract mistakes are cheap to fix before release and expensive after, because every one of these fixes is a breaking change once clients depend on the bad shape. That's why I treat money format, date format and naming as blocking on a public API even though they look cosmetic. Data exposure and unbounded queries are blocking everywhere. My position is simple: entities are never the API contract, not even "temporarily", because temporary contracts become permanent the day a client integrates.

Option When it fits Cost When not to
Hand-written DTOs + Select projection Every API Mapping code Never skip for real endpoints
Mapping libraries (Mapperly source generator) Many similar DTOs Build-time generator; less visible mappings When explicit mapping is short
Entity as contract with [JsonIgnore] Not recommended: opt-out security Exposure by default, schema coupling Any real API, especially with personal data
Public ids (GUID v7, prefixed ids) Public APIs, enumeration concerns Extra column and index Purely internal service-to-service APIs

Security checks sit alongside the DTOs, not instead of them: authentication on the group, a scope or policy per operation, and a per-resource ownership check in the handler before any data is read. To stop the pattern recurring I prefer automated checks over reviewer vigilance: an architecture test banning domain or data types in endpoint signatures, Spectral rules on the generated spec, and a review checklist covering page limits, money and dates.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate argues for separate DTOs and domain models Why: Checks deeper reasoning about domain model versus DTO separation and mapping.
    How to answer

    A domain model represents business concepts with behaviour and invariants (an Order that can be paid, cancelled, and refuses invalid changes). A DTO (data transfer object) is a flat, behaviour-free contract for moving data across a boundary: an HTTP request or response, a message, a query result. Keep them separate so that the API contract and the domain can change independently, so clients cannot over-post fields they must not set (IsAdmin, Status), and so internal data does not leak in responses. Map with explicit code, source-generated mappers (Mapperly) or EF Core projections straight to DTOs for reads. Sharing one type is acceptable only for simple CRUD with no rules, and even then be careful at public boundaries.

  2. When: Candidate mentions over-posting or binding entities Why: Checks the related request-handling review: try/catch 200s, entity binding and manual validation.
    How to answer

    Ranked by severity: (1) over-posting: binding the EF entity lets a client set fields they shouldn't (IsApproved, Role, Price, Id, navigation properties), a security hole. (2) information disclosure: returning ex.Message can leak SQL, server names or personal data. (3) broken HTTP semantics: 200 with success: false makes failures look like successes to monitoring, retries, caches and clients. (4) swallowed exceptions: the catch-all hides bugs and usually doesn't log. (5) hand-rolled validation: inconsistent and duplicated. The rewrite: a request DTO with only the allowed fields, DataAnnotations with [ApiController] (or FluentValidation), explicit mapping to the entity, proper status codes (201, 400, 404, 409) via ProblemDetails, and global exception handling with UseExceptionHandler instead of try/catch in every action.

  3. When: Candidate proposes cursor pagination with a page-size cap Why: Checks the pagination contract design in detail.
    How to answer

    Offset pagination (?page=3&pageSize=50) is simple and allows jumping to page N, but SQL Server still reads and discards every skipped row, so deep pages get slower, and inserts or deletes shift rows between pages, giving duplicates and gaps.

    Cursor (keyset) pagination (?after=eyJ...) remembers the last row's sort key and seeks past it, so every page costs the same and pages stay stable while data changes. The cursor should be opaque and the sort must end in a unique tie-breaker.

    I return items plus a next link or nextCursor, enforce a maximum page size, and make total counts optional, because COUNT(*) over a large filtered set is a second query that can cost more than the page itself. The trade-off: cursors can't jump to an arbitrary page.

🛠 Real-world problems: how you handle them

Customer endpoint leaking password hashes
Situation
A customer self-service API on Azure App Service returned EF Core `Customer` entities directly. It served a web portal and a mobile app with [N] customers, and held personal information covered by the Privacy Act.
Signals
An external penetration test reported `passwordHash` and `isFraudFlagged` in the JSON of `GET /customers/me` and `GET /customers`. Separately, Application Insights showed the list endpoint averaging [1.2 s] and occasional out-of-memory restarts.
Investigation
Reviewed the endpoints and found entities used for both responses and request bodies; reproduced over-posting by sending `isAdmin: true` in a PUT. Query Store showed the list endpoint loading customers plus orders with no `TOP`. Checked logs and gateway analytics to establish whether the exposed fields had been harvested.
Resolution
Immediate: hotfix replacing entity responses with DTOs and capping the list at 100, deployed the same day; rotated the affected hashing scheme to force password resets as a precaution after privacy officer assessment. Then a full rewrite with request DTOs, projection, cursor pagination, decimal money as strings and `DateTimeOffset`.
Prevention
NetArchTest rule banning `Data` types in endpoint signatures; Spectral rules for naming and date formats; review checklist item for page limits; a Notifiable Data Breaches assessment runbook rehearsed with the privacy officer.

How to tell it (STAR)

**S:** A penetration test found our customer API returning password hashes and fraud flags, because endpoints returned EF Core entities directly, and the list endpoint had no limit. **T:** I led the fix and the review of how it happened. **A:** I shipped a same-day hotfix with DTOs and a page cap, worked with [our privacy officer] on the breach assessment, then rewrote the contracts with request DTOs, projection, cursor paging, string money and offset dates, and added an architecture test so entities can't be returned again. **R:** The retest passed, list p95 dropped from [1.2 s] to [90 ms], and the architecture test has since blocked [three] attempts to return entities.

More in API Design

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me