HTTP JSON and error contracts
HTTP JSON and error contracts
An HTTP call can fail at several boundaries: the transport may fail without a response, the server may return a non-success status, a successful response may contain invalid JSON, or valid JSON may violate domain rules. Keep these cases distinct. A 2xx status says the server reported HTTP success, not that a particular DTO is trustworthy. Deserialize into a small explicit contract, then validate required values. The examples below use synthetic payloads and no remote services.
Baseline: .NET 10 / C# 14 (SDK candidate inherited, not installed). Each example is an independent project with predicted output. Build and runtime verification are pending. Run only a reviewed fixture in an approved disposable environment.
Distinguish status codes before parsing
A fake handler serves three known cases. Do not parse a failure response as if it were the success DTO.
using System;using System.Net;using System.Net.Http;using System.Threading;using System.Threading.Tasks;using var client = new HttpClient(new StatusHandler()){ BaseAddress = new Uri("https://example.test/") };foreach (string path in new[] { "200", "404", "503" }){ using var response = await client.GetAsync(path); Console.WriteLine(response.StatusCode switch { HttpStatusCode.OK => "success", HttpStatusCode.NotFound => "missing", HttpStatusCode.ServiceUnavailable => "unavailable", _ => "unexpected status" });}sealed class StatusHandler : HttpMessageHandler{ protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken token) { token.ThrowIfCancellationRequested(); int status = int.Parse(request.RequestUri!.AbsolutePath.Trim('/'), System.Globalization.CultureInfo.InvariantCulture); return Task.FromResult(new HttpResponseMessage((HttpStatusCode)status)); }}GetAsync does not throw merely because the status is 404 or 503. EnsureSuccessStatusCode is appropriate when all non-2xx statuses are exceptional for the calling operation.
Expected observation (reasoned, not executed):
successmissingunavailableCheck JSON syntax and domain meaning
The contract requires a positive ID and a nonblank name. Explicit property mapping avoids relying on naming conventions.
using System;using System.Net.Http;using System.Net.Http.Json;using System.Text;using System.Text.Json;using System.Text.Json.Serialization;foreach (string json in new[] { "{\"id\":3,\"name\":\"Pen\"}", "{\"id\":0}", "{broken" }){ using var content = new StringContent(json, Encoding.UTF8, "application/json"); try { Product? item = await content.ReadFromJsonAsync<Product>(); Console.WriteLine(item is { Id: > 0 } && !string.IsNullOrWhiteSpace(item.Name) ? item.Name : "invalid product"); } catch (JsonException) { Console.WriteLine("invalid JSON"); }}sealed record Product([property: JsonPropertyName("id")] int Id, [property: JsonPropertyName("name")] string? Name);A missing name deserializes as null for this contract; application validation rejects it. A malformed document throws JsonException. A nullable annotation alone is not a full wire validation policy.
Expected observation (reasoned, not executed):
Peninvalid productinvalid JSONRetry only a bounded safe operation
This fake GET receives one 503 and then a 200. It illustrates a decision rule, not a production retry library.
using System;using System.Net;using System.Net.Http;using System.Threading;using System.Threading.Tasks;using var client = new HttpClient(new FlakyHandler());using var stop = new CancellationTokenSource(TimeSpan.FromSeconds(5));for (int attempt = 1; attempt <= 2; attempt++){ using var request = new HttpRequestMessage(HttpMethod.Get, "https://example.test/catalog"); using var response = await client.SendAsync(request, stop.Token); Console.WriteLine($"attempt {attempt}: {(int)response.StatusCode}"); if (response.IsSuccessStatusCode) break; if (response.StatusCode != HttpStatusCode.ServiceUnavailable || attempt == 2) response.EnsureSuccessStatusCode();}sealed class FlakyHandler : HttpMessageHandler{ private int calls; protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken token) { token.ThrowIfCancellationRequested(); var status = Interlocked.Increment(ref calls) == 1 ? HttpStatusCode.ServiceUnavailable : HttpStatusCode.OK; return Task.FromResult(new HttpResponseMessage(status)); }}A new request is constructed for each attempt. Real services need backoff, jitter, Retry-After handling, a total deadline and a policy based on operation semantics. Do not blindly retry non-idempotent mutations.
Expected observation (reasoned, not executed):
attempt 1: 503attempt 2: 200Common mistakes and design limits
Never treat an HTTP response body as a verified domain object. Distinguish invalid JSON from missing required data; limit response size and inspect expected media type before deserializing. Transport errors may surface as HttpRequestException; cancellation and timeout can involve OperationCanceledException with version-specific details. Do not log full sensitive response bodies. A 503 or connection failure does not prove that a mutation did not run. Retry only when operation semantics and service guarantees permit it.
Apply the concept
Classify these cases and propose a caller result: no response due to a connection failure, 404, 200 with broken JSON, 200 with an ID of zero, 503 on a GET.
Check your work: Transport failure; missing resource; decoding failure; domain validation failure; potentially transient server failure eligible for a bounded retry under the read policy.
Further study
Continue with the next planned lesson. Consult the official documentation for API contracts: json, completionoption, httpguidelines, ensuresuccess. API and runtime verification remain incomplete.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
HTTP JSON and error contracts — knowledge check
Apply the lesson concepts to the following scenarios.
What does a 200 response guarantee about a Product DTO?
Which condition is a JSON decoding failure?
What does EnsureSuccessStatusCode do for 503?
When may a GET be retried?
Why construct a new request per retry?