apicontract

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: MIT Imports: 25 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 query strings, request bodies, paging and errors in Workspace app APIs.

Apps that share parameter names, paging and errors can share client code. This module gives Go apps a parser for query strings and JSON bodies, the list response, RFC 9457 error bodies and signed cursors. Its command checks the openapi.json of an app written in any language.

Contract version: 0.1. The package exposes this version as Version.

Standards it builds on

Topic Source
Methods, status codes, 413, 415, 422 RFC 9110, HTTP Semantics
Timestamps RFC 3339
Error bodies RFC 9457, Problem Details for HTTP APIs
Time zones IANA time zone database
Idempotency keys IETF draft draft-ietf-httpapi-idempotency-key-header
Parameter names, cursor paging, snake_case Zalando RESTful API Guidelines

The contract departs from the Zalando guidelines in two places. Requests that parse but break a rule get 422, as RFC 9110 defines it; Zalando sends 400 for both. Request schemas set additionalProperties: false and the parser rejects fields it does not know; Zalando asks servers to report unknown input but asks schemas to stay open.

The rules

Area Rule
Names Query parameters and JSON fields are snake_case. Free-text search is q.
Unknown input Undeclared query parameters and body fields are rule violations (422 unless another input is malformed). A declared query parameter sent twice is malformed (400).
Instants RFC 3339 with upper-case T and either a numeric offset or Z, such as 2026-11-14T09:00:00+01:00.
Days YYYY-MM-DD. In a query range, a day is read 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. Use the cursor helpers to bind cursor to the query and caller.
Lists {"items": [...], "next_cursor": "..."}. next_cursor is omitted when empty. Set total only when it is exact and cheap to compute.
Sorting sort=created_at,-title. A leading - sorts descending.
Bodies JSON objects sent as application/json, at most 1 MiB unless the route says otherwise.
Errors RFC 9457 problem details as application/problem+json, with a stable code and an optional errors list. 400 when input cannot be parsed, 422 when it parses but breaks a rule, 413 for a body that is too large, 415 for a missing or unsupported content type.
Retries Creating requests may send Idempotency-Key: a quoted string as the IETF draft defines it, or a bare key of visible ASCII without commas, quotes or backslashes. The decoded key is 8 to 128 characters.
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.
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 problem body. docs/errors.md explains each problem code; problems with built-in codes link there through type.

Examples

The examples have outputs checked by go test.

Page through a list

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

type notesList struct {
	apicontract.Page
	apicontract.Search
}

func listNotes(w http.ResponseWriter, r *http.Request) {
	var q notesList
	if err := apicontract.BindQuery(r, &q); err != nil {
		apicontract.WriteProblem(w, err)
		return
	}
	binding := apicontract.RequestBinding(r, userID)
	var after struct{ ID int `json:"id"` }
	if q.Cursor != "" {
		if err := cursors.Decode(q.Cursor, binding, &after); err != nil {
			apicontract.WriteProblem(w, err)
			return
		}
	}
	notes, last := loadNotesAfter(after.ID, q.Limit)
	next := ""
	if !last {
		next, _ = cursors.Encode(binding, map[string]int{"id": notes[len(notes)-1].ID})
	}
	apicontract.WriteList(w, notes, next)
}

GET /notes?limit=2, then the same request with the returned cursor, then that cursor with a different query (q=budget added):

200 application/json
{
  "items": [
    {
      "id": 1,
      "title": "Budget"
    },
    {
      "id": 2,
      "title": "Roadmap"
    }
  ],
  "next_cursor": "eyJpZCI6Mn0.cuGm7m76S3bOizAsEbyVpHEsw-5bafeEGFHJ26VFq-E"
}
200 application/json
{
  "items": [
    {
      "id": 3,
      "title": "Hiring"
    }
  ]
}
400 application/problem+json
{
  "type": "https://github.com/whilesmartgo/apicontract/blob/main/docs/errors.md#malformed_query",
  "title": "The query string could not be parsed.",
  "status": 400,
  "code": "malformed_query",
  "errors": [
    {
      "in": "query",
      "name": "cursor",
      "code": "invalid_cursor",
      "detail": "is not a cursor issued for this query"
    }
  ]
}

next_cursor is absent on the last page. RequestBinding ties a cursor to the method, escaped path, query and caller it was issued for, so it fails on another route, another resource or another filter; limit may change between pages.

Read a day range in a time zone
var q struct {
	apicontract.Range
	apicontract.Zone
}
// GET /events?from=2026-11-14&to=2026-11-14&tz=Europe/Berlin
apicontract.BindQuery(r, &q)
fmt.Println(q.From.Format(time.RFC3339))
fmt.Println(q.To.Format(time.RFC3339))
2026-11-14T00:00:00+01:00
2026-11-15T00:00:00+01:00

A day in to covers that whole day, so the range ends at the start of the next day.

Query errors
type eventsList struct {
	apicontract.Page
	apicontract.Range
	PageSize int `query:"page_size" deprecated:"limit"`
}

GET /events?limit=ten, then GET /events?from=2026-11-15&to=2026-11-14&colour=red:

400 application/problem+json
{
  "type": "https://github.com/whilesmartgo/apicontract/blob/main/docs/errors.md#malformed_query",
  "title": "The query string could not be parsed.",
  "status": 400,
  "code": "malformed_query",
  "errors": [
    {
      "in": "query",
      "name": "limit",
      "code": "invalid",
      "detail": "must be an integer"
    }
  ]
}
422 application/problem+json
{
  "type": "https://github.com/whilesmartgo/apicontract/blob/main/docs/errors.md#invalid_query",
  "title": "The query string is not valid.",
  "status": 422,
  "code": "invalid_query",
  "errors": [
    {
      "in": "query",
      "name": "colour",
      "code": "unknown_field",
      "detail": "is not a parameter of this route"
    },
    {
      "in": "query",
      "name": "to",
      "code": "out_of_range",
      "detail": "must be after from"
    }
  ]
}

A declared value that cannot be parsed makes the response a 400 with the collected field errors. Otherwise rule violations, including undeclared parameters, return 422.

Keep an old parameter name working

page_size above is the old name for limit. GET /events?page_size=20, then GET /events?page_size=20&limit=30:

200 application/json
{
  "limit": 20
}
422 application/problem+json
{
  "type": "https://github.com/whilesmartgo/apicontract/blob/main/docs/errors.md#invalid_query",
  "title": "The query string is not valid.",
  "status": 422,
  "code": "invalid_query",
  "errors": [
    {
      "in": "query",
      "name": "page_size",
      "code": "conflict",
      "detail": "page_size and limit disagree; send only limit"
    }
  ]
}
Read a JSON body
type newEvent struct {
	Title     string    `json:"title" required:"true" maxLength:"200"`
	StartsAt  time.Time `json:"starts_at" required:"true"`
	Capacity  *int      `json:"capacity" minimum:"1"`
	Attendees []struct {
		Email string `json:"email" required:"true"`
	} `json:"attendees" maxItems:"50"`
}

func createEvent(w http.ResponseWriter, r *http.Request) {
	var body newEvent
	if err := apicontract.BindJSON(r, &body); err != nil {
		apicontract.WriteProblem(w, err)
		return
	}
	// save the event
	apicontract.WriteJSON(w, http.StatusCreated, body)
}

Three POST /events requests:

  1. {"title": "Planning", "starts_at": "2026-11-14T09:00:00+01:00", "attendees": [{"email": "ada@example.com"}]}
  2. {"starts_at": "2026-11-14T09:00:00", "capacity": 0, "attendees": [{"name": "Ada"}]}
  3. {"capacity": 0, "attendees": [{"name": "Ada"}]}
201 application/json
{
  "title": "Planning",
  "starts_at": "2026-11-14T09:00:00+01:00",
  "capacity": null,
  "attendees": [
    {
      "email": "ada@example.com"
    }
  ]
}
400 application/problem+json
{
  "type": "https://github.com/whilesmartgo/apicontract/blob/main/docs/errors.md#malformed_body",
  "title": "The request body could not be parsed.",
  "status": 400,
  "code": "malformed_body",
  "errors": [
    {
      "in": "body",
      "name": "title",
      "code": "required",
      "detail": "is required"
    },
    {
      "in": "body",
      "name": "starts_at",
      "code": "invalid",
      "detail": "must be an RFC 3339 timestamp with offset, such as 2026-11-14T09:00:00+01:00"
    },
    {
      "in": "body",
      "name": "capacity",
      "code": "out_of_range",
      "detail": "must be at least 1"
    },
    {
      "in": "body",
      "name": "attendees[0].name",
      "code": "unknown_field",
      "detail": "is not a field of this request"
    },
    {
      "in": "body",
      "name": "attendees[0].email",
      "code": "required",
      "detail": "is required"
    }
  ]
}
422 application/problem+json
{
  "type": "https://github.com/whilesmartgo/apicontract/blob/main/docs/errors.md#invalid_body",
  "title": "The request body is not valid.",
  "status": 422,
  "code": "invalid_body",
  "errors": [
    {
      "in": "body",
      "name": "title",
      "code": "required",
      "detail": "is required"
    },
    {
      "in": "body",
      "name": "starts_at",
      "code": "required",
      "detail": "is required"
    },
    {
      "in": "body",
      "name": "capacity",
      "code": "out_of_range",
      "detail": "must be at least 1"
    },
    {
      "in": "body",
      "name": "attendees[0].name",
      "code": "unknown_field",
      "detail": "is not a field of this request"
    },
    {
      "in": "body",
      "name": "attendees[0].email",
      "code": "required",
      "detail": "is required"
    }
  ]
}

The second request has a timestamp without an offset, which cannot be parsed, so it is a 400. The third parses, so the same rule breaks are a 422. Nested fields are named by their path, such as attendees[0].email. Optional pointers such as capacity, maps and free-form fields accept null, which clears the field; other fields reject it. Integer fields accept whole JSON numbers such as 100, 100.0 or 1e2, within signed 64-bit and parser exponent limits. Values must also fit the Go field type.

Bodies the parser refuses before reading fields

A form-encoded body, then a JSON object that repeats a key:

415 application/problem+json
{
  "type": "https://github.com/whilesmartgo/apicontract/blob/main/docs/errors.md#unsupported_media_type",
  "title": "The request body must be JSON.",
  "status": 415,
  "detail": "Send the body as application/json.",
  "code": "unsupported_media_type"
}
400 application/problem+json
{
  "type": "https://github.com/whilesmartgo/apicontract/blob/main/docs/errors.md#malformed_body",
  "title": "The request body could not be parsed.",
  "status": 400,
  "detail": "The request body is not valid JSON: duplicate key \"title\".",
  "code": "malformed_body"
}

The HTTP parser also accepts application subtypes ending in +json. A declared charset must be UTF-8. Bodies over 1 MiB get 413 with code body_too_large. Pass apicontract.MaxBytes(n) to change the limit. BindJSONBytes reads a JSON object you already hold, such as an MCP tool call's arguments, with the same limit and rules.

Check an idempotency key
key, err := apicontract.IdempotencyKey(r) // "" when the header is absent

With Idempotency-Key: short, err is written as:

{"type":"https://github.com/whilesmartgo/apicontract/blob/main/docs/errors.md#malformed_header","title":"A request header could not be parsed.","status":400,"code":"malformed_header","errors":[{"in":"header","name":"Idempotency-Key","code":"invalid","detail":"must be 8 to 128 characters"}]}

"8e03978e-40d5-43e8-bc93-6894a57f9324", with the quotes, and 8e03978e-40d5-43e8-bc93-6894a57f9324 both return the key without quotes. Two header fields or a comma-joined pair of keys are rejected. Commas inside a quoted key are allowed. Storing keys and replaying the first response is up to the app.

Describe a body for tools and specs

BodySchema describes what clients should send to BindJSON for a body struct. Use it for MCP tool input schemas. It includes the ranges of int8, int16 and int32 fields. It omits the full range of 64-bit fields because JavaScript numbers cannot represent those limits exactly. The parser still rejects values outside that range. Integer bounds round inward: maximum:"9.5" means 9. With clamp:"true", the schema keeps maximum as the limit clients should use. The parser also accepts larger values and caps them.

schema, _ := apicontract.BodySchema(newEvent{})
{
  "additionalProperties": false,
  "properties": {
    "attendees": {
      "items": {
        "additionalProperties": false,
        "properties": {
          "email": {
            "type": "string"
          }
        },
        "required": [
          "email"
        ],
        "type": "object"
      },
      "maxItems": 50,
      "type": "array"
    },
    "capacity": {
      "minimum": 1,
      "type": [
        "integer",
        "null"
      ]
    },
    "starts_at": {
      "format": "date-time",
      "type": "string"
    },
    "title": {
      "maxLength": 200,
      "type": "string"
    }
  },
  "required": [
    "title",
    "starts_at"
  ],
  "type": "object"
}

Tags the parsers read:

Tag Applies to Meaning
query:"name" query Parameter name. On a nested struct, a prefix: query:"updated" reads updated_from and updated_to.
json:"name" body Field name using encoding/json tag syntax. An omitted name uses the Go field name.
required:"true" both Must be present and not null. Query values must be nonblank. An old name with a value can satisfy its replacement; JSON Schemas express this alternative.
default:"value" both Used for absent optional fields. Blank query values count as absent. Body fields take defaults for strings, integers, numbers and booleans. A default must meet the field's rules, stay within its maximum even when it clamps, and fit its Go type, or binding fails with a programming error.
minimum, maximum integers, numbers Bounds. Add clamp:"true" to cap values above the maximum; values below the minimum are rejected.
maxLength, enum on a list each entry of a string list; named types such as type Tags []string are supported in bodies Maximum characters and allowed values per entry.
maxItems lists, sort Maximum items.
enum:"a,b" strings, string lists, sort Allowed values.
deprecated:"new_name" both An old name that fills new_name when that is absent. Both with different values is a conflict.
doc both Description in schemas.
bound:"end" query times A day means the end of that day.

Supported body types: strings, integers, floats, booleans, time.Time, apicontract.Date, structs, slices of these, pointers to these, map[string]any for any JSON object, and any or json.RawMessage for any JSON value. Free-form values keep numbers as json.Number, so large integers are not rounded.

Other describers:

  • InputSchema(query) returns the JSON Schema of a query struct.
  • OpenAPIParameters(query) and OpenAPIRequestBody(body) return OpenAPI 3.1 objects for specs built in code.
  • OpenAPIProblemResponse(status) returns an OpenAPI response with the problem body.
  • OpenAPIParametersOf and OpenAPIRequestBodyOf take []Field built from source types, for generators that read Go code.

Check an OpenAPI document

The apicontract command checks OpenAPI 3.0 and 3.1 JSON documents from any language. It checks GET, PUT, POST, PATCH, DELETE, HEAD, OPTIONS and TRACE operations and follows local references. Its schema checks read keywords beside a $ref and members of allOf together with the referenced schema. A document whose schemas are too large or too deeply composed to walk is reported as an error rather than partly checked. It does not resolve external references or validate the full OpenAPI specification.

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

On a document with a few common problems:

openapi.json: GET /notes: error-media-type: the 400 response must be application/problem+json
openapi.json: GET /notes: list-cursor: collections must accept an opaque cursor
openapi.json: GET /notes: list-envelope: collections must return {"items": [...], "next_cursor": "..."}
openapi.json: GET /notes: list-limit: collections must accept limit with maximum 200
openapi.json: GET /notes: param-legacy: query parameter "page" must be deprecated in favour of "cursor"
openapi.json: GET /notes: param-name: query parameter "updatedSince" must be snake_case
openapi.json: POST /notes: body-closed: request objects must set additionalProperties to false so unknown fields are rejected
openapi.json: POST /notes: body-time-format: body field "remind_at" must declare format date-time
1 document, 8 violations, 0 accepted by exceptions, 0 stale exceptions
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 required items property typed only as an array, directly or through allOf.
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 An operation with query parameters or a body declares none of 400, 422 or 4XX.
error-media-type A declared 4xx or 5xx response, including 4XX and 5XX, resolves to an object with no application/problem+json content.
body-name A JSON request body field, at any depth, is not snake_case.
body-time-format A JSON request body field ending in _at has no date-time format.
body-closed A JSON request body schema of type object with properties does not set additionalProperties: false.

A GET route is a collection when its 200 application/json schema, a schema it combines through allOf, or one of its anyOf or oneOf options is an array, or when it has an array in items or data, or when the route 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 or field. 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 query strings and JSON request bodies into typed structs, rejects input a route does not declare, writes the list envelope and RFC 9457 problem bodies, signs opaque cursors, and describes the same structs as JSON Schema and OpenAPI so specs and tool schemas match the parser.

Example (DayRange)
package main

import (
	"fmt"
	"net/http/httptest"
	"time"

	"github.com/whilesmartgo/apicontract"
)

func main() {
	var q struct {
		apicontract.Range
		apicontract.Zone
	}
	request := httptest.NewRequest("GET", "/events?from=2026-11-14&to=2026-11-14&tz=Europe/Berlin", nil)
	if err := apicontract.BindQuery(request, &q); err != nil {
		panic(err)
	}
	fmt.Println(q.From.Format(time.RFC3339))
	fmt.Println(q.To.Format(time.RFC3339))
}
Output:
2026-11-14T00:00:00+01:00
2026-11-15T00:00:00+01:00
Example (Paging)
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"

	"github.com/whilesmartgo/apicontract"
)

func serve(h http.Handler, method, target, body string) {
	request := httptest.NewRequest(method, target, strings.NewReader(body))
	if body != "" {
		request.Header.Set("Content-Type", "application/json")
	}
	recorder := httptest.NewRecorder()
	h.ServeHTTP(recorder, request)
	show(recorder)
}

func show(recorder *httptest.ResponseRecorder) {
	var indented bytes.Buffer
	body := bytes.TrimSpace(recorder.Body.Bytes())
	if err := json.Indent(&indented, body, "", "  "); err != nil {
		indented.Write(body)
	}
	fmt.Printf("%d %s\n%s\n", recorder.Code, recorder.Header().Get("Content-Type"), indented.String())
}

type note struct {
	ID    int    `json:"id"`
	Title string `json:"title"`
}

type notesList struct {
	apicontract.Page
	apicontract.Search
}

func listNotes(cursors *apicontract.Cursors, all []note) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var q notesList
		if err := apicontract.BindQuery(r, &q); err != nil {
			_ = apicontract.WriteProblem(w, err)
			return
		}
		binding := apicontract.RequestBinding(r, "user-1")
		var after struct {
			ID int `json:"id"`
		}
		if q.Cursor != "" {
			if err := cursors.Decode(q.Cursor, binding, &after); err != nil {
				_ = apicontract.WriteProblem(w, err)
				return
			}
		}
		start := after.ID
		end := min(start+q.Limit, len(all))
		next := ""
		if end < len(all) {
			next, _ = cursors.Encode(binding, map[string]int{"id": end})
		}
		_ = apicontract.WriteList(w, all[start:end], next)
	}
}

func main() {
	cursors, _ := apicontract.NewCursors([]byte("an example key of at least 32 bytes"))
	h := listNotes(cursors, []note{{1, "Budget"}, {2, "Roadmap"}, {3, "Hiring"}})

	serve(h, "GET", "/notes?limit=2", "")
	serve(h, "GET", "/notes?limit=2&cursor=eyJpZCI6Mn0.cuGm7m76S3bOizAsEbyVpHEsw-5bafeEGFHJ26VFq-E", "")
	serve(h, "GET", "/notes?limit=2&q=budget&cursor=eyJpZCI6Mn0.cuGm7m76S3bOizAsEbyVpHEsw-5bafeEGFHJ26VFq-E", "")
}
Output:
200 application/json
{
  "items": [
    {
      "id": 1,
      "title": "Budget"
    },
    {
      "id": 2,
      "title": "Roadmap"
    }
  ],
  "next_cursor": "eyJpZCI6Mn0.cuGm7m76S3bOizAsEbyVpHEsw-5bafeEGFHJ26VFq-E"
}
200 application/json
{
  "items": [
    {
      "id": 3,
      "title": "Hiring"
    }
  ]
}
400 application/problem+json
{
  "type": "https://github.com/whilesmartgo/apicontract/blob/main/docs/errors.md#malformed_query",
  "title": "The query string could not be parsed.",
  "status": 400,
  "code": "malformed_query",
  "errors": [
    {
      "in": "query",
      "name": "cursor",
      "code": "invalid_cursor",
      "detail": "is not a cursor issued for this query"
    }
  ]
}
Example (QueryErrors)
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"

	"github.com/whilesmartgo/apicontract"
)

