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

📚 Interview question

Code review: an orders API uses GET /orders/{id}/cancel to cancel an order, returns 200 with {"success": false, "error": "..."} on failures, sends every operation as POST, and has URLs like /api/getOrders, /api/createOrder and /api/deleteOrder. What problems do you find, ranked by severity, and how would you redesign it?

Reviewing an RPC-style HTTP API that violates method semantics (state change on GET, POST for everything, verbs in URLs) and hides failures behind 200 responses, then redesigning it around resources, correct methods and status codes.

Senior CodeReview Advanced aspnet-core code-review http-methods rest status-codes web-api

🎯 Key points

  • Severity 1: state change on GET (crawlers, prefetchers, link previews, CSRF via img tags, caches)
  • Severity 1: 200 + success:false hides failures from monitoring, SLOs, retries and gateways
  • Severity 2: ex.Message leaked and entity bound directly (over-posting); errors must be ProblemDetails (RFC 9457, which replaced RFC 7807) with a trace id
  • Severity 3: POST for everything loses caching, safe retries and idempotency; verbs in URLs fragment the resource model
  • Redesign: GET /orders, POST /orders (201 + Location), GET/PATCH/DELETE /orders/{id} (204/404), authorised per customer
  • State transitions as POST /orders/{id}/cancellation with 409 for invalid state and If-Match for races
  • Migrate without breaking clients: new routes alongside old, Deprecation + Sunset headers, usage telemetry; versioning policy for future changes
  • Lock it in with integration tests asserting status codes and an OpenAPI linter (Spectral) in CI

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

🗣 Full answer (senior)

How I would answer this in an interview

"I'd rank these by what can hurt customers or hide incidents first. The worst is GET /orders/{id}/cancel. GET is meant to be safe, so everything in the path treats it that way: search crawlers follow links, Slack and Teams fetch URLs for previews, browsers prefetch, and caches may serve or replay it. Worse, any website can embed <img src=\"https://shop/orders/42/cancel\"> and a logged-in user's browser will send it with their cookies. That's a CSRF hole that cancels real orders.

Second is returning 200 with success: false. Every tool that reads status codes, Application Insights failure rates, availability tests, the gateway's retry policy, our SLO dashboards, sees success. I've seen a dashboard sit at 99.9% while [about 4%] of checkouts failed. Third, POST for everything throws away HTTP's contract: reads can't be cached and nobody can tell which calls are safe to retry. Verbs in the URL, /getOrders, /deleteOrder, are the least harmful, but they show the API was designed as RPC over HTTP, and they multiply endpoints instead of modelling resources.

For example, at [company] we inherited an API like this. [A link-preview bot cancelled N orders] after someone pasted a cancel link into a support chat. I proposed a redesign around /orders and /orders/{id}, cancellation as POST /orders/{id}/cancellation with 409 when the order had shipped, and ProblemDetails errors. We ran the new routes alongside the old ones, added Deprecation and Sunset headers to the old ones, tracked their usage, and removed them after [three months]. The 5xx rate became visible for the first time and [two] hidden integration failures turned up in the first week."


Code under review

[ApiController]
[Route("api")]
public class OrdersController(ShopDbContext db) : ControllerBase
{
    [HttpGet("orders/{id}/cancel")]                      // 1
    public async Task<IActionResult> Cancel(int id)
    {
        var order = await db.Orders.FindAsync(id);
        if (order is null || order.Status == "Shipped")
            return Ok(new { success = false, error = "Cannot cancel" });   // 2
        order.Status = "Cancelled";
        await db.SaveChangesAsync();
        return Ok(new { success = true });
    }

    [HttpPost("getOrders")]                              // 3, 4
    public async Task<IActionResult> GetOrders([FromBody] OrderFilter f)
    {
        try { return Ok(new { success = true, data = await db.Orders.Where(o => o.CustomerId == f.CustomerId).ToListAsync() }); }
        catch (Exception ex) { return Ok(new { success = false, error = ex.Message }); }   // 2, 5
    }

    [HttpPost("createOrder")]                            // 4, 6
    public async Task<IActionResult> CreateOrder(Order order) { db.Orders.Add(order); await db.SaveChangesAsync(); return Ok(new { success = true, id = order.Id }); }

