api-toolkit

module
v3.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 21, 2026 License: Apache-2.0

README

api-toolkit

Reusable building blocks for Go HTTP APIs that enforce Dependency Inversion. Your application depends on stable ports interfaces, while this toolkit ships adapters for popular libraries in a separate contrib module.

Audience: Go service developers evaluating the toolkit, maintainers checking the stable surface, and release reviewers looking for the canonical docs path.

Modules

Module Import path Use for
Core github.com/aatuh/api-toolkit/v3 Stable ports, middleware, httpx, endpoint helpers, scheduler, and v3 API-gated production primitives.
Contrib github.com/aatuh/api-toolkit/contrib/v3 Third-party adapters, integrations, examples, and tooling outside the stable core API promise.

Install both when following the getting-started guide:

go get github.com/aatuh/api-toolkit/v3
go get github.com/aatuh/api-toolkit/contrib/v3

Supported development and CI toolchain policy: root and contrib target Go 1.25.x. Local and release gates should run with GOTOOLCHAIN=local so drift between module go directives, GitHub Actions setup, and release evidence is visible before publication.

Start here

Package map

Core packages:

  • ports defines toolkit-wide boundary contracts.
  • compat/billing is the explicit compatibility package for the current hosted-checkout and invoicing model.
  • Runtime middleware: middleware/* covers JSON enforcement, timeouts, body/query limits, rate limiting, idempotency, secure headers, tracing, tenant context, deprecation headers, API key auth, JWT auth, and role authz.
  • Request and response helpers: binding, queryparams, upload, httpcache, negotiation, httpx, httpx/identity, httpx/recover, and fielderrors cover validation, collection queries, multipart uploads, conditional requests, content negotiation, JSON responses, Problem Details, request identity, panic recovery, and field errors.
  • Contract and OpenAPI workflow: routecontracts, routepolicy, specs, contracttest, swagstub, and authorization keep runtime route registration, policy metadata, generated OpenAPI, tests, and authorization context aligned.
  • Operations and integrations primitives: endpoints/*, operations, idempotent, webhooks, oauth2, securityprofile, scheduler, scheduler/migrations, and email cover system endpoints, pagination, async operation contracts, idempotent HTTP contracts, webhook contracts, OAuth2 scope helpers, security profiles, jobs, migrations, and email ports.
  • Testing and client helpers: apitest and apiclient provide application test assertions and small client-side helpers without becoming a generated SDK.

Contrib packages:

  • adapters/* provides concrete implementations for routers, logging, validation, Postgres, Redis, Stripe, Resend, outbound HTTP, IDs, clocks, and policy engines.
  • middleware/* provides CORS, request logging, metrics, OpenAPI validation, OpenTelemetry tracing, Clerk auth, and development-only auth headers.
  • integrations/* provides convenience wrappers around selected adapters.
  • bootstrap, config, telemetry, migrator, countrycodes, and contrib email helpers support application wiring.
  • cmd/api-toolkit provides developer tooling for generating production-oriented SaaS API and web skeletons, generated Go/TypeScript clients, OpenAPI contract artifacts, observability bundles, and deployment starters.

For API and test-status ownership, use docs/package-classification.tsv and the human guide in docs/package-doc-standard.md.

Production readiness

api-toolkit v3 is production-credible for conventional Go JSON/HTTP APIs and generated SaaS/API services. It is not a universal backend platform for every transport, streaming workload, provider workflow, or organization-specific operating model. Use docs/production-readiness.md as the readiness matrix and adapter maturity review before standardizing on a package or generated profile. Generated code is app-owned; api-toolkit standardizes infrastructure defaults without becoming your product or provider framework.

Area Readiness Notes
Stable core packages Stable SemVer surface Covered by VERSIONING.md, scripts/apicheck.sh, package classification, and release evidence.
Supported contrib adapters Supported adapter tier Direct tests, docs, drift coverage, and behavior contracts are required; supported-adapter incompatible drift is gate-enforced and does not make contrib stable.
Experimental contrib packages Maintained but unstable Use only with app-owned compatibility expectations until promoted with evidence.
saas-api scaffold Lean service starter Keeps production-safe HTTP defaults without forcing persistence or membership models.
saas-api-full scaffold Production reference scaffold Includes Postgres, Redis, tenancy, API keys, async/outbox, audit, webhooks, OpenAPI 3.1, clients, and deployment starters. Generated code is app-owned.
Streaming, SSE, WebSockets, and large downloads Explicit caveat Use route-level opt-outs; do not apply hard-timeout response buffering, response validation, or idempotency response capture globally.

Streaming routes, server-sent events, websocket upgrades, and large downloads should be marked with x-api-toolkit-streaming and wired with securityprofile.StreamingRouteOverride or equivalent route-specific middleware. This preserves optional http.ResponseWriter interfaces and avoids buffering or validating responses that are not finite JSON documents.

Health endpoint contract

The health package exposes separate liveness, readiness, and detailed health behaviors:

  • Liveness and readiness are expected to reflect configured checker state and should not silently report healthy when no probe checks are configured.
  • Detailed health output is an operator-focused surface because it can include dependency-level status and check details.
  • ports.HealthCheckConfig.EnableDetailed controls whether HTTP packages should expose detailed health responses.
  • Mount detailed health, pprof, and metrics behind admin/internal access control or upstream network policy; prefer Handler.RegisterPublicRoutesTo, Handler.RegisterAdminDetailedHealthRoute, pprof.RegisterAdminRoutes, and bootstrap.MountSystemEndpointsToWithAdmin for new mounts because operator-only routes require an explicit wrapper.
  • HTTP dependency check URLs are application configuration. Do not derive them from request parameters or tenant-controlled input.
  • Missing checker registrations or invalid probe wiring should fail closed and surface as unhealthy state rather than synthetic success.
  • When EnableCaching is true, checker results may be reused across health endpoints until CacheDuration expires.

Safe system endpoint mounting should keep public probes separate from operator-only dependency detail, metrics, and pprof. Web, mobile, and desktop clients should use public probes only; they should never call operator-only endpoints directly. If you mount pprof outside the bootstrap helper, use pprof.RegisterAdminRoutes. If you split routers manually, use healthHandler.RegisterPublicRoutesTo(publicRouter) for public probes and healthHandler.RegisterAdminDetailedHealthRoute(adminRouter, requireAdmin) for operator detail.

err := bootstrap.MountSystemEndpointsToWithAdmin(router, bootstrap.SystemEndpoints{
	Health:  healthHandler,
	Metrics: bootstrap.PrometheusMetricsHandler(),
	Pprof:   pprof.Handler(),
}, bootstrap.SystemEndpointAdminOptions{
	RequireAdmin: requireAdmin,
	EnablePprof:  true,
})
if err != nil {
	return err
}

Security and operations

Stability

Stable core package list: VERSIONING.md is the source of truth, and scripts/apicheck.sh must cover the same package list.

Release command details live in docs/release-runbook.md. Keep this landing page as a pointer, not a second release runbook.

  • Release review checklist: docs/release-review.md
  • Release notes: docs/release-notes.md
  • Release manifests guide: docs/release-manifests.md
  • Contrib drift package manifest: docs/contrib-api-drift-packages.txt
  • Contrib drift disposition manifest: docs/contrib-api-drift-dispositions.tsv
  • Current supported v3 API baseline: see docs/release-runbook.md.
  • First v3 major-release evidence may compare against v2.1.0 only as documented v2-to-v3 breakage evidence, for example API_BASE_REF=v2.1.0 GOTOOLCHAIN=local make release-check and API_BASE_REF=v2.1.0 GOTOOLCHAIN=local make release-evidence; v3 patch and minor releases compare against the latest published v3 tag.
  • Release readiness requires an explicit baseline, for example API_BASE_REF=v3.1.0 GOTOOLCHAIN=local make release-check for a post-v3.1.0 v3 release.
  • Publication evidence requires an explicit baseline, for example API_BASE_REF=v3.1.0 GOTOOLCHAIN=local make release-evidence, from a clean worktree.
  • ALLOW_DIRTY_RELEASE_EVIDENCE=1 API_BASE_REF=v3.1.0 GOTOOLCHAIN=local make release-evidence is only for local dirty-tree audit evidence and is not acceptable before publishing.
  • make finalize is not release evidence.
  • make release-api-check, make contrib-api-drift-report, and make contrib-release-notes-check are explained in the runbook. Supported-adapter contrib packages are still outside the stable core API promise; supported-adapter incompatible drift is gate-enforced and does not make contrib stable.
Adapter coverage policy

Use docs/package-classification.tsv as the source of truth for API and test coverage status.

  • wrapper-only packages may use wrapper-smoke-tested only when smoke coverage is sufficient because the wrapper delegates behavior to another maintained package.
  • Wrapper smoke tests must prove interface satisfaction, constructor/defaults, disabled or nil behavior, and option propagation.
  • example-only packages are build-smoke checked and are not behavior-complete coverage.
  • Public packages need direct tests unless explicitly classified as wrapper, example, generated, tooling, test-support, or excluded.
  • needs-tests is a release blocker until replaced with direct tests or a documented exception.

Local documentation checks

For documentation-only changes, prefer:

GOTOOLCHAIN=local make docs-check

For implementation changes, examples, package docs, generated files, scripts, or repo-wide contracts, use the workflow in docs/README.md to choose between docs-check, fast-check, audit-check, and finalize.

Directories

Path Synopsis
Package apiclient provides small client-side helpers for api-toolkit APIs.
Package apiclient provides small client-side helpers for api-toolkit APIs.
Package apitest provides HTTP response assertions for application tests.
Package apitest provides HTTP response assertions for application tests.
Package authorization provides stable helpers for API authorization boundaries.
Package authorization provides stable helpers for API authorization boundaries.
Package binding decodes HTTP request body, query, and path values into typed structs and returns api-toolkit field errors.
Package binding decodes HTTP request body, query, and path values into typed structs and returns api-toolkit field errors.
compat
billing
Package billing exposes the provider-shaped v2 billing compatibility surface outside the generic ports package.
Package billing exposes the provider-shaped v2 billing compatibility surface outside the generic ports package.
Package contracttest provides testing helpers for API contract drift checks.
Package contracttest provides testing helpers for API contract drift checks.
Package docscheck contains documentation contract tests.
Package docscheck contains documentation contract tests.
Package email defines the stable core email port.
Package email defines the stable core email port.
endpoints
docs
Package docs registers stable API documentation and OpenAPI endpoints.
Package docs registers stable API documentation and OpenAPI endpoints.
health
Package health registers stable liveness, readiness, and detailed health endpoints.
Package health registers stable liveness, readiness, and detailed health endpoints.
list
Package list provides stable list-query parsing and list response helpers.
Package list provides stable list-query parsing and list response helpers.
pprof
Package pprof registers Go pprof handlers on an HTTP router.
Package pprof registers Go pprof handlers on an HTTP router.
version
Package version registers a stable JSON version endpoint.
Package version registers a stable JSON version endpoint.
Package fielderrors defines stable field-level validation error shapes.
Package fielderrors defines stable field-level validation error shapes.
Package httpcache provides conditional request helpers for REST APIs.
Package httpcache provides conditional request helpers for REST APIs.
Package httpx provides HTTP utilities, including RFC 9457 Problem Details helpers.
Package httpx provides HTTP utilities, including RFC 9457 Problem Details helpers.
identity
Package identity resolves canonical request identity values.
Package identity resolves canonical request identity values.
recover
Package recover provides panic recovery utilities for HTTP handlers.
Package recover provides panic recovery utilities for HTTP handlers.
Package idempotent standardizes HTTP contracts for idempotent API workflows.
Package idempotent standardizes HTTP contracts for idempotent API workflows.
middleware
auth/apikey
Package apikey provides stable API key authentication middleware.
Package apikey provides stable API key authentication middleware.
auth/authz
Package authz provides role-based authorization middleware.
Package authz provides role-based authorization middleware.
auth/jwt
Package jwt provides stable JWT authentication middleware.
Package jwt provides stable JWT authentication middleware.
auth/shared
Package shared centralizes auth middleware primitives that need to stay behaviorally aligned across JWT-based integrations.
Package shared centralizes auth middleware primitives that need to stay behaviorally aligned across JWT-based integrations.
auth/tenant
Package tenant provides stable tenant scoping middleware.
Package tenant provides stable tenant scoping middleware.
deprecation
Package deprecation emits runtime Deprecation, Sunset, and Link headers.
Package deprecation emits runtime Deprecation, Sunset, and Link headers.
idempotency
Package idempotency provides stable HTTP idempotency middleware.
Package idempotency provides stable HTTP idempotency middleware.
json
Package jsonmw provides stable JSON request helpers and middleware.
Package jsonmw provides stable JSON request helpers and middleware.
maxbody
Package maxbody provides stable request-body size limiting middleware.
Package maxbody provides stable request-body size limiting middleware.
querylimits
Package querylimits provides query parameter guardrails.
Package querylimits provides query parameter guardrails.
ratelimit
Package ratelimit provides stable rate-limit middleware over ports.RateLimiter.
Package ratelimit provides stable rate-limit middleware over ports.RateLimiter.
secure
Package secure provides stable security header middleware.
Package secure provides stable security header middleware.
timeout
Package timeout provides cooperative request-deadline middleware and an explicit hard timeout variant for handlers that need a synthesized timeout response when downstream code ignores context cancellation.
Package timeout provides cooperative request-deadline middleware and an explicit hard timeout variant for handlers that need a synthesized timeout response when downstream code ignores context cancellation.
trace
Package trace provides stable request trace and correlation middleware.
Package trace provides stable request trace and correlation middleware.
Package negotiation provides HTTP content negotiation helpers.
Package negotiation provides HTTP content negotiation helpers.
Package oauth2 provides provider-neutral OAuth2 bearer-token helpers.
Package oauth2 provides provider-neutral OAuth2 bearer-token helpers.
Package operations provides HTTP contracts for asynchronous API operations.
Package operations provides HTTP contracts for asynchronous API operations.
Package ports provides toolkit-wide boundary contracts.
Package ports provides toolkit-wide boundary contracts.
Package queryparams parses common collection query parameters.
Package queryparams parses common collection query parameters.
Package routecontracts registers HTTP routes and OpenAPI operations together.
Package routecontracts registers HTTP routes and OpenAPI operations together.
Package routepolicy derives opt-in runtime middleware from route contracts.
Package routepolicy derives opt-in runtime middleware from route contracts.
Package scheduler provides stable background job scheduling primitives.
Package scheduler provides stable background job scheduling primitives.
migrations
Package migrations provides stable scheduler migration helpers.
Package migrations provides stable scheduler migration helpers.
Package securityprofile provides security posture defaults.
Package securityprofile provides security posture defaults.
Package specs provides stable OpenAPI registry utilities and endpoint constants.
Package specs provides stable OpenAPI registry utilities and endpoint constants.
Package swagstub provides stable stubs for swagger-based workflows.
Package swagstub provides stable stubs for swagger-based workflows.
testutil
Package upload decodes multipart upload requests with validation errors.
Package upload decodes multipart upload requests with validation errors.
Package webhooks provides reusable webhook receiver and signing primitives.
Package webhooks provides reusable webhook receiver and signing primitives.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL