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#
requiredmodifier or[Required](System.ComponentModel.DataAnnotations), or whose type is a non-nullable reference type such asstring; a value-type property such asintwithout 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
| Property | Default | Meaning |
|---|---|---|
ValidateRequest | true | Validate the request body. |
ValidateResponse | false | Validate 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, Tags | none | Text for the OpenAPI document. |
Deprecated | false | Marks 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:
| Path | Content |
|---|---|
/openapi.json | The document in JSON |
/openapi.yaml | The document in YAML |
/.well-known/openapi | Links 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
operationIdis<service>_<path with / as _>_<METHOD>, for exampleinventory_items_{sku}_adjustments_POST; - each operation is tagged with its service name unless
[ValidateSchema(Tags = ...)]sets tags; the tag’s description is the service’sServiceDescription, else<service> microservice (v<version>); - an operation without a
Summaryis 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-timeoutandx-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:
| Key | Default | Meaning |
|---|---|---|
Gateway:OpenApi:Title | Gateway API | The document title |
Gateway:OpenApi:Description | Unified API aggregating all connected microservices. | The description |
Gateway:OpenApi:Version | 1.0.0 | The document version |
Gateway:OpenApi:ServerUrl | / | The server URL |
Gateway:OpenApi:TokenUrl | none | With 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.SourceGenis missing, so no schema exists. 422for a property the path supplies. The request type declares it as a non-nullable reference type, or with the C#requiredmodifier or[Required], so the schema requires it in the body; declare it nullable and withoutrequired.400instead of422. Validation did not run; check the first pitfall. A body that is not valid JSON gets422(keywordjson) on an endpoint with[ValidateSchema], and400on an endpoint without it.- The OpenAPI document lacks a service. The service is not connected; the document lists connected endpoints only.
