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

📚 Interview question

Your OpenAPI document is wrong: some endpoints are missing, responses have no schema, polymorphic types show only the base class, enums appear as integers and nullability is wrong. How do you diagnose and fix it?

Debugging question on a wrong or incomplete OpenAPI document in ASP.NET Core: endpoints missing from API Explorer, untyped IResult responses, JsonPolymorphic and JsonDerivedType for oneOf, enum converters, nullable and required properties, and a snapshot test to keep it right.

Mid-Level Debugging Intermediate api-explorer aspnet-core debugging openapi polymorphism system-text-json

🎯 Key points

  • Start from the document itself and API Explorer: list ApiDescriptions in a test to see whether an endpoint is missing from metadata or only from the document
  • Missing endpoints: no AddEndpointsApiExplorer (Swashbuckle), ExcludeFromDescription, conventional MVC routes (API Explorer only describes attribute-routed actions), endpoints without an HTTP method, ShouldInclude or group-name filtering
  • No response schema: handler returns IResult; fix with TypedResults and Results<...> or Produces<T>()
  • Schemas follow the System.Text.Json contract: polymorphism needs [JsonPolymorphic] and [JsonDerivedType] to produce oneOf with a discriminator
  • Enums as strings need JsonStringEnumConverter configured for the API (ConfigureHttpJsonOptions or on the enum type) so wire format and document agree
  • Nullability comes from nullable reference type annotations; required comes from the required keyword, [Required] or constructor parameters
  • Impact on clients: generated clients silently drop undocumented fields, use any/object, or crash on unexpected nulls, so a wrong document is a data-loss risk
  • Fixing the contract can be a breaking change: lock it in with a snapshot test and route wire changes through the API's versioning policy

⏱ 30-second answer

I treat the document as output of metadata plus the System.Text.Json contract, and check each symptom against its source:

  • Missing endpoints: is it in API Explorer? Common causes are ExcludeFromDescription, conventional MVC routes, no AddEndpointsApiExplorer with Swashbuckle, or a document's ShouldInclude filter.
  • No response schema: the handler returns IResult; switch to TypedResults with Results<...>.
  • Polymorphism: add [JsonPolymorphic] / [JsonDerivedType] to get oneOf with a discriminator.
  • Enums as integers: register JsonStringEnumConverter for the API.
  • Nullability: enable nullable reference types and use required.

Then I add a snapshot test of the document. The trade-off: fixing the source (types, JSON options) is more work than patching with transformers, but keeps the docs and the wire format in step.

🗣 Full answer (senior)

How I would answer this in an interview

"The first thing I remember is that the generator doesn't read my code; it reads two things: endpoint metadata through API Explorer, and the System.Text.Json contract for each type. So every wrong thing in the document is either missing metadata or a JSON contract that differs from what I assumed. I start by fetching /openapi/v1.json and, in a quick test, listing IApiDescriptionGroupCollectionProvider descriptions. If an endpoint isn't in API Explorer, it's a metadata problem; if it is but the schema looks wrong, it's a contract problem.

For missing endpoints the usual causes are: ExcludeFromDescription or [ApiExplorerSettings(IgnoreApi = true)]; controllers using conventional routes, which API Explorer ignores, so they need attribute routing; endpoints mapped with plain Map and no HTTP method; Swashbuckle without AddEndpointsApiExplorer; or, with several documents, a ShouldInclude that filters by group name. For responses with no schema, it's nearly always a handler returning IResult, so I switch to Results<Ok<T>, NotFound> with TypedResults.

Polymorphism, enums and nullability are contract issues. A base type only shows its own properties unless it has [JsonPolymorphic] and [JsonDerivedType], and then the document gets a oneOf with a discriminator, which also means the serialiser actually writes the derived properties. Enums come out as integers because that's what System.Text.Json sends; I register JsonStringEnumConverter through ConfigureHttpJsonOptions or on the enum type, and the document and the wire format change together. Nullability follows nullable reference annotations, so a project without <Nullable>enable</Nullable> documents every reference as nullable, and required comes from the required keyword or [Required]. The mistake I see is fixing the document with a transformer so it says strings while the API still sends integers. Fix the contract, not the description of it."


Symptom to cause

