Skip to content

Latest commit

 

History

History
406 lines (323 loc) · 28.1 KB

plugin-rest-api.mdx

File metadata and controls

406 lines (323 loc) · 28.1 KB
title Plugin Rest Api — API Protocol reference
navTitle Plugin Rest Api
description Defines the schema for REST API plugins that register Discovery, Metadata, Data CRUD, Batch, and Permission routes with the HTTP Dispatcher.

{/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */}

REST API Plugin Protocol

Defines the schema for REST API plugins that register Discovery, Metadata, Data CRUD, Batch, and Permission routes with the HTTP Dispatcher.

This plugin type implements Phase 2 of the API Protocol implementation plan, providing standardized REST endpoints with:

  • Request validation middleware using Zod schemas
  • Response envelope wrapping with BaseResponseSchema
  • Error handling using ApiErrorSchema
  • OpenAPI documentation auto-generation

Features:

  • Route registration for core API endpoints
  • Automatic schema-based validation
  • Standardized request/response envelopes
  • OpenAPI/Swagger documentation generation

Architecture Alignment:

  • Salesforce: REST API with metadata and data CRUD
  • Microsoft Dynamics: Web API with entity operations
  • Strapi: Auto-generated REST endpoints from schemas

Serving routes from a platform plugin (imperative http.server mount)

// A PLATFORM plugin mounts its routes in CODE — resolve the `http.server`
// service from the plugin context and register handlers on `kernel:ready`
// (the service is registered by plugin-hono-server). This is the platform's
// own door-building primitive, not an app-author surface: an app declares
// `defineStack({ apis })`, computes in a flow, and registers code as a stack
// function or a connector. The worked
// manifest example that used to sit here declared `contributes.routes`,
// which was removed in @objectstack/spec 17 (commit bc56e1881): nothing ever read
// it, so every route it showed parsed cleanly and served nothing.
class RestApiPlugin {
  name = 'rest_api';
  async init(ctx: PluginContext) {
    ctx.hook('kernel:ready', async () => {
      const server = await ctx.getService<IHttpServer>('http.server');
      server.get('/api/v1/discovery', (req, res) => { ... });
      server.post('/api/v1/data/:object', (req, res) => { ... });
    });
  }
}

A declarative endpoint over a pipeline the platform already runs (query/return records, trigger a flow) is defineStack({ apis }) instead — no plugin code at all.

**Source:** `packages/spec/src/api/plugin-rest-api.zod.ts`

TypeScript Usage

import { ErrorHandlingConfigSchema, OpenApiGenerationConfigSchema, RequestValidationConfigSchema, ResponseEnvelopeConfigSchema, RestApiEndpointSchema, RestApiPluginConfigSchema, RestApiRouteCategory, RestApiRouteRegistrationSchema, ValidationMode } from '@objectstack/spec/api';
import type { ErrorHandlingConfig, OpenApiGenerationConfig, RequestValidationConfig, ResponseEnvelopeConfig, RestApiEndpoint, RestApiPluginConfig, RestApiRouteCategory, RestApiRouteRegistration, ValidationMode } from '@objectstack/spec/api';

// Validate data
const result = ErrorHandlingConfigSchema.parse(data);

ErrorHandlingConfig

Properties

Property Type Required Description
enabled boolean optional (default: true) Enable standardized error handling
includeStackTrace boolean optional (default: false) Include stack traces in error responses
logErrors boolean optional (default: true) Log errors to system logger
exposeInternalErrors boolean optional (default: false) Expose internal error details in responses
includeRequestId boolean optional (default: true) Include requestId in error responses
includeTimestamp boolean optional (default: true) Include timestamp in error responses
includeDocumentation boolean optional (default: true) Include documentation URLs for errors
documentationBaseUrl string optional Base URL for error documentation
customErrorMessages Record<string, string> optional Custom error messages by error code
redactFields string[] optional Field names to redact from error details

OpenApiGenerationConfig

Properties

