apicontract

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: MIT Imports: 17 Imported by: 2 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

API contract for Workspace apps

Shared rules and tools for naming, parsing and paging HTTP queries in Workspace apps.

Clients, MCP tools and agents need to handle each app's date ranges, paging and errors. Shared names and formats let them reuse that handling. This module provides a query parser, a list response body and an error body. Its command checks openapi.json from apps written in any language.

Contract version: 0.1. It changes with this module's minor version.

The rules

Area Rule
Names Query parameters and JSON fields are snake_case. Free-text search is q.
Instants RFC 3339 with an offset, such as 2026-11-14T09:00:00+01:00.
Days YYYY-MM-DD, resolved in the tz parameter (an IANA zone), or UTC.
Ranges from and to, or <field>_from and <field>_to when a resource has several time fields. Both accept a timestamp or a day. from is inclusive. A timestamp in to is exclusive; a day in to includes that whole day.
Paging limit defaults to 50; values above 200 return 200. cursor is opaque and bound to the query and caller through Cursors and QueryBinding. The binding excludes cursor and limit.
Lists {"items": [...], "next_cursor": "..."}. next_cursor is absent on the last page. total appears only when it is exact and cheap.
Sorting sort=created_at,-title. A leading - sorts descending.
Errors {"error": "message", "code": "snake_case", "fields": [...]}. fields is omitted when empty. Query parsing returns 400 for malformed values and 422 for rule violations when no value is malformed.
Old names Keep page, per_page, page_size, offset, start, end, query and search accepted while callers move, and mark them deprecated in the spec. Routes must declare the old parameters; the parser does not add them.
Version info.x-whilesmart-contract in the OpenAPI document states the version the app meets.

The JSON Schemas in schema/ are the machine-readable form: shared query parameters, the list envelope and the error body.

Parse a list query

Declare the parameters a route takes as a struct. Embed the shared pieces and add your own fields with query tags.

type eventsQuery struct {
	apicontract.Page
	apicontract.Range
	apicontract.Zone
	CalendarID string                `query:"calendar_id"`
	Sort       []apicontract.SortKey `query:"sort" enum:"starts_at,title"`
	Start      time.Time             `query:"start" deprecated:"from"`
}

func listEvents(w http.ResponseWriter, r *http.Request) {
	var q eventsQuery
	if err := apicontract.BindQuery(r, &q); err != nil {
		apicontract.WriteProblem(w, err)
		return
	}
	// q.Limit is between 1 and 200, q.From and q.To are a half-open range.
	apicontract.WriteList(w, events, next)
}

With Gin, pass c.Request and c.Writer.

A field tagged deprecated:"from" accepts the old name and fills the declared from field when the caller leaves it empty or omits it. Different values, compared as trimmed strings, produce a conflict. The response is 422 unless another value is malformed, which makes it 400.

Name a range field to prefix its parameters. This field reads updated_from and updated_to:

Updated apicontract.Range `query:"updated"`

Supported tags: query, doc, default, required, minimum, maximum, clamp, maxLength, enum, deprecated and bound:"end".

Cursors

Cursors signs a page position and binds it to a string supplied by the app. Use QueryBinding with the query and caller IDs to reject a cursor from another caller or query with a 400. It excludes cursor and limit, so callers can change the page size.

cursors, err := apicontract.NewCursors(key) // at least 32 bytes
binding := apicontract.QueryBinding(r.URL.Query(), userID, ownerID)
next, err := cursors.Encode(binding, position)
err = cursors.Decode(q.Cursor, binding, &position)

Positions are signed, not encrypted. Do not put secrets in them.

Describe the same parameters elsewhere

  • InputSchema(eventsQuery{}) returns a JSON Schema object for tool inputs, such as MCP tools. It describes the route's parameter names and bounds; it does not parse inputs or apply aliases and clamping.
  • OpenAPIParameters(eventsQuery{}) returns OpenAPI 3.1 query parameter objects for specs built in code.

Check an OpenAPI document

The apicontract command checks contract rules in OpenAPI 3.0 and 3.1 JSON documents from any language. It follows local references, up to 16 steps, but does not resolve external references or validate the full OpenAPI specification. It checks GET, PUT, POST, PATCH and DELETE operations.

go run github.com/whilesmartgo/apicontract/cmd/apicontract@latest lint openapi.json

It reports:

Rule Fails when
contract-version info.x-whilesmart-contract is missing, empty or not a string.
param-name A query parameter is not snake_case.
param-legacy An old name such as page_size is not marked deprecated.
param-time-format A parameter named from, to, since or until, or ending in _from, _to, _since or _until, has no date or date-time format, directly or in anyOf or oneOf.
response-schema A GET route declares a 200 response with no content, or with application/json but no nonempty schema.
list-envelope A collection's 200 response schema has no items array. This check does not require next_cursor.
list-limit A collection has no limit, or limit is not an integer with a declared maximum of at most 200.
list-cursor A collection has no cursor.
error-responses A checked operation with query parameters or a body declares none of 400, 422 or 4XX.

A GET route is treated as a collection when its 200 application/json schema is an array or has an array in items or data, or when it declares limit, cursor, page, per_page, page_size or offset.

Adopt it on an existing API

Record current violations with a reason, then run the check in CI:

apicontract lint -exceptions api-contract.exceptions.json -seed "predates the contract" openapi.json
apicontract lint -exceptions api-contract.exceptions.json openapi.json

Violations that match no exception fail the run. An exception that matches no violation in a checked document also fails. An entry may use * for rule, method or path, and may omit subject to cover every parameter. Broad exceptions can accept new violations. Running -seed again adds exceptions for current violations and removes stale ones in checked documents. -report file.md writes accepted violations as a Markdown table.

License

MIT

Documentation

Overview

Package apicontract implements the shared HTTP API contract for Workspace apps.

It parses list and search query parameters into typed structs, writes the list envelope and the error body, signs opaque cursors, and describes the same parameters as JSON Schema and OpenAPI so specs and tool schemas match the parser.

Index

Constants

View Source
const (
	CodeMalformedQuery = "malformed_query"
	CodeInvalidQuery   = "invalid_query"
	CodeInternal       = "internal_error"
)

Error codes written in ErrorBody.Code.

View Source
const (
	FieldInvalid       = "invalid"
	FieldRequired      = "required"
	FieldOutOfRange    = "out_of_range"
	FieldTooLong       = "too_long"
	FieldUnknownValue  = "unknown_value"
	FieldConflict      = "conflict"
	FieldInvalidCursor = "invalid_cursor"
)

Field error codes written in FieldError.Code.

View Source
const (
	DefaultLimit    = 50
	MaxLimit        = 200
	MaxCursorLength = 2048
)
View Source
const Version = "0.1"

Version is the contract version this module implements. An OpenAPI document states the version it meets in info.x-whilesmart-contract.

View Source
const VersionExtension = "x-whilesmart-contract"

VersionExtension is the OpenAPI info extension that carries Version.

Variables

This section is empty.

Functions

func BindQuery

func BindQuery(r *http.Request, dst any) error

BindQuery parses the request's query string into dst, a pointer to a struct whose fields carry query tags. It returns a *Problem with status 400 when a value cannot be parsed and 422 when a parsed value breaks a rule. Any other error means dst is not a valid parameter struct.

func BindValues

func BindValues(values url.Values, dst any) error

BindValues parses values into dst. See BindQuery.

func InputSchema

func InputSchema(v any) (map[string]any, error)

InputSchema describes the parameters of the struct value v as a JSON Schema object. Use it for tool input schemas so tools accept the same names, formats and bounds as the HTTP route.

func OpenAPIParameters

func OpenAPIParameters(v any) ([]map[string]any, error)

OpenAPIParameters describes the parameters of the struct value v as OpenAPI 3.1 query parameter objects, for specs that are built in code.

func OpenAPIParametersOf

func OpenAPIParametersOf(fields []Field) ([]map[string]any, error)

OpenAPIParametersOf is OpenAPIParameters for a struct described by fields instead of a value.

func QueryBinding

func QueryBinding(values url.Values, principal ...string) string

QueryBinding returns a binding for a cursor from the query values that shape the result and from the principal parts, such as user and owner IDs. cursor and limit are left out so a client can change the page size between pages.

func WriteError

func WriteError(w http.ResponseWriter, status int, code, message string, fields ...FieldError) error

WriteError writes an error body with the given status.

func WriteJSON

func WriteJSON(w http.ResponseWriter, status int, value any) error

WriteJSON writes value as JSON with the given status.

func WriteList

func WriteList[T any](w http.ResponseWriter, items []T, next string) error

WriteList writes a 200 response with the list envelope.

func WriteProblem

func WriteProblem(w http.ResponseWriter, err error) error