Symptom Likely cause Fix
Endpoint missing ExcludeFromDescription, IgnoreApi, conventional MVC route, no HTTP method, ShouldInclude filter, no AddEndpointsApiExplorer with Swashbuckle Remove the exclusion, use attribute routing, map with MapGet/MapPost, fix the filter
200 with no schema Handler returns IResult TypedResults + Results<...>, or Produces<T>()
Error responses missing Produced by filters or middleware ProducesProblem, ProducesValidationProblem
Only base class shown No polymorphism metadata [JsonPolymorphic] + [JsonDerivedType]
Enums as integers Default System.Text.Json behaviour JsonStringEnumConverter in ConfigureHttpJsonOptions or on the enum
Everything nullable Nullable reference types disabled <Nullable>enable</Nullable>, correct annotations
Nothing required No required/[Required] and no constructor parameters required members or positional records
Document differs from runtime JSON Controllers configured with AddJsonOptions but the generator reads a different options instance Configure both, or put converters on the types

Diagnostic order

Step Tool
1. See what the generator sees /openapi/v1.json, jq, a viewer
2. Is the endpoint in metadata? API Explorer test, EndpointDataSource
3. What does the wire really look like? Call the endpoint, compare JSON with the schema
4. Fix the source Types, JSON options, metadata
5. Lock it in Snapshot test of the document

Production example

A partner reported that our PaymentMethod responses had properties the document didn't mention. The base record had no [JsonDerivedType], so the document showed only id and type, and their generated client discarded cardLast4 and bsb. Adding the polymorphism attributes produced a oneOf with a kind discriminator, and a snapshot test now fails if the document changes unexpectedly.

🔍 What the interviewer is checking

Checks that the candidate can trace document problems back to metadata or the JSON contract rather than patching the output.

Green flags

  • Separates API Explorer (metadata) problems from schema (contract) problems.
  • Knows [JsonPolymorphic]/[JsonDerivedType] and that they change serialisation too.
  • Fixes enums through JSON options so wire and docs agree.
  • Adds a snapshot test of the document.

Red flags

  • Hand-writes the spec or patches it with transformers to hide mismatches.
  • Doesn't know conventional routes are excluded from API Explorer.
  • Blames the generator without checking metadata.

📚 Learn in depth

1. Two inputs, one document

Endpoint metadata ---> API Explorer ---> paths, operations, parameters, response types
                                              |
System.Text.Json ---> JsonTypeInfo ----------> schemas (properties, types, nullability,
  options + attributes                          required, enums, polymorphism)
                                              |
                                    transformers -> document

If you understand which input owns a symptom, the fix is obvious. Transformers are the last resort, for things neither input can express.

2. Why endpoints go missing

  • Conventional routes (MapControllerRoute) aren't described by API Explorer; [ApiController] requires attribute routing for this reason.
  • No HTTP method: endpoints from app.Map("/x", ...) have no HttpMethodMetadata, so they can't be described as an operation.
  • Exclusion metadata: ExcludeFromDescription(), [ApiExplorerSettings(IgnoreApi = true)], or [ExcludeFromDescription].
  • Multiple documents: the default ShouldInclude matches the endpoint's group name to the document name; an endpoint in group v2 won't appear in v1.
  • Environment-conditional mapping: endpoints only mapped when IsDevelopment() vanish from a build-time document.

3. Polymorphism

[JsonPolymorphic(TypeDiscriminatorPropertyName = "kind")]
[JsonDerivedType(typeof(Card), "card")]
[JsonDerivedType(typeof(BankAccount), "bank")]
public abstract record PaymentMethod(Guid Id);

The built-in generator turns this into oneOf: [Card, BankAccount] with discriminator.propertyName: kind. Without the attributes, System.Text.Json serialises by the declared type, so for a PaymentMethod-typed property the derived properties are not even sent, which is a data bug, not just a docs bug.

4. Enums and nullability

  • Enums: JsonStringEnumConverter (or the generic JsonStringEnumConverter<TEnum>, which is AOT-safe) changes both the wire format and the schema to type: string, enum: [...].
  • Nullability: with NRT enabled, string? becomes type: ["string", "null"] in OpenAPI 3.1 and string doesn't. required in the schema comes from C# required members, [Required], [JsonRequired] or constructor parameters of records.

5. Snapshot testing

Fetch the document in a WebApplicationFactory test and compare it with an approved file (Verify, or a plain file compare). Any change shows as a diff that must be accepted deliberately. Pair it with the committed build-time spec for CI checks.

Try it yourself

  1. Map one endpoint with app.Map and one with app.MapGet; check which appears in the document.
  2. Return Results.Ok(dto) and TypedResults.Ok(dto) from two handlers and compare their responses.
  3. Add a polymorphic hierarchy with and without [JsonDerivedType]; compare both the document and the actual JSON.
  4. Toggle <Nullable> and diff the schemas.
  5. Write a Verify snapshot test for /openapi/v1.json.

💻 Code

Fixing the sources, not patching the document.

// Program.cs
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Http.HttpResults;

var builder = WebApplication.CreateBuilder(args);

