OpenAPI and response schemas
OpenAPI and response schemas
OpenAPI describes HTTP operations, inputs and possible response representations in a machine-readable document. A schema describes data shape; endpoint metadata helps generation, but neither proves that a running service obeys the contract.
An OpenAPI document contains paths, operations, parameters, responses and schemas. ASP.NET Core can generate it using the Microsoft.AspNetCore.OpenApi package, AddOpenApi and MapOpenApi. The optional document UI is separate; neither the document nor its UI authenticates requests. Typed result metadata and explicit Produces declarations help describe outcomes; metadata does not enforce them. Use response DTOs, verify status/body/headers against the contract, and avoid returning extra entity fields. This batch uses the .NET 10 package candidate 10.0.15 for the generation example only, requiring reviewed restore and a lockfile before release. It does not depend on a public hosted API. Development-only exposure is usual; the fixture intentionally maps the document in its isolated environment so it can test it. Production document access requires an explicit policy.
Baseline: .NET 10 / C# 14. Each code block is an independent static example with a companion Web SDK project. Read the endpoint registration and client checks first; the surrounding host harness is repeated for standalone use. Expected observations are reasoned, not executed. Run only in a clean, isolated local environment with an approved SDK; no launch profile, external network or real data. The OpenAPI package example additionally requires approved restore.
Read a typed response contract
Use a result union and inspect actual responses independently of generated docs.
using System.Net;using System.Net.Http.Json;using System.Text;using System.Text.Json;using Microsoft.AspNetCore.Http.HttpResults;using Microsoft.AspNetCore.Mvc;
// Standalone lab: run in a clean, isolated environment only.var builder = WebApplication.CreateBuilder(new WebApplicationOptions{ Args = Array.Empty<string>(), EnvironmentName = "Production", ContentRootPath = AppContext.BaseDirectory});builder.Configuration.Sources.Clear();builder.Logging.ClearProviders();builder.WebHost.ConfigureKestrel(options =>{ options.Listen(IPAddress.Loopback, 0); options.Limits.MaxRequestBodySize = 16 * 1024;});await using var app = builder.Build();app.MapGet("/books/{id:int}", Results<Ok<BookDto>, NotFound> (int id) => id == 2 ? TypedResults.Ok(new BookDto(2, "Map Atlas")) : TypedResults.NotFound());using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(15));await app.StartAsync(deadline.Token);try{ var address = new Uri(app.Urls.Single()); if (address.Host != "127.0.0.1" || address.Scheme != "http") throw new InvalidOperationException("Unexpected listener address."); using var client = new HttpClient(new HttpClientHandler { UseProxy = false, AllowAutoRedirect = false }) { BaseAddress = address }; using var found = await client.GetAsync("/books/2", deadline.Token); using var doc = JsonDocument.Parse(await found.Content.ReadAsStringAsync(deadline.Token)); Console.WriteLine($"{(int)found.StatusCode}:{doc.RootElement.GetProperty("id").GetInt32()}"); using var missing = await client.GetAsync("/books/7", deadline.Token); Console.WriteLine((int)missing.StatusCode);}finally{ using var shutdown = new CancellationTokenSource(TimeSpan.FromSeconds(5)); await app.StopAsync(shutdown.Token);}record BookDto(int Id, string Title);The concrete alternatives and actual response checks agree for both tested IDs.
Expected observation (reasoned, not executed):
200:2404Generate a local OpenAPI document
This example needs the pinned OpenAPI package; inspect stable response keys rather than schema ordering.
using System.Net;using System.Net.Http.Json;using System.Text;using System.Text.Json;using Microsoft.AspNetCore.Http.HttpResults;using Microsoft.AspNetCore.Mvc;
// Standalone lab: run in a clean, isolated environment only.var builder = WebApplication.CreateBuilder(new WebApplicationOptions{ Args = Array.Empty<string>(), EnvironmentName = "Production", ContentRootPath = AppContext.BaseDirectory});builder.Configuration.Sources.Clear();builder.Logging.ClearProviders();builder.WebHost.ConfigureKestrel(options =>{ options.Listen(IPAddress.Loopback, 0); options.Limits.MaxRequestBodySize = 16 * 1024;});builder.Services.AddOpenApi();await using var app = builder.Build();app.MapGet("/books/{id:int}", Results<Ok<BookDto>, NotFound> (int id) => id == 2 ? TypedResults.Ok(new BookDto(2, "Map Atlas")) : TypedResults.NotFound()) .WithName("GetBook");app.MapOpenApi();using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(15));await app.StartAsync(deadline.Token);try{ var address = new Uri(app.Urls.Single()); if (address.Host != "127.0.0.1" || address.Scheme != "http") throw new InvalidOperationException("Unexpected listener address."); using var client = new HttpClient(new HttpClientHandler { UseProxy = false, AllowAutoRedirect = false }) { BaseAddress = address }; using var response = await client.GetAsync("/openapi/v1.json", deadline.Token); response.EnsureSuccessStatusCode(); using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync(deadline.Token)); var operation = doc.RootElement.GetProperty("paths").GetProperty("/books/{id}").GetProperty("get"); var responses = operation.GetProperty("responses"); Console.WriteLine(responses.TryGetProperty("200", out _)); Console.WriteLine(responses.TryGetProperty("404", out _));}finally{ using var shutdown = new CancellationTokenSource(TimeSpan.FromSeconds(5)); await app.StopAsync(shutdown.Token);}record BookDto(int Id, string Title);The operation should describe both result alternatives. Document generation is pending actual restore and runtime verification.
Expected observation (reasoned, not executed):
TrueTrueShow metadata is not enforcement
Intentionally misleading metadata declares 200, but the handler sends 404; do not copy this pattern into a real API.
using System.Net;using System.Net.Http.Json;using System.Text;using System.Text.Json;using Microsoft.AspNetCore.Http.HttpResults;using Microsoft.AspNetCore.Mvc;
// Standalone lab: run in a clean, isolated environment only.var builder = WebApplication.CreateBuilder(new WebApplicationOptions{ Args = Array.Empty<string>(), EnvironmentName = "Production", ContentRootPath = AppContext.BaseDirectory});builder.Configuration.Sources.Clear();builder.Logging.ClearProviders();builder.WebHost.ConfigureKestrel(options =>{ options.Listen(IPAddress.Loopback, 0); options.Limits.MaxRequestBodySize = 16 * 1024;});await using var app = builder.Build();app.MapGet("/draft", () => Results.NotFound()).Produces<string>(200);using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(15));await app.StartAsync(deadline.Token);try{ var address = new Uri(app.Urls.Single()); if (address.Host != "127.0.0.1" || address.Scheme != "http") throw new InvalidOperationException("Unexpected listener address."); using var client = new HttpClient(new HttpClientHandler { UseProxy = false, AllowAutoRedirect = false }) { BaseAddress = address }; using var response = await client.GetAsync("/draft", deadline.Token); Console.WriteLine((int)response.StatusCode);}finally{ using var shutdown = new CancellationTokenSource(TimeSpan.FromSeconds(5)); await app.StopAsync(shutdown.Token);}Produces annotates the endpoint; it does not transform a 404 into a 200. Fix the declared contract rather than changing status to hide errors.
Expected observation (reasoned, not executed):
404Common mistakes and design boundaries
An OpenAPI document is not a test suite. Do not publish private schemas or allow unauthenticated operations merely because a UI is available. Avoid hardcoding an OpenAPI version without verifying generation settings. Version contracts deliberately, and test clients against realistic error paths as well as success.
Apply your understanding
Describe a GET /books/{id} contract with a JSON DTO on 200 and a bodyless 404. List what to inspect in the generated document and two actual HTTP checks.
Complete the linked manual practice and knowledge check. The examples are not automated ByteMind assessments.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
OpenAPI and response schemas — knowledge check
Apply the lesson concepts to the following scenarios.
What does OpenAPI describe?
What does MapOpenApi add?
Why use TypedResults for alternatives?
Produces declares 200 but the handler returns NotFound. What does the client get?
What is the best way to verify a response contract?