    [HttpPost("deleteOrder")]                            // 3, 4
    public async Task<IActionResult> DeleteOrder([FromBody] int id) { /* ... */ return Ok(new { success = true }); }
}

Findings, ranked by severity

# Severity Finding Impact
1 Security / data loss State change on GET (// 1) CSRF via <img>, crawlers and link previews cancel orders, caches may replay
2 Hidden failures 200 + success: false (// 2) Monitoring, SLOs, gateways and retry policies see success; clients must parse bodies
3 Security ex.Message returned to clients (// 5) Leaks SQL, server and schema details
4 Data integrity Entity bound directly on create (// 6) Over-posting (Status, Id, CustomerId), no validation, no 201/Location
5 Reliability POST for reads and deletes (// 3) No caching, no safe retries, DELETE semantics lost
6 Design Verbs in URLs (// 4) RPC-style surface, duplicated endpoints, harder docs and governance
7 Concurrency Cancel has no precondition Cancel races with shipping; last write wins

The rewrite

[ApiController]
[Route("orders")]
public sealed class OrdersController(IOrderService orders) : ControllerBase
{
    [HttpGet]
    public Task<PagedResult<OrderSummary>> List([FromQuery] OrderQuery q, CancellationToken ct) => orders.ListAsync(q, ct);

    [HttpGet("{id:int}")]
    public async Task<ActionResult<OrderDto>> Get(int id, CancellationToken ct) =>
        await orders.GetAsync(id, ct) is { } o ? o : NotFound();

    [HttpPost]
    public async Task<ActionResult<OrderDto>> Create(CreateOrderRequest req, CancellationToken ct)
    {
        var created = await orders.CreateAsync(req, ct);          // DTO in, validated, no over-posting
        return CreatedAtAction(nameof(Get), new { id = created.Id }, created);   // 201 + Location
    }

    [HttpPost("{id:int}/cancellation")]                           // state transition, not GET
    public async Task<IActionResult> Cancel(int id, CancellationToken ct) =>
        await orders.CancelAsync(id, ct) switch
        {
            CancelResult.Cancelled => NoContent(),
            CancelResult.NotFound => NotFound(),
            CancelResult.AlreadyShipped => Problem(statusCode: 409, title: "Order already shipped",
                type: "https://errors.example.com.au/order-already-shipped"),
            _ => Problem()
        };

    [HttpDelete("{id:int}")]
    public async Task<IActionResult> Delete(int id, CancellationToken ct) =>
        await orders.DeleteAsync(id, ct) ? NoContent() : NotFound();
}

With builder.Services.AddProblemDetails() and app.UseExceptionHandler(), unhandled exceptions become a 500 application/problem+json with a trace id, never ex.Message.

How I'd close the review

  • Blocking: GET with side effects; 200-with-error responses; ex.Message in responses; binding the entity.
  • Strongly suggested: resource-oriented routes and methods, ProblemDetails, 201 + Location, a concurrency check on cancel.
  • Migration plan: keep old routes as thin adapters calling the same service, add Deprecation and Sunset headers and a usage metric per client, publish the new OpenAPI document, remove after the sunset date.
  • Guardrails: API guidelines (no verbs in paths, no 200-with-error), a Spectral lint rule on the OpenAPI document in CI, and integration tests asserting status codes.

🔍 What the interviewer is checking

Checks whether the candidate can rank HTTP design problems by real-world impact, propose a correct resource-oriented redesign, and migrate without breaking existing clients.

Green flags

  • Ranks the GET side effect first and names CSRF and crawlers
  • Explains why 200-with-error blinds monitoring and retries
  • Redesigns with correct methods, 201 + Location, 409 for invalid transitions and ProblemDetails
  • Plans a non-breaking migration with Deprecation/Sunset headers and usage tracking
  • Proposes guardrails (guidelines, OpenAPI linting)

Red flags

  • Treats all findings as equal style issues
  • Proposes a big-bang breaking rewrite
  • Thinks SameSite cookies make GET side effects safe

📚 Learn in depth

1. Why GET must be safe

User pastes https://shop/orders/42/cancel in Teams
   -> Teams link preview service: GET /orders/42/cancel  (with no auth: 401, fine)
User visits evil.example with an active session cookie
   -> <img src="https://shop/orders/42/cancel">          (cookies attached: order cancelled)
Browser prefetch / service worker cache / crawler
   -> more GETs with side effects

SameSite cookies (Lax by default in modern browsers) still allow top-level GET navigations cross-site, so SameSite=Lax does not protect a state-changing GET. Antiforgery tokens are designed for unsafe methods; ASP.NET Core doesn't validate them on GET.

2. Why 200-with-error breaks the ecosystem

Client --> APIM (retry on 5xx) --> App (returns 200 {success:false})
            |                         |
            no retry, counted OK      App Insights: success=true, resultCode=200
                                      Availability test: pass
                                      SLO burn rate: 0

Status codes are the one thing every HTTP tool understands. Hiding failures in the body means every consumer must implement its own parsing, and generic tooling (dashboards, alerts, circuit breakers, CDN error caching rules) becomes blind.

3. RPC over HTTP vs resource orientation

An RPC style isn't wrong in itself: gRPC and JSON-RPC are legitimate. The problem is RPC disguised as HTTP: using HTTP as a tunnel while ignoring its semantics. If you want RPC, use gRPC, which has its own status codes, deadlines and retry semantics. If you use HTTP, use its methods and codes.

RPC-style Resource-style
POST /api/getOrders GET /orders?customerId=17
POST /api/createOrder POST /orders → 201 + Location
POST /api/deleteOrder DELETE /orders/42 → 204
GET /orders/42/cancel POST /orders/42/cancellation → 204 / 409

4. Modelling the state transition

Three common shapes:

  • POST /orders/42/cancellation: a sub-resource representing the act of cancelling (can return 201 with the cancellation record, reason and refund).
  • POST /orders/42/cancel: a pragmatic action endpoint; widely used (e.g. Stripe's /cancel), fine when consistent.
  • PATCH /orders/42 {"status":"Cancelled"}: simple but pushes business rules into generic field updates and makes authorisation per transition harder.

Invalid transitions return 409 Conflict with a ProblemDetails type such as order-already-shipped. Add If-Match to guard against racing with the warehouse.

5. Migrating without breaking clients

  1. Add the new endpoints backed by the same application service.
  2. Turn the old endpoints into adapters; keep their old response shape.
  3. Emit Deprecation (RFC 9745) and Sunset (RFC 8594) headers plus a Link to migration docs on old routes.
  4. Track usage of old routes per client (API key or app id) in Application Insights or APIM analytics.
  5. Contact remaining consumers; remove old routes after the sunset date.

The dangerous GET cancel is the exception: disable it immediately (return 405 or redirect to a confirmation page) even if it breaks someone, because it's a security hole.

Try it yourself

  1. Create a GET endpoint that changes state and trigger it from an <img> tag on another local site while logged in with a cookie.
  2. Query Application Insights: requests | where resultCode == "200" | where customDimensions has "success" to find 200-with-error patterns in an existing app.
  3. Write a Spectral rule that flags paths containing verbs like get, create, delete.
  4. Add Deprecation and Sunset headers via an endpoint filter on a route group.
  5. Write an integration test asserting POST /orders/{id}/cancellation returns 409 for a shipped order.

💻 Code

The deprecation adapter that keeps old clients working while the new API rolls out, and an endpoint filter that adds Deprecation and Sunset headers.

// LegacyOrderRoutes.cs (.NET 10)
namespace Shop.Api;

public static class LegacyOrderRoutes
{
    public static void MapLegacyOrders(this IEndpointRouteBuilder app)
    {
        var legacy = app.MapGroup("/api")
            .AddEndpointFilter<DeprecationFilter>()
            .WithTags("Legacy")
            .ExcludeFromDescription();                    // keep old routes out of the new OpenAPI document

        // Old shape preserved for existing clients; same application service underneath.
        legacy.MapPost("/getOrders", async (OrderFilter f, IOrderService orders, CancellationToken ct) =>
            Results.Ok(new { success = true, data = await orders.ListForCustomerAsync(f.CustomerId, ct) }));

        // The unsafe GET is shut off immediately: security beats compatibility.
        legacy.MapGet("/orders/{id:int}/cancel", () => Results.Problem(
            statusCode: StatusCodes.Status405MethodNotAllowed,
            title: "Use POST /orders/{id}/cancellation"));
    }
}

public sealed class DeprecationFilter(ILogger<DeprecationFilter> logger) : IEndpointFilter
{
    private static readonly DateTimeOffset SunsetDate = new(2027, 3, 31, 0, 0, 0, TimeSpan.Zero);

    public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext ctx, EndpointFilterDelegate next)
    {
        var http = ctx.HttpContext;
        http.Response.Headers["Deprecation"] = "@1767225600";                 // RFC 9745: deprecated since 2026-01-01
        http.Response.Headers["Sunset"] = SunsetDate.ToString("R");           // RFC 8594
        http.Response.Headers.Link = "<https://developer.example.com.au/orders-v2>; rel=\"deprecation\"";
        logger.LogInformation("Legacy route {Path} called by client {ClientId}",
            http.Request.Path, http.User.FindFirst("client_id")?.Value ?? "unknown");   // usage tracking
        return await next(ctx);
    }
}

public sealed record OrderFilter(int CustomerId);
public sealed record OrderSummary(int Id, string Status, decimal Total);
public interface IOrderService
{
    Task<IReadOnlyList<OrderSummary>> ListForCustomerAsync(int customerId, CancellationToken ct);
}

Integration tests that lock the contract in: status codes and ProblemDetails, not just happy paths (xUnit + WebApplicationFactory).

// OrdersContractTests.cs
using System.Net;
using System.Net.Http.Json;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Testing;

namespace Shop.Api.Tests;

public sealed class OrdersContractTests(WebApplicationFactory<Program> factory)
    : IClassFixture<WebApplicationFactory<Program>>
{
    private readonly HttpClient _client = factory.CreateClient();

    [Fact]
    public async Task Get_cancel_is_not_allowed()
    {
        var response = await _client.GetAsync("/api/orders/1/cancel");
        Assert.Equal(HttpStatusCode.MethodNotAllowed, response.StatusCode);
    }

    [Fact]
    public async Task Cancelling_a_shipped_order_returns_409_problem_details()
    {
        var response = await _client.PostAsync("/orders/2/cancellation", content: null);   // seeded as Shipped

        Assert.Equal(HttpStatusCode.Conflict, response.StatusCode);
        Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
        var problem = await response.Content.ReadFromJsonAsync<ProblemDetails>();
        Assert.Equal("https://errors.example.com.au/order-already-shipped", problem?.Type);
    }

    [Fact]
    public async Task Create_returns_201_with_location()
    {
        var response = await _client.PostAsJsonAsync("/orders", new { customerId = 17, lines = new[] { new { sku = "KET-1", quantity = 1 } } });
        Assert.Equal(HttpStatusCode.Created, response.StatusCode);
        Assert.NotNull(response.Headers.Location);
    }
}

⚠ Common mistakes

  • Mistake: Treating the GET cancel as a style issue. Why it is wrong: It is a CSRF and accidental-trigger vulnerability that destroys data. Instead: Block it immediately and move to POST.
  • Mistake: Keeping success: false because "the front end expects it". Why it is wrong: All generic tooling is blind to failures. Instead: Real status codes with ProblemDetails; adapt the old front end during migration.
  • Mistake: Replacing /deleteOrder with DELETE /orders/{id} but returning 200 {success:true}. Why it is wrong: Half a fix; status codes still lie. Instead: 204 on success, 404 when missing.
  • Mistake: Modelling every transition as PATCH status. Why it is wrong: Business rules and per-transition authorisation get buried in field updates. Instead: Explicit transition endpoints for meaningful business actions.
  • Mistake: Rewriting all routes in one breaking release. Why it is wrong: Mobile apps and partners on old versions break. Instead: Run old and new side by side with Deprecation/Sunset headers and usage tracking.
  • Mistake: Returning ex.Message in error bodies. Why it is wrong: Leaks internals and helps attackers. Instead: UseExceptionHandler + AddProblemDetails, with a trace id for support.
  • Mistake: Reviewing only the controller. Why it is wrong: Gateways, client SDKs and docs encode the same mistakes. Instead: Fix the OpenAPI contract and lint it in CI.

🏛 Senior insight: trade-offs

A senior review separates what must stop now from what should improve over time. The GET side effect and leaked exception messages are security issues: block them in this PR. The 200-with-error pattern is an observability and reliability issue: fix it now for new endpoints and plan the migration for existing clients. Verbs in URLs are design debt: fix them as part of the migration, not as a big-bang rewrite.

The other senior move is stopping recurrence. One review fixes one controller; API guidelines plus an OpenAPI linter in CI (Spectral rules for verbs in paths, required error responses, 201 on POST) fix the next fifty.

Fix When Cost Risk if deferred
Block GET side effects This PR Breaks clients using it CSRF, accidental cancellations
ProblemDetails + real codes New endpoints now, old ones via migration Front-end changes Invisible failures, bad retries
Resource routes + methods Over a deprecation window Parallel routes for months Growing RPC sprawl
Lint rules in CI Next sprint Initial rule tuning Same mistakes in new services

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions try/catch returning 200 or binding entities Why: Checks a related code review on error handling, over-posting and 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.

  2. When: Candidate mentions 409 or status codes for failures Why: Checks precise status code selection
    How to answer

    The status code tells clients and infrastructure what happened before they read the body, so it must be exact.

    • Success: 200 OK with a body, 201 Created plus a Location header, 202 Accepted for work that finishes later, 204 No Content when there's nothing to return.
    • Client errors: 400 bad input, 422 well-formed but semantically invalid, 401 not authenticated vs 403 not allowed, 404 not found vs 410 gone, 409 conflicts with current state, 412 a precondition like If-Match failed, 429 rate limited with Retry-After.
    • Server errors: 500 our bug, 502 bad upstream response, 503 temporarily unavailable, 504 upstream timeout.

    The trade-off is precision versus consistency: pick a small, documented set and use it the same way in every service.

  3. When: Candidate mentions safe methods or idempotency Why: Checks method semantics and why intermediaries rely on them
    How to answer

    GET reads, POST creates or runs a command, PUT replaces a resource at a known URI, PATCH partially updates it, DELETE removes it, HEAD is GET without the body, and OPTIONS asks what is allowed (used by CORS preflight).

    • Safe (no intended state change): GET, HEAD, OPTIONS.
    • Idempotent (repeating has the same effect as doing it once): the safe methods plus PUT and DELETE.
    • POST and PATCH are neither, unless you make them so.

    These properties are a contract that caches, proxies, browsers and retry policies rely on: a gateway may retry a timed-out PUT but must not blindly retry a POST. Breaking the contract, such as changing state on GET, causes duplicate side effects and crawler disasters.

🛠 Real-world problems: how you handle them

Link-preview bot cancels orders through a GET endpoint
Situation
An [online retailer's] orders API, built [years] earlier, exposed `GET /orders/{id}/cancel` used by an internal support tool. [~25,000] orders a day; customers in [AU and NZ].
Signals
Customers complained that orders were cancelled without their action; the audit log showed cancellations by [support staff accounts] at times they weren't working; request telemetry showed the GETs came from a [chat platform's link-preview] user agent shortly after links were pasted into a support channel.
Investigation
Correlated audit entries with Application Insights requests by operation id; found the user agent and IP ranges of the preview service; confirmed the preview requests carried a session cookie because the support tool used cookie auth with `SameSite=None`. Reviewed the rest of the API and found 200-with-error responses that had hidden [two] failing partner integrations.
Resolution
Immediately: disabled the GET route (405 with a pointer to the new endpoint), restored the affected orders, and notified customers. Then: introduced `POST /orders/{id}/cancellation` with antiforgery protection in the support tool, 409 for invalid transitions, ProblemDetails errors across the API, and a deprecation window for the other RPC routes.
Prevention
API guidelines banning side effects on GET and 200-with-error; Spectral lint on the OpenAPI document in CI; an integration test suite asserting methods and status codes; an alert on cancellations by staff accounts outside rostered hours.

How to tell it (STAR)

**S:** At [retailer], orders were being cancelled without anyone clicking anything, [N orders] over [two weeks]. **T:** I was asked to find the cause and make sure it couldn't happen again. **A:** I correlated the audit log with request telemetry and found a chat app's link-preview bot calling our GET cancel endpoint with a support agent's cookie. I disabled the route the same day, restored the orders, then led the redesign to POST-based transitions, ProblemDetails and real status codes, with a deprecation window for the old routes and lint rules in CI. **R:** Accidental cancellations stopped immediately, the true failure rate became visible for the first time, which exposed [two] broken partner integrations, and no new RPC-style routes have been merged since.

↩ Usually asked after

More in HTTP Fundamentals

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me