📖 9 min read (~ 1800 words).

Examples & defaults

Example values and defaults are documentation that travels with the schema: an example: shows a caller what a value looks like, a default: declares what the field is when the caller omits it. Both are typed to the field — a numeric default on an integer field is a JSON number, not a string. The panes below pair the annotated Go with the fragment the scanner emits, from the test-covered docs/examples/concepts/examples package.

For the exact value shapes these keywords accept, see Keywords.

example

example: <value> attaches an example to the property, coerced to the field’s type — Hello, world! stays a string, 3 becomes a number.

Annotated Go
// Greeting carries an example value for documentation.
//
// swagger:model
type Greeting struct {
	// Message is the greeting text.
	//
	// example: Hello, world!
	Message string `json:"message"`

	// Count is how many times to repeat it.
	//
	// example: 3
	Count int32 `json:"count"`
}

Full source: docs/examples/concepts/examples/examples.go

{
  "type": "object",
  "title": "Greeting carries an example value for documentation.",
  "properties": {
    "count": {
      "description": "Count is how many times to repeat it.",
      "type": "integer",
      "format": "int32",
      "x-go-name": "Count",
      "example": 3
    },
    "message": {
      "description": "Message is the greeting text.",
      "type": "string",
      "x-go-name": "Message",
      "example": "Hello, world!"
    }
  },
  "x-go-package": "github.com/go-openapi/codescan/docs/examples/concepts/examples"
}

Full source: docs/examples/concepts/examples/testdata/example.json

The value is not limited to scalars. A JSON literal is parsed into a structured example — a { … } object on a map field, a [ … ] array on a slice field. A bare comma-separated list (example: a,b) is not split; it is kept verbatim as a string, so write example: ["a","b"] when you need an array.

On a plain string field a surrounding pair of double quotes is treated as delimiters and stripped — so example: "Foo" yields Foo, and example: "" sets an empty string (the same applies to default:). Bare values keep their text as-is.

Annotated Go
// Profile carries structured (non-scalar) example values. A JSON object literal
// on a map field and a JSON array literal on a slice field are parsed into
// structured examples — a bare comma-separated list would instead be kept
// verbatim as a string.
//
// swagger:model
type Profile struct {
	// Labels is a set of key/value labels.
	//
	// example: {"env":"prod","tier":"gold"}
	Labels map[string]string `json:"labels"`

	// Roles is the list of assigned roles.
	//
	// example: ["admin","auditor"]
	Roles []string `json:"roles"`
}

Full source: docs/examples/concepts/examples/examples.go

#/definitions/Profile
{
  "description": "Profile carries structured (non-scalar) example values. A JSON object literal\non a map field and a JSON array literal on a slice field are parsed into\nstructured examples — a bare comma-separated list would instead be kept\nverbatim as a string.",
  "type": "object",
  "properties": {
    "labels": {
      "description": "Labels is a set of key/value labels.",
      "type": "object",
      "additionalProperties": {
        "type": "string"
      },
      "x-go-name": "Labels",
      "example": {
        "env": "prod",
        "tier": "gold"
      }
    },
    "roles": {
      "description": "Roles is the list of assigned roles.",
      "type": "array",
      "items": {
        "type": "string"
      },
      "x-go-name": "Roles",
      "example": [
        "admin",
        "auditor"
      ]
    }
  },
  "x-go-package": "github.com/go-openapi/codescan/docs/examples/concepts/examples"
}

Full source: docs/examples/concepts/examples/testdata/complexexample.json

default

default: <value> sets the property’s default, again typed to the field — 8080 is a number, false a boolean, auto a string.

Annotated Go
// Settings carries default values applied when a field is omitted.
//
// swagger:model
type Settings struct {
	// Port is the listen port.
	//
	// default: 8080
	Port int32 `json:"port"`

	// Mode is the run mode.
	//
	// default: auto
	Mode string `json:"mode"`

	// Verbose toggles verbose logging.
	//
	// default: false
	Verbose bool `json:"verbose"`
}

Full source: docs/examples/concepts/examples/examples.go