// Enums as strings on the wire AND in the document (Minimal APIs read these options)
builder.Services.ConfigureHttpJsonOptions(o => o.SerializerOptions.Converters.Add(new JsonStringEnumConverter()));
builder.Services.AddOpenApi();

var app = builder.Build();
app.MapOpenApi();

// MapGet (not Map) so the endpoint has an HTTP method and is described
app.MapGet("/customers/{id:guid}/payment-methods", GetPaymentMethods)
   .WithName("GetPaymentMethods")
   .ProducesProblem(StatusCodes.Status403Forbidden); // produced by authorisation, not the handler

app.Run();

// Typed results: 200 + schema and 404 documented without Produces
static Results<Ok<PaymentMethod[]>, NotFound> GetPaymentMethods(Guid id) =>
    id == Guid.Empty
        ? TypedResults.NotFound()
        : TypedResults.Ok<PaymentMethod[]>([new Card(Guid.NewGuid(), "4242", CardBrand.Visa)]);

// Polymorphism: oneOf with a discriminator, and derived properties are actually serialised
[JsonPolymorphic(TypeDiscriminatorPropertyName = "kind")]
[JsonDerivedType(typeof(Card), "card")]
[JsonDerivedType(typeof(BankAccount), "bank")]
public abstract record PaymentMethod(Guid Id);

public sealed record Card(Guid Id, string Last4, CardBrand Brand) : PaymentMethod(Id);
public sealed record BankAccount(Guid Id, string Bsb, string AccountLast3, string? Nickname) : PaymentMethod(Id); // Nickname nullable, others required

public enum CardBrand { Visa, Mastercard, Amex }
// Tests/OpenApiSnapshotTests.cs: any change to the document must be approved
using Microsoft.AspNetCore.Mvc.Testing;

namespace Payments.Api.Tests;

public sealed class OpenApiSnapshotTests(WebApplicationFactory<Program> factory) : IClassFixture<WebApplicationFactory<Program>>
{
    [Fact]
    public async Task Document_matches_approved_snapshot()
    {
        var client = factory.CreateClient();
        var json = await client.GetStringAsync("/openapi/v1.json", TestContext.Current.CancellationToken);
        await VerifyJson(json); // Verify.Xunit: writes *.received.json on mismatch
    }
}

⚠ Common mistakes

  • Mistake: Patching the document with a transformer to say enums are strings. Why it is wrong: The API still sends integers, so clients generated from the document break at runtime. Instead: Change the JSON options or the enum type so wire and document agree.
  • Mistake: Assuming a missing endpoint is a generator bug. Why it is wrong: It is usually missing from API Explorer (exclusion, conventional route, no HTTP method, group filter). Instead: List API Explorer descriptions first.
  • Mistake: Returning IResult and wondering why the schema is empty. Why it is wrong: There is no type information to describe. Instead: TypedResults with Results<...>.
  • Mistake: Treating missing derived properties as a documentation issue only. Why it is wrong: Without [JsonDerivedType], System.Text.Json doesn't serialise them either. Instead: Add polymorphism attributes and test the actual JSON.
  • Mistake: Configuring converters only through AddControllers().AddJsonOptions(...) when the document is built from another options instance. Why it is wrong: The document and the runtime output can disagree. Instead: Configure both, or put [JsonConverter] on the type itself.
  • Mistake: Leaving nullable reference types off. Why it is wrong: Every reference property is documented as nullable and nothing is required, so generated clients are full of null checks. Instead: Enable NRT and use required or positional records.
  • Mistake: Not testing the document. Why it is wrong: It silently regresses with every refactor. Instead: Snapshot test it and commit a build-time spec.

🏛 Senior insight: trade-offs

A wrong OpenAPI document is usually a symptom of a real contract problem: an API that sends integers clients don't expect, derived properties that never leave the server, or nullability nobody decided. The senior move is to fix the source and make the document trustworthy enough that clients are generated from it, then guard it with a snapshot test so regressions show up in review.

Two things a senior adds. First, the client impact: generators trust the document, so an undocumented property is silently discarded, a missing schema becomes any, and a wrongly non-nullable field crashes a strongly typed client the first time it is null. That makes document accuracy a data-integrity concern, not cosmetics. Second, the fix itself can break consumers: switching enums to strings or adding a discriminator changes the wire format. Treat it like any contract change: agree it with consumers, ship it in a new version (or behind a compatible addition), and let the breaking-change check in CI make the decision visible. Consistent design rules (one error shape via ProblemDetails, one enum style, explicit nullability, discriminated hierarchies) make the document accurate almost automatically, because there are fewer special cases to describe.

