Schema validation and OpenAPI

The source generator derives a JSON Schema from each typed endpoint’s request and response types. The schemas have two uses:

Validate request bodies

Add [ValidateSchema] to a typed endpoint. A body that does not match the schema gets 422 before the handler runs:

/// <summary>A stock adjustment: a whole number of units and a reason in the body.</summary>
public sealed record AdjustStockRequest
{
    /// <summary>
    /// Set by the SDK from {sku} in the path, after validation. Nullable, so the schema does not
    /// require it in the body.
    /// </summary>
    public string? Sku { get; init; }

    public required int Quantity { get; init; }

    public required string Reason { get; init; }
}

/// <summary>The stock after the adjustment.</summary>
public sealed record AdjustStockResponse(string Sku, int QuantityOnHand);

/// <summary>
/// Adjusts the stock of an item. [ValidateSchema] checks the JSON body against the schema the
/// source generator derives from AdjustStockRequest, so a body without the quantity or the reason, or
/// with a value of the wrong type, is answered 422 before the handler runs.
/// </summary>
[StellaEndpoint("POST", "/items/{sku}/adjustments", TimeoutSeconds = 10)]
[ValidateSchema(Summary = "Adjust the stock of an item", Tags = ["inventory"])]
public sealed class AdjustStockEndpoint : IStellaEndpoint<AdjustStockRequest, AdjustStockResponse>
{
    public Task<AdjustStockResponse> HandleAsync(AdjustStockRequest request, CancellationToken cancellationToken) =>
        Task.FromResult(new AdjustStockResponse(request.Sku ?? string.Empty, 100 + request.Quantity));
}
curl -i -X POST http://localhost:5080/items/SKU-001/adjustments \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d '{"quantity":"five"}'

Expected result: 422 with Content-Type: application/problem+json:

{
  "type": "urn:stellaops:router:schema-validation",
  "title": "Schema Validation Failed",
  "status": 422,
  "detail": "Request body failed schema validation for ...",
  "errors": [
    { "instanceLocation": "/quantity", "schemaLocation": "#/properties/quantity/type", "message": "...", "keyword": "type" }
  ]
}

type names the error kind; the gateway’s own errors use the same urn:stellaops:router: form. instanceLocation is a JSON pointer into the body. The message text depends on the validator. instance is the request path, here /items/SKU-001/adjustments.

What the schema requires

The schema describes the body only. The SDK validates the body first, then reads it into the request type, then sets properties from the query string and the path parameters (see Microservice SDK). The generated schema:

So a property that the path or the query fills, such as Sku above, is declared nullable and without required, or the schema requires it in the body as well. The gateway’s OpenAPI document shows the same schemas.

Attribute properties

PropertyDefaultMeaning
ValidateRequesttrueValidate the request body.
ValidateResponsefalseValidate the response body as well, against the schema of the response type (for development and tests). A response that fails is logged and the caller gets 500 Internal Server Error.
Summary, Description, TagsnoneText for the OpenAPI document.
DeprecatedfalseMarks the operation as deprecated in the OpenAPI document.

[ValidateSchema] on a raw endpoint is ignored and reported as STELLA006. A type whose schema cannot be generated is reported as STELLA005.

The gateway’s OpenAPI document

With Gateway:OpenApi:Enabled (default true), the gateway serves a document built from the endpoints and schemas of the connected services:

PathContent
/openapi.jsonThe document in JSON
/openapi.yamlThe document in YAML
/.well-known/openapiLinks to both forms, with the document’s ETag
curl -s http://localhost:5080/openapi.json -o openapi.json

The document changes as services connect and disconnect. It is cached for Gateway:OpenApi:CacheTtlSeconds (300 seconds) and built again when a service connects or disconnects. The answers carry Cache-Control: public, max-age=60 and an ETag; a request with a matching If-None-Match gets 304 Not Modified.

The document is OpenAPI 3.1.0:

A schema the service cannot compile is logged as an error at start-up, and the endpoint then runs without validation.

Settings:

KeyDefaultMeaning
Gateway:OpenApi:TitleGateway APIThe document title
Gateway:OpenApi:DescriptionUnified API aggregating all connected microservices.The description
Gateway:OpenApi:Version1.0.0The document version
Gateway:OpenApi:ServerUrl/The server URL
Gateway:OpenApi:TokenUrlnoneWith a token URL, the document declares an OAuth 2.0 client-credentials scheme that lists the scopes the endpoints require; without it, only the bearer scheme

The paths answer without a token. Turn the document off with Gateway:OpenApi:Enabled=false, or keep the paths internal, when it should not be public.

Pitfalls