#/definitions/Settings
{
  "type": "object",
  "title": "Settings carries default values applied when a field is omitted.",
  "properties": {
    "mode": {
      "description": "Mode is the run mode.",
      "type": "string",
      "default": "auto",
      "x-go-name": "Mode"
    },
    "port": {
      "description": "Port is the listen port.",
      "type": "integer",
      "format": "int32",
      "default": 8080,
      "x-go-name": "Port"
    },
    "verbose": {
      "description": "Verbose toggles verbose logging.",
      "type": "boolean",
      "default": false,
      "x-go-name": "Verbose"
    }
  },
  "x-go-package": "github.com/go-openapi/codescan/docs/examples/concepts/examples"
}

Full source: docs/examples/concepts/examples/testdata/default.json

swagger:default

swagger:default is a narrow, value-only classifier hint placed on a var or const. It does not publish a spec entity of its own — it has no standalone output — so most spec defaults are carried by the default: keyword above rather than this annotation.

// DefaultPort is the fallback port used wherever Port is not supplied. The
// swagger:default annotation is a narrow value-only discovery hint.
//
// swagger:default
var DefaultPort = 8080

Full source: docs/examples/concepts/examples/examples.go

On a defined-type field

When a field’s type is a named (defined) type, it renders as a $ref to that type’s definition — and a $ref cannot carry sibling keywords. An example: or default: on such a field is therefore preserved on the override arm of an allOf compound, so the value still reaches the spec.

Annotated Go
// Currency is a named (defined) string type, so it earns its own definition and
// a field typed Currency renders as a $ref. A $ref cannot carry sibling
// keywords, so an example or default on such a field rides the override arm of
// an allOf compound — the value still reaches the spec.
//
// swagger:model
type Currency string

// Price shows example + default on a defined-type field.
//
// swagger:model
type Price struct {
	// Unit is the ISO currency code.
	//
	// default: USD
	// example: EUR
	Unit Currency `json:"unit"`
}

Full source: docs/examples/concepts/examples/examples.go

#/definitions/Price
{
  "type": "object",
  "title": "Price shows example + default on a defined-type field.",
  "properties": {
    "unit": {
      "description": "Unit is the ISO currency code.",
      "allOf": [
        {
          "$ref": "#/definitions/Currency"
        },
        {
          "default": "USD",
          "example": "EUR"
        }
      ],
      "x-go-name": "Unit"
    }
  },
  "x-go-package": "github.com/go-openapi/codescan/docs/examples/concepts/examples"
}

Full source: docs/examples/concepts/examples/testdata/reffield.json

A JSON object or array literal on a $ref’d field is coerced into a structured value on that override arm — exactly as it is on a plain field — so the example reads as real JSON, not an escaped string. A bare scalar is the exception: on the override arm the referenced type is unknown, so a scalar stays a string rather than being silently retyped.

Annotated Go
// Coordinates is a defined struct, so a field typed Coordinates renders as a
// $ref.
//
// swagger:model
type Coordinates struct {
	// Lat is the latitude.
	Lat float64 `json:"lat"`

	// Lng is the longitude.
	Lng float64 `json:"lng"`
}

// Place shows a JSON-object example on a $ref'd field. Because the field is a
// $ref, the example rides the override arm of the allOf — and a JSON object (or
// array) literal is coerced into a structured value there, exactly as it is on a
// plain field. A bare scalar would instead stay a string, since the referenced
// type is not known on the override arm.
//
// swagger:model
type Place struct {
	// At is the location.
	//
	// example: {"lat":48.85,"lng":2.35}
	At Coordinates `json:"at"`
}

Full source: docs/examples/concepts/examples/examples.go

#/definitions/Place
{
  "description": "Place shows a JSON-object example on a $ref'd field. Because the field is a\n$ref, the example rides the override arm of the allOf — and a JSON object (or\narray) literal is coerced into a structured value there, exactly as it is on a\nplain field. A bare scalar would instead stay a string, since the referenced\ntype is not known on the override arm.",
  "type": "object",
  "properties": {
    "at": {
      "description": "At is the location.",
      "allOf": [
        {
          "$ref": "#/definitions/Coordinates"
        },
        {
          "example": {
            "lat": 48.85,
            "lng": 2.35
          }
        }
      ],
      "x-go-name": "At"
    }
  },
  "x-go-package": "github.com/go-openapi/codescan/docs/examples/concepts/examples"
}