Fix location When it fits Cost When not to
Types (attributes, required, NRT) Contract issues: polymorphism, nullability, enums Touches DTOs Third-party types you don't own
JSON options App-wide wire-format choices Changes every response, may be breaking One-off exceptions
Endpoint metadata Missing endpoints or responses A few lines per endpoint Contract shape problems
Schema transformer Formats, examples, third-party types Can drift from the wire Anything the serialiser can express
New API version The fix changes the wire format for existing clients Two versions to run for a while Purely additive fixes

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says the endpoint is missing from API Explorer. Why: Checks the metadata model behind missing endpoints and response types.
    How to answer

    Every endpoint carries an EndpointMetadataCollection: a list of objects added by attributes, conventions like WithName, WithTags, RequireAuthorization, and types that implement IEndpointMetadataProvider such as TypedResults. Many features read that list:

    • API Explorer (IApiDescriptionGroupCollectionProvider) turns it into ApiDescriptions that the OpenAPI generator uses: Produces, ProducesProblem, WithTags, WithSummary.
    • LinkGenerator uses the endpoint name from WithName, which is also the operationId.
    • Authorisation, CORS, rate limiting and output caching middleware read it from HttpContext.GetEndpoint().

    The trade-off: metadata is one source of truth for docs and behaviour, but anything not in metadata (a hand-written IResult, a manual status code) is invisible to the docs.

  2. When: Candidate suggests a snapshot test or committed spec. Why: Checks committing the spec so regressions show up in review.
    How to answer

    Adding the Microsoft.Extensions.ApiDescription.Server package makes dotnet build produce the OpenAPI document. It launches your app's entry point with an inert server, asks the registered document provider for each document, and writes {Project}.json to obj (or to OpenApiDocumentsDirectory). Because your start-up code runs during build, guard anything that connects to databases or Key Vault.

    I commit the spec: API changes then show up as diffs in pull requests, CI can fail when the regenerated file differs, and clients are generated from a file rather than a running server. For clients I use Kiota (C#, TypeScript, Go, Python...) or NSwag (C#, TypeScript).

    The trade-off: a slightly slower build and a guarded Program.cs, in exchange for a contract you can review, diff and generate from.

  3. When: Candidate notes that switching enums to strings is a breaking change. Why: Checks how contract fixes that change the wire format are versioned and checked in CI.
    How to answer

    I make the committed build-time spec the contract and gate pull requests on it:

    1. Drift check: rebuild and fail if the generated spec differs from the committed one.
    2. Breaking-change check: oasdiff breaking compares the PR's spec with main and the last released spec, and fails on removed paths or properties, new required request fields, narrowed enums or changed types.
    3. Lint: Spectral rules for house style (operationIds, ProblemDetails errors, naming).
    4. Versioning: one document per major version (AddOpenApi("v1"), AddOpenApi("v2")), so breaking changes go into a new version while v1 stays frozen.

    The trade-off: CI becomes stricter and occasionally needs a deliberate override, but breaking changes become explicit decisions instead of production incidents.

🛠 Real-world problems: how you handle them

Partner client dropped bank account fields because the document lacked polymorphism
Situation
A [payments] API on .NET 10 consumed by [3] partners who generate clients from our OpenAPI document. `PaymentMethod` had two derived records (card and bank account).
Signals
A partner ticket said bank account details were missing from their app; their generated client had only `id` and `type` on `PaymentMethod`; our own JSON logs showed the derived properties were also absent from some responses where the property was typed as the base.
Investigation
Fetched `/openapi/v1.json` and saw a single `PaymentMethod` schema with no `oneOf`; called the endpoint directly and compared the JSON; found responses typed as `PaymentMethod[]` serialised only base properties; confirmed no `[JsonDerivedType]` existed and enums were integers too.
Resolution
Added `[JsonPolymorphic]` and `[JsonDerivedType]` with a `kind` discriminator and registered `JsonStringEnumConverter`, after agreeing the change with partners because both were wire-format changes. Published the new document and partners regenerated their clients.
Prevention
A Verify snapshot test of the document, a committed build-time spec with a breaking-change check in CI, and a checklist item for any new DTO hierarchy.

How to tell it (STAR)

**S:** A partner of our [payments] API at [company] reported missing bank account details, and their client was generated from our OpenAPI document. **T:** I owned finding out whether it was their client or our contract. **A:** I compared the document with the real JSON, found our base-typed responses weren't serialising derived properties and the document had no `oneOf`, added polymorphism attributes and a string enum converter, coordinated the wire change with partners, and added a snapshot test of the document. **R:** All [3] partners regenerated within [a week], the missing-field tickets stopped, and the snapshot test has since caught [2] unintended contract changes before release.

↩ Usually asked after

More in API Features

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me