Property Type Required Description
enabled boolean optional (default: true) Enable automatic OpenAPI documentation generation
version Enum<'3.0.0' | '3.0.1' | '3.0.2' | '3.0.3' | '3.1.0'> optional (default: "3.0.3") OpenAPI specification version
title string optional (default: "ObjectStack API") API title
description string optional API description
apiVersion string optional (default: "1.0.0") API version
outputPath string optional (default: "/api/docs/openapi.json") URL path to serve OpenAPI JSON
uiPath never optional [REMOVED] RestApiPluginConfig.openApi.uiPath was removed in @objectstack/spec 18.1.0 (ADR-0049 enforce-or-remove) — nothing ever read it: no documentation viewer was ever served at its path, the /api/docs default included, and the platform serves no HTML API documentation viewer at all, only the machine-readable OpenAPI document. Delete the key. The OpenAPI document is served at GET /api/v1/openapi.json under the REST server's default api.basePath and api.version (the path follows both) while api.enableOpenApi is on; point any viewer or client generator you run yourself at that document.
uiFramework never optional [REMOVED] RestApiPluginConfig.openApi.uiFramework was removed in @objectstack/spec 18.1.0 (ADR-0049 enforce-or-remove) — nothing ever read it: no swagger-ui, redoc, rapidoc or elements viewer was ever rendered from it, and the platform serves no HTML API documentation viewer at all, only the machine-readable OpenAPI document. Delete the key. The OpenAPI document is served at GET /api/v1/openapi.json under the REST server's default api.basePath and api.version (the path follows both) while api.enableOpenApi is on; point any viewer or client generator you run yourself at that document.
includeInternal boolean optional (default: false) Include internal endpoints in documentation
generateSchemas boolean optional (default: true) Auto-generate schemas from Zod definitions
includeExamples boolean optional (default: true) Include request/response examples
servers { url: string; description?: string }[] optional Server URLs for API
contact { name?: string; url?: string; email?: string } optional API contact information
license { name: string; url?: string } optional API license information
securitySchemes Record<string, { type: Enum<'apiKey' | 'http' | 'oauth2' | 'openIdConnect'>; scheme?: string; bearerFormat?: string }> optional Security scheme definitions

Nested Shape: OpenApiGenerationConfig.servers[number]

Property Type Required Description
url string ✅ Server URL
description string optional Server description

Nested Shape: OpenApiGenerationConfig.license

Property Type Required Description
name string ✅ License name
url string optional License URL

RequestValidationConfig

Properties

Property Type Required Description
enabled boolean optional (default: true) Enable automatic request validation
mode Enum<'strict' | 'permissive' | 'strip'> optional (default: "strict") How to handle validation errors
validateBody boolean optional (default: true) Validate request body against schema
validateQuery boolean optional (default: true) Validate query string parameters
validateParams boolean optional (default: true) Validate URL path parameters
validateHeaders boolean optional (default: false) Validate request headers
includeFieldErrors boolean optional (default: true) Include field-level error details in response
errorPrefix string optional Custom prefix for validation error messages
schemaRegistry string optional Schema registry name to use for validation

ResponseEnvelopeConfig

Properties

Property Type Required Description
enabled boolean optional (default: true) Enable automatic response envelope wrapping
includeMetadata boolean optional (default: true) Include meta object in responses
includeTimestamp boolean optional (default: true) Include timestamp in response metadata
includeRequestId boolean optional (default: true) Include requestId in response metadata
includeDuration boolean optional (default: false) Include request duration in ms
includeTraceId boolean optional (default: false) Include distributed traceId
customMetadata Record<string, any> optional Additional metadata fields to include
skipIfWrapped boolean optional (default: true) Skip wrapping if response already has success field

RestApiEndpoint

Properties

Property Type Required Description
method Enum<'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS'> ✅ HTTP method for this endpoint
path string ✅ URL path pattern (e.g., /api/v1/data/:object/:id)
handler string ✅ Protocol method name or handler identifier
category Enum<'discovery' | 'metadata' | 'data' | 'batch' | 'permission' | 'analytics' | 'automation' | 'ui' | 'realtime' | 'notification' | 'ai' | 'i18n'> ✅ Route category
public boolean optional (default: false) Is publicly accessible without authentication
permissions string[] optional Required permissions (e.g., ["data.read", "object.account.read"])
summary string optional Short description for OpenAPI
description string optional Detailed description for OpenAPI
tags string[] optional OpenAPI tags for grouping
requestSchema string optional Request schema name (for validation)
responseSchema string optional Response schema name (for documentation)
timeoutMs integer optional Request timeout in milliseconds
rateLimit string optional Rate limit policy name
cacheable boolean optional (default: false) Whether response can be cached
cacheTtlSeconds integer optional Cache TTL in seconds
timeout never optional [REMOVED] RestApiEndpoint.timeout was renamed to timeoutMs in @objectstack/spec 17 — the unit of a duration-shaped number lives in the key name, not only in the describe prose, and the neighbouring cache TTL two lines below is in SECONDS. Rename the key to timeoutMs; the value (milliseconds) is unchanged.
cacheTtl never optional [REMOVED] RestApiEndpoint.cacheTtl was renamed to cacheTtlSeconds in @objectstack/spec 17 — the unit of a duration-shaped number lives in the key name, not only in the describe prose, and the neighbouring request timeout two lines above is in MILLISECONDS. Rename the key to cacheTtlSeconds; the value (seconds) is unchanged.
handlerStatus never optional [REMOVED] RestApiEndpoint.handlerStatus was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — nothing ever read it: no registrar, dispatcher or adapter consulted the key, so an endpoint declared stub or planned was served exactly like an implemented one, and the 501 NOT_IMPLEMENTED its docstring promised is raised by the declarative-endpoint executor for a target it cannot serve, never from this field. Delete the key. An endpoint that has no handler yet is simply not registered; a declared-but-unbuilt route answering 501 is not a platform capability (ruling record, 2026-09-01).