Full source: docs/examples/concepts/examples/testdata/refstructured.json

On a response body

example: is not limited to model fields. On a swagger:response whose body is a top-level array (or other non-struct) type, the example lands on the response body schema:

Annotated Go
// NTPServers is a top-level array response carrying an example. The example
// lands on the response body schema rather than being dropped.
//
// swagger:response ntpServers
// example: ["10.0.0.1","10.0.0.2"]
type NTPServers []string

// swagger:route GET /ntp ntp listNTP
//
// responses:
//
//	200: ntpServers


// Pet is the response payload.
//
// swagger:model Pet
type Pet struct {
	Name string `json:"name"`
}

// PetResponse returns a pet, with one example payload per media type.
//
// The plural `examples:` keyword on a struct swagger:response is a YAML map
// keyed by media type, populating the OpenAPI response `examples` object.
//
// swagger:response petResponse
//
// examples:
//
//	application/json:
//	  name: Fluffy
//	application/xml: "<pet><name>Fluffy</name></pet>"
type PetResponse struct {
	// in: body
	Body Pet `json:"body"`
}

// swagger:route GET /pets pets listPets
//
// responses:
//
//	200: petResponse

Full source: docs/examples/concepts/examples/examples.go

responses[ntpServers]
{
  "description": "NTPServers is a top-level array response carrying an example. The example\nlands on the response body schema rather than being dropped.",
  "schema": {
    "type": "array",
    "items": {
      "type": "string"
    },
    "example": [
      "10.0.0.1",
      "10.0.0.2"
    ]
  }
}

Full source: docs/examples/concepts/examples/testdata/responseexample.json

Response examples by media type

A response can carry an examples: map keyed by media type — these populate the OpenAPI response examples object, one example payload per content type. Both annotation styles support it.

In a swagger:operation YAML body, examples: sits under the response code:

// swagger:operation GET /status status getStatus
//
// ---
// responses:
//   '200':
//     description: Success
//     examples:
//       application/json:
//         hello: world

On a struct-based swagger:response, the same examples: block lives in the declaration comment (the plural examples: is the response keyword; the singular example: above is the schema decorator) and produces the same response examples object:

Annotated Go
// Pet is the response payload.
//
// swagger:model Pet
type Pet struct {
	Name string `json:"name"`
}

// PetResponse returns a pet, with one example payload per media type.
//
// The plural `examples:` keyword on a struct swagger:response is a YAML map
// keyed by media type, populating the OpenAPI response `examples` object.
//
// swagger:response petResponse
//
// examples:
//
//	application/json:
//	  name: Fluffy
//	application/xml: "<pet><name>Fluffy</name></pet>"
type PetResponse struct {
	// in: body
	Body Pet `json:"body"`
}

// swagger:route GET /pets pets listPets
//
// responses:
//
//	200: petResponse

Full source: docs/examples/concepts/examples/examples.go

responses[petResponse]
{
  "description": "PetResponse returns a pet, with one example payload per media type.\n\nThe plural `examples:` keyword on a struct swagger:response is a YAML map\nkeyed by media type, populating the OpenAPI response `examples` object.",
  "schema": {
    "$ref": "#/definitions/Pet"
  },
  "examples": {
    "application/json": {
      "name": "Fluffy"
    },
    "application/xml": "\u003cpet\u003e\u003cname\u003eFluffy\u003c/name\u003e\u003c/pet\u003e"
  }
}

Full source: docs/examples/concepts/examples/testdata/responseexamplesbymime.json

Because the example lives on the response, one shared model can carry a different example per response code and per operation — a 200 and a 404 that both return the same error model each show their own illustrative payload, with no need for a distinct struct per case.

What’s next