Recipe 13.3 · C#
JSON APIs End to End
Problem
Calling a JSON API is more than one line. The request body must be serialized with the right
options, errors come back as application/problem+json with useful detail that
EnsureSuccessStatusCode throws away, and large result sets arrive as one big array that you would
rather process as it streams in.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
// Not to copy: loses the server's error detail, buffers everything
var json = JsonConvert.SerializeObject(request);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync("orders", content);
response.EnsureSuccessStatusCode(); // "Response status code: 400"
var body = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<OrderDto>(body);
When this fails, the log says "Response status code does not indicate success: 400 (Bad Request)". The server said which field was wrong, but the code threw that message away.
The improved recipe
Use the System.Net.Http.Json extensions for the happy path, and read the problem details on the
unhappy path.
using System;
using System.Collections.Generic;
using System.Net;
namespace ImproveCode.Http;
public sealed record CreateOrderRequest(
int CustomerId, IReadOnlyList<OrderLineDto> Lines);
public sealed record OrderLineDto(string Sku, int Quantity);
public sealed record OrderDto(
int Id, int CustomerId, string Status, decimal Total);
public sealed record ApiProblem(
string? Type, string? Title, int? Status, string? Detail);
public sealed class ApiException(
HttpStatusCode statusCode, ApiProblem? problem)
: Exception(
$"API returned {(int)statusCode}: " +
$"{problem?.Title ?? statusCode.ToString()}" +
(problem?.Detail is null ? "" : $" ({problem.Detail})"))
{
public HttpStatusCode StatusCode { get; } = statusCode;
public ApiProblem? Problem { get; } = problem;
}
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace ImproveCode.Http;
public sealed class OrderApiClient(HttpClient http)
{
private static readonly JsonSerializerOptions Json =
new(JsonSerializerDefaults.Web);
public async Task<OrderDto?> GetOrderAsync(
int id, CancellationToken ct = default)
{
using HttpResponseMessage response =
await http.GetAsync($"orders/{id}", ct);
if (response.StatusCode == HttpStatusCode.NotFound)
{
return null;
}
await EnsureSuccessAsync(response, ct);
return await response.Content
.ReadFromJsonAsync<OrderDto>(Json, ct);
}
public async Task<OrderDto> CreateOrderAsync(
CreateOrderRequest request, CancellationToken ct = default)
{
using HttpResponseMessage response =
await http.PostAsJsonAsync("orders", request, Json, ct);
await EnsureSuccessAsync(response, ct);
return await response.Content
.ReadFromJsonAsync<OrderDto>(Json, ct)
?? throw new ApiException(response.StatusCode, null);
}
public IAsyncEnumerable<OrderDto?> StreamOrdersAsync(
CancellationToken ct = default) =>
http.GetFromJsonAsAsyncEnumerable<OrderDto>(
"orders/export", Json, ct);
private static async Task EnsureSuccessAsync(
HttpResponseMessage response, CancellationToken ct)
{
if (response.IsSuccessStatusCode)
{
return;
}
ApiProblem? problem = null;
string? mediaType = response.Content.Headers.ContentType?.MediaType;
if (mediaType is "application/problem+json" or "application/json")
{
try
{
problem = await response.Content
.ReadFromJsonAsync<ApiProblem>(Json, ct);
}
catch (JsonException)
{
// Body was not problem details; keep the status code.
}
}
throw new ApiException(response.StatusCode, problem);
}
}
Usage from a job that exports orders:
await foreach (OrderDto? order in client.StreamOrdersAsync(ct))
{
if (order is not null)
{
await writer.WriteAsync(order, ct);
}
}
How it works
PostAsJsonAsync serializes straight into the request stream with the options you pass, sets
Content-Type: application/json; charset=utf-8, and avoids building an intermediate string.
ReadFromJsonAsync does the reverse from the response stream. Passing one static
JsonSerializerOptions keeps the metadata cache warm, as Chapter 12 explains.
EnsureSuccessAsync replaces EnsureSuccessStatusCode. ASP.NET Core and most modern APIs return
RFC 9457 problem details on errors: a small JSON object with title, status and detail. The
method reads it when the content type says it is JSON and throws an ApiException that carries
both the status code and the server's explanation. Your log now says
API returned 400: Validation failed (Quantity must be at least 1). Callers can also catch
ApiException and branch on StatusCode, for example to show a validation message for 400 and
an apology for 503.
GetFromJsonAsAsyncEnumerable streams a JSON array. Each item is yielded as soon as it has been
read, so an export of 500,000 orders uses the memory of a few orders, not all of them. The
response is read with HttpCompletionOption.ResponseHeadersRead under the covers, which is what
makes the streaming real.
Every method takes a CancellationToken. In ASP.NET Core, pass HttpContext.RequestAborted, and
when the user closes the browser the outgoing call is cancelled too.
Variations and pitfalls
- Always dispose the response.
using HttpResponseMessagereturns the connection to the pool promptly. Forgetting it on error paths is a classic slow leak. - Don't log whole bodies. Problem details are safe to log. Raw response bodies can contain
personal data, and Chapter 4 explains what never to log. If you need the body for diagnosis, log
the first 500 characters at
Debuglevel. - Validation errors. ASP.NET Core adds an
errorsdictionary to validation problems. AddIDictionary<string, string[]>? ErrorstoApiProblemif you want to show them per field. - Expected failures. If a failure is part of the normal flow, such as an insufficient balance,
return Chapter 5's
Resulttype from the client instead of throwing. - Generated clients. For a large API with an OpenAPI document, a generated client (NSwag or
Kiota) saves typing. Register it with
AddHttpClientso it still gets the factory and resilience.