RestApiPluginConfig

Properties

Property Type Required Description
enabled boolean optional (default: true) Enable REST API plugin
basePath string optional (default: "/api") Base path for all API routes
version string optional (default: "v1") API version identifier
routes { prefix: string; service: string; category: Enum<'discovery' | 'metadata' | 'data' | 'batch' | 'permission' | 'analytics' | …>; methods?: string[]; … }[] ✅ Route registrations
validation { enabled?: boolean; mode?: Enum<'strict' | 'permissive' | 'strip'>; validateBody?: boolean; validateQuery?: boolean; … } optional Request validation configuration
responseEnvelope { enabled?: boolean; includeMetadata?: boolean; includeTimestamp?: boolean; includeRequestId?: boolean; … } optional Response envelope configuration
errorHandling { enabled?: boolean; includeStackTrace?: boolean; logErrors?: boolean; exposeInternalErrors?: boolean; … } optional Error handling configuration
openApi { enabled?: boolean; version?: Enum<'3.0.0' | '3.0.1' | '3.0.2' | '3.0.3' | '3.1.0'>; title?: string; description?: string; … } optional OpenAPI documentation configuration
globalMiddleware { name: string; type: Enum<'authentication' | 'authorization' | 'logging' | 'validation' | 'transformation' | 'error' | 'custom'>; enabled?: boolean; order?: integer; … }[] optional Global middleware stack
cors { enabled?: boolean; origins?: string[]; methods?: Enum<'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS'>[]; credentials?: boolean } optional CORS configuration
performance { enableCompression?: boolean; enableETag?: boolean; enableCaching?: boolean; defaultCacheTtlSeconds?: integer } optional Performance optimization settings

Nested Shape: RestApiPluginConfig.routes[number]

Property Type Required Description
prefix string ✅ URL path prefix for this route group
service string ✅ Core service name (metadata, data, auth, etc.)
category Enum<'discovery' | 'metadata' | 'data' | 'batch' | 'permission' | 'analytics' | …> ✅ Primary category for this route group
methods string[] optional Protocol method names implemented
endpoints { method: Enum<'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS'>; path: string; handler: string; category: Enum<'discovery' | 'metadata' | 'data' | 'batch' | 'permission' | 'analytics' | …>; … }[] optional Endpoint definitions
middleware { name: string; type: Enum<'authentication' | 'authorization' | 'logging' | 'validation' | 'transformation' | 'error' | 'custom'>; enabled?: boolean; order?: integer; … }[] optional Middleware stack for this route group
authRequired boolean optional (default: true) Whether authentication is required by default
documentation { title?: string; description?: string; tags?: string[] } optional Documentation metadata for this route group

Nested Shape: RestApiPluginConfig.validation

Property Type Required Description
enabled boolean optional (default: true) Enable automatic request validation
mode Enum<'strict' | 'permissive' | 'strip'> optional (default: "strict") How to handle validation errors
validateBody boolean optional (default: true) Validate request body against schema
validateQuery boolean optional (default: true) Validate query string parameters
validateParams boolean optional (default: true) Validate URL path parameters
validateHeaders boolean optional (default: false) Validate request headers
includeFieldErrors boolean optional (default: true) Include field-level error details in response
errorPrefix string optional Custom prefix for validation error messages
schemaRegistry string optional Schema registry name to use for validation

Nested Shape: RestApiPluginConfig.responseEnvelope

