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:

  • the service validates request bodies against them when the endpoint has [ValidateSchema];
  • the service publishes them to the gateway, which serves one OpenAPI document for every connected endpoint.

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:

  • requires a property that has the C# required modifier or [Required] (System.ComponentModel.DataAnnotations), or whose type is a non-nullable reference type such as string; a value-type property such as int without either is optional;
  • gives a nullable property its own type and allows null: string? is ["string", "null"], List<string>? is ["array", "null"], int? is ["integer", "null"].

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:

  • each operation’s operationId is <service>_<path with / as _>_<METHOD>, for example inventory_items_{sku}_adjustments_POST;
  • each operation is tagged with its service name unless [ValidateSchema(Tags = ...)] sets tags; the tag’s description is the service’s ServiceDescription, else <service> microservice (v<version>);
  • an operation without a Summary is summarised as <METHOD> <path>;
  • schema names carry the service name as prefix, so two services can use the same type name;
  • each operation carries the extensions x-stellaops-gateway-auth (the claims the gateway checks), x-stellaops-timeout and x-stellaops-timeout-seconds.

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

  • Validation never fires. The endpoint is raw, or StellaOps.Microservice.SourceGen is missing, so no schema exists.
  • 422 for a property the path supplies. The request type declares it as a non-nullable reference type, or with the C# required modifier or [Required], so the schema requires it in the body; declare it nullable and without required.
  • 400 instead of 422. Validation did not run; check the first pitfall. A body that is not valid JSON gets 422 (keyword json) on an endpoint with [ValidateSchema], and 400 on an endpoint without it.
  • The OpenAPI document lacks a service. The service is not connected; the document lists connected endpoints only.