WriteProblem writes err as an error body. Errors that are not a *Problem are written as a 500 without exposing their text.

Types

type Cursors

type Cursors struct {
	// contains filtered or unexported fields
}

Cursors signs and verifies opaque cursors. A cursor carries a JSON position and a MAC over the position and a binding, so it is rejected when replayed against a different query or principal. Positions are readable by anyone who decodes the cursor; do not put secrets in them.

func NewCursors

func NewCursors(key []byte) (*Cursors, error)

NewCursors returns a Cursors signing with key, which must be at least 32 bytes.

func (*Cursors) Decode

func (c *Cursors) Decode(cursor, binding string, position any) error

Decode verifies cursor against binding and decodes its position. A cursor that is malformed, tampered with or bound to something else returns a *Problem with status 400.

func (*Cursors) Encode

func (c *Cursors) Encode(binding string, position any) (string, error)

Encode returns a cursor for position, bound to binding.

type ErrorBody

type ErrorBody struct {
	Error  string       `json:"error"`
	Code   string       `json:"code"`
	Fields []FieldError `json:"fields,omitempty"`
}

ErrorBody is the JSON body of every error response. Error stays a plain string so clients that read it as a message keep working.

type Field

type Field struct {
	Name      string
	Exported  bool
	Anonymous bool
	Type      FieldType
	Tag       reflect.StructTag
	// Range is true when the field's type is apicontract.Range.
	Range bool
	// Fields holds the nested fields when Type is FieldStruct.
	Fields []Field
}

Field describes one struct field. Static tools that read Go source, such as OpenAPI generators, build Fields from the source types and pass them to OpenAPIParametersOf, so they describe a parameter struct exactly as BindQuery reads it. Fields lists every field of the struct in order.

type FieldError

type FieldError struct {
	Name    string `json:"name"`
	Code    string `json:"code"`
	Message string `json:"message"`
}

type FieldType

type FieldType int

FieldType classifies a struct field for parameter description.

const (
	FieldOther FieldType = iota
	FieldString
	FieldInt
	FieldBool
	FieldTime
	FieldLocation
	FieldSort
	FieldStrings
	FieldStruct
)

type List

type List[T any] struct {
	Items      []T    `json:"items"`
	NextCursor string `json:"next_cursor,omitempty"`
	Total      *int   `json:"total,omitempty"`
}

List is the response envelope for collection routes. NextCursor is empty on the last page. Total is set only when it is exact and cheap to compute.

func NewList

func NewList[T any](items []T, next string) List[T]

NewList returns a List whose Items encode as [] rather than null.

type Page

type Page struct {
	Limit  int    `` /* 135-byte string literal not displayed */
	Cursor string `` /* 141-byte string literal not displayed */
}

Page holds cursor paging parameters. Limit defaults to DefaultLimit and is clamped to MaxLimit.

type Problem

type Problem struct {
	Status  int
	Code    string
	Message string
	Fields  []FieldError
}

Problem is an error that knows its HTTP status and body.

func (*Problem) Body

func (p *Problem) Body() ErrorBody

func (*Problem) Error

func (p *Problem) Error() string

type Range

type Range struct {
	From time.Time `` /* 132-byte string literal not displayed */
	To   time.Time `query:"to" bound:"end" doc:"End of the range. A timestamp is exclusive. A YYYY-MM-DD day includes that whole day."`
}

Range is a half-open time range [From, To). A day value (YYYY-MM-DD) in From means the start of that day; in To it means the end of that day. Days are resolved in the request Zone, or UTC when the struct has no Zone.

Embedded without a query tag the parameters are from and to. As a named field with query:"updated" they are updated_from and updated_to.

type Search struct {
	Q string `query:"q" maxLength:"500" doc:"Free-text search."`
}

Search holds the free-text search parameter.

type SortKey

type SortKey struct {
	Field string
	Desc  bool
}

SortKey is one entry of a sort parameter such as sort=created_at,-title.

type Zone

type Zone struct {
	Location *time.Location `query:"tz" doc:"IANA time zone used to resolve YYYY-MM-DD days. Defaults to UTC."`
}

Zone holds the IANA time zone used to resolve day values.

Directories

Path Synopsis
cmd
apicontract command
Command apicontract checks OpenAPI documents against the API contract.
Command apicontract checks OpenAPI documents against the API contract.
Package lint checks an OpenAPI document against the API contract.
Package lint checks an OpenAPI document against the API contract.

Jump to

Keyboard shortcuts

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