Property Type Required Description
enabled boolean optional (default: true) Enable automatic response envelope wrapping
includeMetadata boolean optional (default: true) Include meta object in responses
includeTimestamp boolean optional (default: true) Include timestamp in response metadata
includeRequestId boolean optional (default: true) Include requestId in response metadata
includeDuration boolean optional (default: false) Include request duration in ms
includeTraceId boolean optional (default: false) Include distributed traceId
customMetadata Record<string, any> optional Additional metadata fields to include
skipIfWrapped boolean optional (default: true) Skip wrapping if response already has success field

Nested Shape: RestApiPluginConfig.errorHandling

Property Type Required Description
enabled boolean optional (default: true) Enable standardized error handling
includeStackTrace boolean optional (default: false) Include stack traces in error responses
logErrors boolean optional (default: true) Log errors to system logger
exposeInternalErrors boolean optional (default: false) Expose internal error details in responses
includeRequestId boolean optional (default: true) Include requestId in error responses
includeTimestamp boolean optional (default: true) Include timestamp in error responses
includeDocumentation boolean optional (default: true) Include documentation URLs for errors
documentationBaseUrl string optional Base URL for error documentation
customErrorMessages Record<string, string> optional Custom error messages by error code
redactFields string[] optional Field names to redact from error details

Nested Shape: RestApiPluginConfig.openApi

Property Type Required Description
enabled boolean optional (default: true) Enable automatic OpenAPI documentation generation
version Enum<'3.0.0' | '3.0.1' | '3.0.2' | '3.0.3' | '3.1.0'> optional (default: "3.0.3") OpenAPI specification version
title string optional (default: "ObjectStack API") API title
description string optional API description
apiVersion string optional (default: "1.0.0") API version
outputPath string optional (default: "/api/docs/openapi.json") URL path to serve OpenAPI JSON
uiPath never optional [REMOVED] RestApiPluginConfig.openApi.uiPath was removed in @objectstack/spec 18.1.0 (ADR-0049 enforce-or-remove) — nothing ever read it: no documentation viewer was ever served at its path, the /api/docs default included, and the platform serves no HTML API documentation viewer at all, only the machine-readable OpenAPI document. Delete the key. The OpenAPI document is served at GET /api/v1/openapi.json under the REST server's default api.basePath and api.version (the path follows both) while api.enableOpenApi is on; point any viewer or client generator you run yourself at that document.
uiFramework never optional [REMOVED] RestApiPluginConfig.openApi.uiFramework was removed in @objectstack/spec 18.1.0 (ADR-0049 enforce-or-remove) — nothing ever read it: no swagger-ui, redoc, rapidoc or elements viewer was ever rendered from it, and the platform serves no HTML API documentation viewer at all, only the machine-readable OpenAPI document. Delete the key. The OpenAPI document is served at GET /api/v1/openapi.json under the REST server's default api.basePath and api.version (the path follows both) while api.enableOpenApi is on; point any viewer or client generator you run yourself at that document.
includeInternal boolean optional (default: false) Include internal endpoints in documentation
generateSchemas boolean optional (default: true) Auto-generate schemas from Zod definitions
includeExamples boolean optional (default: true) Include request/response examples
servers { url: string; description?: string }[] optional Server URLs for API
contact { name?: string; url?: string; email?: string } optional API contact information
license { name: string; url?: string } optional API license information
securitySchemes Record<string, { type: Enum<'apiKey' | 'http' | 'oauth2' | 'openIdConnect'>; scheme?: string; bearerFormat?: string }> optional Security scheme definitions

Nested Shape: RestApiPluginConfig.globalMiddleware[number]

Property Type Required Description
name string ✅ Middleware name (snake_case)
type Enum<'authentication' | 'authorization' | 'logging' | 'validation' | 'transformation' | 'error' | 'custom'> ✅ Middleware type
enabled boolean optional (default: true) Whether middleware is enabled
order integer optional (default: 100) Execution order priority
config Record<string, any> optional Middleware configuration object
paths { include?: string[]; exclude?: string[] } optional Path filtering

Nested Shape: RestApiPluginConfig.performance

Property Type Required Description
enableCompression boolean optional (default: true) Enable response compression
enableETag boolean optional (default: true) Enable ETag generation
enableCaching boolean optional (default: true) Enable HTTP caching
defaultCacheTtlSeconds integer optional (default: 300) Default cache TTL in seconds
defaultCacheTtl never optional [REMOVED] RestApiPluginConfig.performance.defaultCacheTtl was renamed to defaultCacheTtlSeconds in @objectstack/spec 17 — the unit of a duration-shaped number lives in the key name, not only in the describe prose. Rename the key to defaultCacheTtlSeconds; the value (seconds) is unchanged.