func serve(h http.Handler, method, target, body string) {
	request := httptest.NewRequest(method, target, strings.NewReader(body))
	if body != "" {
		request.Header.Set("Content-Type", "application/json")
	}
	recorder := httptest.NewRecorder()
	h.ServeHTTP(recorder, request)
	show(recorder)
}

func show(recorder *httptest.ResponseRecorder) {
	var indented bytes.Buffer
	body := bytes.TrimSpace(recorder.Body.Bytes())
	if err := json.Indent(&indented, body, "", "  "); err != nil {
		indented.Write(body)
	}
	fmt.Printf("%d %s\n%s\n", recorder.Code, recorder.Header().Get("Content-Type"), indented.String())
}

type eventsList struct {
	apicontract.Page
	apicontract.Range
	PageSize int `query:"page_size" deprecated:"limit"`
}

func listEvents(w http.ResponseWriter, r *http.Request) {
	var q eventsList
	if err := apicontract.BindQuery(r, &q); err != nil {
		_ = apicontract.WriteProblem(w, err)
		return
	}
	_ = apicontract.WriteJSON(w, http.StatusOK, map[string]any{"limit": q.Limit})
}

func main() {
	h := http.HandlerFunc(listEvents)
	serve(h, "GET", "/events?limit=ten", "")
	serve(h, "GET", "/events?from=2026-11-15&to=2026-11-14&colour=red", "")
}
Output:
400 application/problem+json
{
  "type": "https://github.com/whilesmartgo/apicontract/blob/main/docs/errors.md#malformed_query",
  "title": "The query string could not be parsed.",
  "status": 400,
  "code": "malformed_query",
  "errors": [
    {
      "in": "query",
      "name": "limit",
      "code": "invalid",
      "detail": "must be an integer"
    }
  ]
}
422 application/problem+json
{
  "type": "https://github.com/whilesmartgo/apicontract/blob/main/docs/errors.md#invalid_query",
  "title": "The query string is not valid.",
  "status": 422,
  "code": "invalid_query",
  "errors": [
    {
      "in": "query",
      "name": "colour",
      "code": "unknown_field",
      "detail": "is not a parameter of this route"
    },
    {
      "in": "query",
      "name": "to",
      "code": "out_of_range",
      "detail": "must be after from"
    }
  ]
}
Example (RenamedParameter)
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"

	"github.com/whilesmartgo/apicontract"
)

func serve(h http.Handler, method, target, body string) {
	request := httptest.NewRequest(method, target, strings.NewReader(body))
	if body != "" {
		request.Header.Set("Content-Type", "application/json")
	}
	recorder := httptest.NewRecorder()
	h.ServeHTTP(recorder, request)
	show(recorder)
}

func show(recorder *httptest.ResponseRecorder) {
	var indented bytes.Buffer
	body := bytes.TrimSpace(recorder.Body.Bytes())
	if err := json.Indent(&indented, body, "", "  "); err != nil {
		indented.Write(body)
	}
	fmt.Printf("%d %s\n%s\n", recorder.Code, recorder.Header().Get("Content-Type"), indented.String())
}

type eventsList struct {
	apicontract.Page
	apicontract.Range
	PageSize int `query:"page_size" deprecated:"limit"`
}

func listEvents(w http.ResponseWriter, r *http.Request) {
	var q eventsList
	if err := apicontract.BindQuery(r, &q); err != nil {
		_ = apicontract.WriteProblem(w, err)
		return
	}
	_ = apicontract.WriteJSON(w, http.StatusOK, map[string]any{"limit": q.Limit})
}

func main() {
	h := http.HandlerFunc(listEvents)
	serve(h, "GET", "/events?page_size=20", "")
	serve(h, "GET", "/events?page_size=20&limit=30", "")
}
Output:
200 application/json
{
  "limit": 20
}
422 application/problem+json
{
  "type": "https://github.com/whilesmartgo/apicontract/blob/main/docs/errors.md#invalid_query",
  "title": "The query string is not valid.",
  "status": 422,
  "code": "invalid_query",
  "errors": [
    {
      "in": "query",
      "name": "page_size",
      "code": "conflict",
      "detail": "page_size and limit disagree; send only limit"
    }
  ]
}
Example (RequestBody)
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"
	"time"

	"github.com/whilesmartgo/apicontract"
)

func serve(h http.Handler, method, target, body string) {
	request := httptest.NewRequest(method, target, strings.NewReader(body))
	if body != "" {
		request.Header.Set("Content-Type", "application/json")
	}
	recorder := httptest.NewRecorder()
	h.ServeHTTP(recorder, request)
	show(recorder)
}

func show(recorder *httptest.ResponseRecorder) {
	var indented bytes.Buffer
	body := bytes.TrimSpace(recorder.Body.Bytes())
	if err := json.Indent(&indented, body, "", "  "); err != nil {
		indented.Write(body)
	}
	fmt.Printf("%d %s\n%s\n", recorder.Code, recorder.Header().Get("Content-Type"), indented.String())
}

