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.
Ranked by severity:
<img src> on any site becomes a CSRF attack.success: false: failures are invisible to monitoring, SLOs, retry policies and gateways; clients must parse every body.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.
"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
/ordersand/orders/{id}, cancellation asPOST /orders/{id}/cancellationwith 409 when the order had shipped, and ProblemDetails errors. We ran the new routes alongside the old ones, addedDeprecationandSunsetheaders 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."
[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 }); }
}
| # | 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 |
[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.
ex.Message in responses; binding the entity.Deprecation and Sunset headers and a usage metric per client, publish the new OpenAPI document, remove after the sunset date.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
Red flags
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.
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.
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 |
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.
Deprecation (RFC 9745) and Sunset (RFC 8594) headers plus a Link to migration docs on old routes.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.
<img> tag on another local site while logged in with a cookie.requests | where resultCode == "200" | where customDimensions has "success" to find 200-with-error patterns in an existing app.get, create, delete.Deprecation and Sunset headers via an endpoint filter on a route group.POST /orders/{id}/cancellation returns 409 for a shipped order.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);
}
}
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./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.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.ex.Message in error bodies. Why it is wrong: Leaks internals and helps attackers. Instead: UseExceptionHandler + AddProblemDetails, with a trace id for support.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 |
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.
The status code tells clients and infrastructure what happened before they read the body, so it must be exact.
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.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.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.
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).
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.
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.
Last updated 23 Nov 2026.