RestApiRouteCategory

Allowed Values

  • discovery
  • metadata
  • data
  • batch
  • permission
  • analytics
  • automation
  • ui
  • realtime
  • notification
  • ai
  • i18n

RestApiRouteRegistration

Properties

Property Type Required Description
prefix string ✅ URL path prefix for this route group
service string ✅ Core service name (metadata, data, auth, etc.)
category Enum<'discovery' | 'metadata' | 'data' | 'batch' | 'permission' | 'analytics' | 'automation' | 'ui' | 'realtime' | 'notification' | 'ai' | 'i18n'> ✅ Primary category for this route group
methods string[] optional Protocol method names implemented
endpoints { method: Enum<'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS'>; path: string; handler: string; category: Enum<'discovery' | 'metadata' | 'data' | 'batch' | 'permission' | 'analytics' | …>; … }[] optional Endpoint definitions
middleware { name: string; type: Enum<'authentication' | 'authorization' | 'logging' | 'validation' | 'transformation' | 'error' | 'custom'>; enabled?: boolean; order?: integer; … }[] optional Middleware stack for this route group
authRequired boolean optional (default: true) Whether authentication is required by default
documentation { title?: string; description?: string; tags?: string[] } optional Documentation metadata for this route group

Nested Shape: RestApiRouteRegistration.endpoints[number]

Property Type Required Description
method Enum<'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS'> ✅ HTTP method for this endpoint
path string ✅ URL path pattern (e.g., /api/v1/data/:object/:id)
handler string ✅ Protocol method name or handler identifier
category Enum<'discovery' | 'metadata' | 'data' | 'batch' | 'permission' | 'analytics' | …> ✅ Route category
public boolean optional (default: false) Is publicly accessible without authentication
permissions string[] optional Required permissions (e.g., ["data.read", "object.account.read"])
summary string optional Short description for OpenAPI
description string optional Detailed description for OpenAPI
tags string[] optional OpenAPI tags for grouping
requestSchema string optional Request schema name (for validation)
responseSchema string optional Response schema name (for documentation)
timeoutMs integer optional Request timeout in milliseconds
rateLimit string optional Rate limit policy name
cacheable boolean optional (default: false) Whether response can be cached
cacheTtlSeconds integer optional Cache TTL in seconds
timeout never optional [REMOVED] RestApiEndpoint.timeout was renamed to timeoutMs in @objectstack/spec 17 — the unit of a duration-shaped number lives in the key name, not only in the describe prose, and the neighbouring cache TTL two lines below is in SECONDS. Rename the key to timeoutMs; the value (milliseconds) is unchanged.
cacheTtl never optional [REMOVED] RestApiEndpoint.cacheTtl was renamed to cacheTtlSeconds in @objectstack/spec 17 — the unit of a duration-shaped number lives in the key name, not only in the describe prose, and the neighbouring request timeout two lines above is in MILLISECONDS. Rename the key to cacheTtlSeconds; the value (seconds) is unchanged.
handlerStatus never optional [REMOVED] RestApiEndpoint.handlerStatus was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — nothing ever read it: no registrar, dispatcher or adapter consulted the key, so an endpoint declared stub or planned was served exactly like an implemented one, and the 501 NOT_IMPLEMENTED its docstring promised is raised by the declarative-endpoint executor for a target it cannot serve, never from this field. Delete the key. An endpoint that has no handler yet is simply not registered; a declared-but-unbuilt route answering 501 is not a platform capability (ruling record, 2026-09-01).

Nested Shape: RestApiRouteRegistration.middleware[number]

Property Type Required Description
name string ✅ Middleware name (snake_case)
type Enum<'authentication' | 'authorization' | 'logging' | 'validation' | 'transformation' | 'error' | 'custom'> ✅ Middleware type
enabled boolean optional (default: true) Whether middleware is enabled
order integer optional (default: 100) Execution order priority
config Record<string, any> optional Middleware configuration object
paths { include?: string[]; exclude?: string[] } optional Path filtering

Nested Shape: RestApiRouteRegistration.documentation

Property Type Required Description
title string optional Route group title
description string optional Route group description
tags string[] optional OpenAPI tags

ValidationMode

Allowed Values

  • strict
  • permissive
  • strip