type newEvent struct {
	Title     string    `json:"title" required:"true" maxLength:"200"`
	StartsAt  time.Time `json:"starts_at" required:"true"`
	Capacity  *int      `json:"capacity" minimum:"1"`
	Attendees []struct {
		Email string `json:"email" required:"true"`
	} `json:"attendees" maxItems:"50"`
}

func createEventHandler(w http.ResponseWriter, r *http.Request) {
	var body newEvent
	if err := apicontract.BindJSON(r, &body); err != nil {
		_ = apicontract.WriteProblem(w, err)
		return
	}
	_ = apicontract.WriteJSON(w, http.StatusCreated, body)
}

func main() {
	h := http.HandlerFunc(createEventHandler)
	serve(h, "POST", "/events", `{"title": "Planning", "starts_at": "2026-11-14T09:00:00+01:00", "attendees": [{"email": "ada@example.com"}]}`)
	serve(h, "POST", "/events", `{"starts_at": "2026-11-14T09:00:00", "capacity": 0, "attendees": [{"name": "Ada"}]}`)
	serve(h, "POST", "/events", `{"capacity": 0, "attendees": [{"name": "Ada"}]}`)
}
Output:
201 application/json
{
  "title": "Planning",
  "starts_at": "2026-11-14T09:00:00+01:00",
  "capacity": null,
  "attendees": [
    {
      "email": "ada@example.com"
    }
  ]
}
400 application/problem+json
{
  "type": "https://github.com/whilesmartgo/apicontract/blob/main/docs/errors.md#malformed_body",
  "title": "The request body could not be parsed.",
  "status": 400,
  "code": "malformed_body",
  "errors": [
    {
      "in": "body",
      "name": "title",
      "code": "required",
      "detail": "is required"
    },
    {
      "in": "body",
      "name": "starts_at",
      "code": "invalid",
      "detail": "must be an RFC 3339 timestamp with offset, such as 2026-11-14T09:00:00+01:00"
    },
    {
      "in": "body",
      "name": "capacity",
      "code": "out_of_range",
      "detail": "must be at least 1"
    },
    {
      "in": "body",
      "name": "attendees[0].name",
      "code": "unknown_field",
      "detail": "is not a field of this request"
    },
    {
      "in": "body",
      "name": "attendees[0].email",
      "code": "required",
      "detail": "is required"
    }
  ]
}
422 application/problem+json
{
  "type": "https://github.com/whilesmartgo/apicontract/blob/main/docs/errors.md#invalid_body",
  "title": "The request body is not valid.",
  "status": 422,
  "code": "invalid_body",
  "errors": [
    {
      "in": "body",
      "name": "title",
      "code": "required",
      "detail": "is required"
    },
    {
      "in": "body",
      "name": "starts_at",
      "code": "required",
      "detail": "is required"
    },
    {
      "in": "body",
      "name": "capacity",
      "code": "out_of_range",
      "detail": "must be at least 1"
    },
    {
      "in": "body",
      "name": "attendees[0].name",
      "code": "unknown_field",
      "detail": "is not a field of this request"
    },
    {
      "in": "body",
      "name": "attendees[0].email",
      "code": "required",
      "detail": "is required"
    }
  ]
}
Example (RequestBodyRejected)
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"
	"time"

	"github.com/whilesmartgo/apicontract"
)

func serve(h http.Handler, method, target, body string) {
	request := httptest.NewRequest(method, target, strings.NewReader(body))
	if body != "" {
		request.Header.Set("Content-Type", "application/json")
	}
	recorder := httptest.NewRecorder()
	h.ServeHTTP(recorder, request)
	show(recorder)
}

func show(recorder *httptest.ResponseRecorder) {
	var indented bytes.Buffer
	body := bytes.TrimSpace(recorder.Body.Bytes())
	if err := json.Indent(&indented, body, "", "  "); err != nil {
		indented.Write(body)
	}
	fmt.Printf("%d %s\n%s\n", recorder.Code, recorder.Header().Get("Content-Type"), indented.String())
}

type newEvent struct {
	Title     string    `json:"title" required:"true" maxLength:"200"`
	StartsAt  time.Time `json:"starts_at" required:"true"`
	Capacity  *int      `json:"capacity" minimum:"1"`
	Attendees []struct {
		Email string `json:"email" required:"true"`
	} `json:"attendees" maxItems:"50"`
}

func createEventHandler(w http.ResponseWriter, r *http.Request) {
	var body newEvent
	if err := apicontract.BindJSON(r, &body); err != nil {
		_ = apicontract.WriteProblem(w, err)
		return
	}
	_ = apicontract.WriteJSON(w, http.StatusCreated, body)
}

func main() {
	h := http.HandlerFunc(createEventHandler)
	request := httptest.NewRequest("POST", "/events", strings.NewReader("title=Planning"))
	request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	recorder := httptest.NewRecorder()
	h.ServeHTTP(recorder, request)
	show(recorder)

	serve(h, "POST", "/events", `{"title": "a", "title": "b"}`)
}
Output:
415 application/problem+json
{
  "type": "https://github.com/whilesmartgo/apicontract/blob/main/docs/errors.md#unsupported_media_type",
  "title": "The request body must be JSON.",
  "status": 415,
  "detail": "Send the body as application/json.",
  "code": "unsupported_media_type"
}
400 application/problem+json
{
  "type": "https://github.com/whilesmartgo/apicontract/blob/main/docs/errors.md#malformed_body",
  "title": "The request body could not be parsed.",
  "status": 400,
  "detail": "The request body is not valid JSON: duplicate key \"title\".",
  "code": "malformed_body"
}

Index

Examples

Constants

View Source
const (
	CodeMalformedQuery       = "malformed_query"
	CodeInvalidQuery         = "invalid_query"
	CodeMalformedBody        = "malformed_body"
	CodeInvalidBody          = "invalid_body"
	CodeUnsupportedMediaType = "unsupported_media_type"
	CodeBodyTooLarge         = "body_too_large"
	CodeMalformedHeader      = "malformed_header"
	CodeInternal             = "internal_error"
)

Problem codes written in Problem.Code.

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

Field error codes written in FieldError.Code.

View Source
const (
	InQuery  = "query"
	InBody   = "body"
	InHeader = "header"
)

Where a FieldError points, written in FieldError.In.

View Source
const (
	DefaultLimit    = 50
	MaxLimit        = 200
	MaxCursorLength = 2048
)
View Source
const DefaultMaxBodyBytes = 1 << 20

DefaultMaxBodyBytes is the request body size BindJSON accepts unless MaxBytes says otherwise.

View Source
const IdempotencyHeader = "Idempotency-Key"

IdempotencyHeader is the request header that carries an idempotency key.

View Source
const ProblemContentType = "application/problem+json"

ProblemContentType is the media type of every error response (RFC 9457).

View Source
const ProblemTypeBase = "https://github.com/whilesmartgo/apicontract/blob/main/docs/errors.md#"

ProblemTypeBase prefixes the type URI of the problems this package writes. Each code has a section in docs/errors.md.

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 BindJSON added in v0.1.1

func BindJSON(r *http.Request, dst any, options ...BodyOption) error

BindJSON reads the request's JSON body into dst, a pointer to a struct whose fields carry json tags and the same rule tags as query structs. It returns a *Problem with status 415 when the body is not JSON, 413 when it is larger than the limit, 400 when it cannot be parsed or a value has the wrong type, and 422 when a parsed value breaks a rule, including a field the struct does not declare. Any other error means dst is not a valid body struct.

func BindJSONBytes added in v0.1.1

func BindJSONBytes(data []byte, dst any, options ...BodyOption) error

BindJSONBytes parses a JSON object, such as a request body or a tool call's arguments, into dst, with the same size limit and rules as BindJSON.

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, including a parameter the struct does not declare. 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 BodySchema added in v0.1.1

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

BodySchema describes the body struct value v as a JSON Schema object, as BindJSON reads it. Use it for tool input schemas and request body schemas.

Example
package main

import (
	"encoding/json"
	"fmt"
	"time"

	"github.com/whilesmartgo/apicontract"
)

type newEvent struct {
	Title     string    `json:"title" required:"true" maxLength:"200"`
	StartsAt  time.Time `json:"starts_at" required:"true"`
	Capacity  *int      `json:"capacity" minimum:"1"`
	Attendees []struct {
		Email string `json:"email" required:"true"`
	} `json:"attendees" maxItems:"50"`
}

func main() {
	schema, _ := apicontract.BodySchema(newEvent{})
	data, _ := json.MarshalIndent(schema, "", "  ")
	fmt.Println(string(data))
}
Output:
{
  "additionalProperties": false,
  "properties": {
    "attendees": {
      "items": {
        "additionalProperties": false,
        "properties": {
          "email": {
            "type": "string"
          }
        },
        "required": [
          "email"
        ],
        "type": "object"
      },
      "maxItems": 50,
      "type": "array"
    },
    "capacity": {
      "minimum": 1,
      "type": [
        "integer",
        "null"
      ]
    },
    "starts_at": {
      "format": "date-time",
      "type": "string"
    },
    "title": {
      "maxLength": 200,
      "type": "string"
    }
  },
  "required": [
    "title",
    "starts_at"
  ],
  "type": "object"
}

func ErrorSchema added in v0.1.1

func ErrorSchema() map[string]any

ErrorSchema returns the JSON Schema of the problem body, as published in schema/error.json, without its $schema and $id keywords.

func IdempotencyKey added in v0.1.1

func IdempotencyKey(r *http.Request) (string, error)

IdempotencyKey returns the request's Idempotency-Key, or an empty string when the header is absent. The key is a Structured Field String as the IETF draft specifies, such as "8e03978e-40d5-43e8-bc93-6894a57f9324" with the quotes, or a bare key of visible ASCII without commas, quotes or backslashes. The decoded key must be 8 to 128 characters. A key sent more than once, in separate fields or joined by a comma, or one that cannot be parsed returns a *Problem with status 400. Storing keys and replaying responses is left to the app.

Example
package main

import (
	"encoding/json"
	"fmt"
	"net/http/httptest"

	"github.com/whilesmartgo/apicontract"
)

func main() {
	request := httptest.NewRequest("POST", "/events", nil)
	request.Header.Set("Idempotency-Key", "short")
	_, err := apicontract.IdempotencyKey(request)
	data, _ := json.Marshal(err)
	fmt.Println(string(data))
}
Output:
{"type":"https://github.com/whilesmartgo/apicontract/blob/main/docs/errors.md#malformed_header","title":"A request header could not be parsed.","status":400,"code":"malformed_header","errors":[{"in":"header","name":"Idempotency-Key","code":"invalid","detail":"must be 8 to 128 characters"}]}

func InputSchema

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

InputSchema describes the query 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 OpenAPIProblemResponse added in v0.1.1

func OpenAPIProblemResponse(status int) map[string]any

OpenAPIProblemResponse returns an OpenAPI response object for an error status, with the problem body under application/problem+json.

func OpenAPIRequestBody added in v0.1.1

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

OpenAPIRequestBody describes the body struct value v as an OpenAPI 3.1 request body object.

func OpenAPIRequestBodyOf added in v0.1.1

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

OpenAPIRequestBodyOf is OpenAPIRequestBody 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. Prefer RequestBinding, which also binds the route; QueryBinding alone lets a cursor from one route verify on another route with the same query and caller.

func RequestBinding added in v0.1.1

func RequestBinding(r *http.Request, principal ...string) string

RequestBinding returns a binding for a cursor from the request's method and path, the query values that shape the result, and the principal parts, such as user and owner IDs. A cursor bound this way is rejected on another route, on the same route for another resource, with another filter, or for another caller. 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, detail string, errors ...FieldError) error

WriteError writes a problem with status, code and detail.

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 a problem. Errors that are not a *Problem are written as a 500 without exposing their text.

Types

type BodyOption added in v0.1.1

type BodyOption func(*bodyConfig)

BodyOption configures BindJSON.

func MaxBytes added in v0.1.1

func MaxBytes(n int64) BodyOption

MaxBytes sets the largest body BindJSON and BindJSONBytes accept. It must be positive.

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. A Cursors not made by NewCursors returns a plain error, which WriteProblem reports as a 500.

func (*Cursors) Encode

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

Encode returns a cursor for position, bound to binding.

type Date added in v0.1.1

type Date struct {
	Year  int
	Month time.Month
	Day   int
}

Date is a calendar day with no time or zone, written as YYYY-MM-DD.

func DateOf added in v0.1.1

func DateOf(t time.Time) Date

DateOf returns the day of t in t's location.

func ParseDate added in v0.1.1

func ParseDate(value string) (Date, error)

ParseDate parses a YYYY-MM-DD day.

func (Date) In added in v0.1.1

func (d Date) In(location *time.Location) time.Time

In returns the start of the day in location.

func (Date) IsZero added in v0.1.1

func (d Date) IsZero() bool

IsZero reports whether d is the zero Date.

func (Date) MarshalJSON added in v0.1.1

func (d Date) MarshalJSON() ([]byte, error)

func (Date) String added in v0.1.1

func (d Date) String() string

func (*Date) UnmarshalJSON added in v0.1.1

func (d *Date) UnmarshalJSON(data []byte) error

type Field

type Field struct {
	Name      string
	Exported  bool
	Anonymous bool
	Type      FieldType
	Tag       reflect.StructTag
	// Pointer is true when the field is a pointer to Type. A pointer body
	// field accepts null.
	Pointer bool
	// Bits is the size of an integer or floating-point type, such as 8 for
	// int8. Zero means 64.
	Bits int
	// Range is true when the field's type is apicontract.Range.
	Range bool
	// Fields holds the nested fields when Type is FieldStruct.
	Fields []Field
	// Elem describes the element type when Type is FieldList.
	Elem *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 or OpenAPIRequestBodyOf, so they describe a struct exactly as BindQuery and BindJSON read it. Fields lists every field of the struct in order.

type FieldError

type FieldError struct {
	In     string `json:"in"`
	Name   string `json:"name"`
	Code   string `json:"code"`
	Detail string `json:"detail"`
}

FieldError is one input at fault. Name is the query parameter, the header, or the body field path as the client sent it, such as attendees[2].email.

type FieldType

type FieldType int

FieldType classifies a struct field for parameter and body description.

const (
	FieldOther FieldType = iota
	FieldString
	FieldInt
	FieldBool
	FieldTime
	FieldLocation
	FieldSort
	FieldStrings
	FieldStruct
	FieldNumber
	FieldDate
	FieldList
	FieldAny
	FieldObject
)

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 {
	Type   string       `json:"type,omitempty"`
	Title  string       `json:"title"`
	Status int          `json:"status"`
	Detail string       `json:"detail,omitempty"`
	Code   string       `json:"code"`
	Errors []FieldError `json:"errors,omitempty"`
}

Problem is an error that is written as an RFC 9457 problem details object. Code and Errors are extension members.

func NewProblem added in v0.1.1

func NewProblem(status int, code, detail string, errors ...FieldError) *Problem

NewProblem returns a problem with status and code. Codes defined by this package get their documented type and title; other codes get the status text as title and no type, which RFC 9457 reads as about:blank.

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