apispec

package
v0.46.0 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: Apache-2.0 Imports: 8 Imported by: 1 module, 0 packages

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.

Documentation

Overview

Package apispec discovers and projects the OpenAPI documents a Dynatrace environment publishes about itself.

Two conventions carry this package, and neither is a documented contract:

  • every platform API serves its specification at `<api-base-path>/openapi.yaml`, and
  • the environment publishes a machine-readable index of those documents at RegistryPath — the same `configUrl` the environment's own Swagger UI consumes.

They are stable, uniform, observed conventions. Because they are not guaranteed, every entry point here fails soft: a missing index is a typed *RegistryUnavailableError rather than a raw 404, and one unreadable document never invalidates the rest of a listing.

Raw specifications are far too large to hand to a caller verbatim — the largest observed is ~47k tokens for a single API — so the useful output is a projection: an operation index for choosing an operation, and one fully resolved operation for composing a call.

Index

Constants

View Source
const ClassicSpecFileName = "spec3.json"

ClassicSpecFileName is the classic environment API's specification filename. The `openapi.yaml` convention does not hold for the classic surface — it is a 404 there — so classic entries are recognised by this name instead.

View Source
const RegistryPath = "/platform/metadata/v1/swagger-ui.json"

RegistryPath is the environment's machine-readable index of published API specifications.

View Source
const SpecFileName = "openapi.yaml"

SpecFileName is the conventional specification filename under an API base path.

Variables

This section is empty.

Functions

func IsAbsoluteURL

func IsAbsoluteURL(s string) bool

IsAbsoluteURL reports whether s is an absolute URL rather than a path on the environment. Callers use it to reject a passthrough target that would leave the configured environment.

func MethodIsAlwaysMutating

func MethodIsAlwaysMutating(method string) bool

MethodIsAlwaysMutating reports whether a method cannot be a read whatever a specification claims. It is the lower bound the specification cannot lower.

func MethodIsRead

func MethodIsRead(method string) bool

MethodIsRead reports whether an HTTP method is conventionally a read.

This is a one-sided floor, never a classification: GET and HEAD are reads by convention, and PUT/PATCH/DELETE are never reads. POST carries no information at all and must never be inferred from — measured across 64 specified operations, 12 POSTs required only a `:read` scope while one required `:delete`, so method inference is wrong in both directions on POST, including the dangerous one.

func ScopeVerb

func ScopeVerb(scope string) string

ScopeVerb returns the trailing verb of a scope string, or "" when the scope is not in `<service>:<resource>:<verb>` form.

func SpecPathForBase

func SpecPathForBase(basePath string) string

SpecPathForBase returns the conventional specification path for an API base path.

Types

type Access

type Access string

Access is how much a scope verb permits. It is the specification-derived half of classifying a generic request; mapping it onto a safety operation is the caller's job, because that mapping is CLI policy rather than API knowledge.

const (
	// AccessRead permits reading only.
	AccessRead Access = "read"
	// AccessWrite permits creating or modifying.
	AccessWrite Access = "write"
	// AccessDelete permits deletion.
	AccessDelete Access = "delete"
	// AccessUnknown means the scope verb could not be classified — either no
	// scope was declared, or its verb is not in the table below.
	//
	// This is a first-class outcome, not an error case. It must never be
	// collapsed into AccessRead: a caller that treats "unknown" as "read" turns
	// every unclassifiable mutation into a permitted one.
	AccessUnknown Access = "unknown"
)

func AccessForScopes

func AccessForScopes(scopes []string) Access

AccessForScopes classifies a declared scope set.

The *most* permissive verb across the set decides, because a caller holding several scopes for one operation can exercise all of them, and the gate has to cover the strongest. An unclassifiable verb anywhere makes the whole set unknown — one unrecognised scope is enough to invalidate a conclusion drawn from the others.

An empty scope set is AccessUnknown: it means the document declared nothing, which is common (two of six APIs sampled declare no per-operation scopes) and is exactly the case that must not be mistaken for "harmless".

type Entry

type Entry struct {
	// Name is the registry's own display name, e.g. "Document Service".
	Name string `json:"name" yaml:"name"`
	// URL is the location of the specification document, usually a path relative
	// to the environment (e.g. "/platform/document/v1/openapi.yaml") but
	// occasionally absolute for documents hosted elsewhere.
	URL string `json:"url" yaml:"url"`
}

Entry is one API specification the environment's registry publishes.

func (Entry) BasePath

func (e Entry) BasePath() string

BasePath is the API base path the entry documents — the specification path with its filename removed, e.g. "/platform/document/v1". It is empty for external entries, whose base path is not on this environment.

func (Entry) Classic

func (e Entry) Classic() bool

Classic reports whether the entry is a classic environment-API document, which uses spec3.json rather than the openapi.yaml convention.

func (Entry) External

func (e Entry) External() bool

External reports whether the entry points at an absolute URL rather than a path on this environment. Such entries (classic UI links) are listed but never fetched: they are not reachable through the platform gateway with a platform token.

type Handler

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

Handler fetches and projects the specifications one environment publishes.

Parsed documents are memoized for the Handler's lifetime, which makes a drill-down (index, then one operation) cost a single fetch per API. The cache is deliberately in-memory only: a spec is tenant- and version-specific, and a cross-invocation disk cache would be host state outliving the request.

func NewHandler

func NewHandler(c *httpclient.Client) *Handler

NewHandler creates a specification handler bound to one environment.

func (*Handler) RawDocument

func (h *Handler) RawDocument(docPath string) ([]byte, error)

RawDocument returns a specification document exactly as served, without projecting it. It is deliberately independent of parsing: a document dtctl cannot parse is precisely the case where a caller wants the bytes. A document already fetched for its projection is served from memory rather than re-fetched.

func (*Handler) RawDocumentForEntry

func (h *Handler) RawDocumentForEntry(e Entry) ([]byte, error)

RawDocumentForEntry returns the unparsed document a registry entry points at.

func (*Handler) Registry

func (h *Handler) Registry() (*Registry, error)

Registry fetches the environment's specification index. It is one HTTP request, and the result is memoized.

func (*Handler) Spec

func (h *Handler) Spec(docPath string) (*Spec, error)

Spec fetches and parses the specification document at docPath, a path relative to the environment. Results are memoized per Handler.

func (*Handler) SpecForEntry

func (h *Handler) SpecForEntry(e Entry) (*Spec, error)

SpecForEntry fetches the document a registry entry points at. External entries are refused rather than fetched: they live on another host and are not reachable through the platform gateway with a platform token.

type MediaType

type MediaType struct {
	ContentType string `json:"content_type" yaml:"content_type"`
	Schema      any    `json:"schema,omitempty" yaml:"schema,omitempty"`
}

MediaType pairs a content type with its schema. The schema has its top-level $ref resolved — one hop, which is what makes it usable without the rest of the document, and is where resolution deliberately stops.

type Operation

type Operation struct {
	Method      string `json:"method" yaml:"method"`
	Path        string `json:"path" yaml:"path"`
	OperationID string `json:"operation_id,omitempty" yaml:"operation_id,omitempty"`
	Summary     string `json:"summary,omitempty" yaml:"summary,omitempty"`
	Description string `json:"description,omitempty" yaml:"description,omitempty"`
	Deprecated  bool   `json:"deprecated,omitempty" yaml:"deprecated,omitempty"`
	// Scopes are the scopes the document declares for this operation. Empty means
	// the document declares none — which is common and must not be read as "no
	// scope required": two of six APIs sampled declare no per-operation scopes at
	// all, and one declares an explicitly empty list.
	Scopes      []string     `json:"scopes,omitempty" yaml:"scopes,omitempty"`
	Parameters  []Parameter  `json:"parameters,omitempty" yaml:"parameters,omitempty"`
	RequestBody *RequestBody `json:"request_body,omitempty" yaml:"request_body,omitempty"`
	Responses   []Response   `json:"responses,omitempty" yaml:"responses,omitempty"`
}

Operation is one path+method pair, projected to what a caller needs to choose it (identity, summary, scope) and to compose it (parameters, bodies).

func (Operation) Access

func (o Operation) Access() Access

Access classifies the operation from the scopes its specification declares.

func (Operation) ID

func (o Operation) ID() string

ID is the operation's stable human-facing identity, "METHOD /path". It is what `describe api --operation` accepts and what an operation index lists.

type Parameter

type Parameter struct {
	Name        string `json:"name" yaml:"name"`
	In          string `json:"in" yaml:"in"`
	Required    bool   `json:"required,omitempty" yaml:"required,omitempty"`
	Type        string `json:"type,omitempty" yaml:"type,omitempty"`
	Description string `json:"description,omitempty" yaml:"description,omitempty"`
	// Schema is the parameter's schema with a top-level $ref resolved, present
	// when it carries more than a scalar type.
	Schema any `json:"schema,omitempty" yaml:"schema,omitempty"`
}

Parameter is one path, query, header or cookie parameter.

type Registry

type Registry struct {
	Entries []Entry
}

Registry is the environment's index of published specifications, in the order the environment returned them.

func (*Registry) Candidates

func (r *Registry) Candidates(query string) []Entry

Candidates returns every entry whose name or base path contains query, case-insensitively. It backs a caller's disambiguation message and, like Registry.FindEntry, never looks beyond what the registry returned.

func (*Registry) EntryForPath

func (r *Registry) EntryForPath(requestPath string) (*Entry, bool)

EntryForPath returns the registry entry whose base path is the longest prefix of requestPath — the API that owns a given request. The longest prefix wins so that a nested base path is preferred over the shorter one it sits under.

func (*Registry) FindEntry

func (r *Registry) FindEntry(query string) (*Entry, bool)

FindEntry resolves a name or base path to a registry entry, matching only against what the registry actually returned.

Resolution order: exact base path, then exact (case-insensitive) name, then a case-insensitive substring of the name or base path. A miss returns (nil, false) — callers must never synthesize a candidate path from a name, which would turn dtctl into a prober that confirms the existence of APIs an environment deliberately omits from its own index.

type RegistryUnavailableError

type RegistryUnavailableError struct {
	Path string
	// StatusCode is the HTTP status, or 0 when the request never completed or
	// failed after a successful response (a body that would not parse).
	StatusCode int
	Err        error
}

RegistryUnavailableError reports that the environment's API index could not be read. It is a distinct type because it is an expected outcome, not a bug: the index is an observed convention, so a caller should explain it and name the Swagger UI as the fallback — never surface a raw response body.

func (*RegistryUnavailableError) Error

func (e *RegistryUnavailableError) Error() string

Error distinguishes "not published" from "refused", because they call for opposite responses from the caller.

Reporting a 401 as "this environment publishes no API index" is a statement about the environment made from evidence about the credential, and it sends someone to check the wrong thing entirely. Only a 404 licenses that claim.

func (*RegistryUnavailableError) Unwrap

func (e *RegistryUnavailableError) Unwrap() error

type RequestBody

type RequestBody struct {
	Required bool        `json:"required,omitempty" yaml:"required,omitempty"`
	Contents []MediaType `json:"contents,omitempty" yaml:"contents,omitempty"`
}

RequestBody is an operation's request body across its media types.

type Response

type Response struct {
	Status      string      `json:"status" yaml:"status"`
	Description string      `json:"description,omitempty" yaml:"description,omitempty"`
	Contents    []MediaType `json:"contents,omitempty" yaml:"contents,omitempty"`
}

Response is one documented response status.

type Spec

type Spec struct {
	// Title, Version, Category and Summary come from `info` — Category and
	// Summary from the `x-service-category` and `x-summary` extensions, which
	// make an API's grouping machine-readable.
	Title    string
	Version  string
	Category string
	Summary  string
	// BasePath is the API's gateway-relative base path, taken from
	// `servers[0].x-api-gateway-url` where present.
	BasePath string
	// Operations are in document order.
	Operations []Operation
	// Raw is the document exactly as served.
	Raw []byte
	// contains filtered or unexported fields
}

Spec is the projection of one OpenAPI document: its identity, its base path, and its operations. The original bytes are retained so a caller that explicitly asks for the raw document does not have to fetch it twice.

func ParseSpec

func ParseSpec(body []byte) (*Spec, error)

ParseSpec projects an OpenAPI document. The input is always parsed as YAML: JSON is a subset, so this handles the classic `spec3.json` documents and every observed Content-Type variant with one code path.

func (*Spec) Find

func (s *Spec) Find(method, templatePath string) (*Operation, bool)

Find returns the operation with the given method and exact template path.

func (*Spec) FindByID

func (s *Spec) FindByID(id string) (*Operation, bool)

FindByID returns the operation whose Operation.ID matches id ("METHOD /path"), case-insensitively on the method. A bare path with no method matches when exactly one operation has that path.

func (*Spec) Match

func (s *Spec) Match(method, requestPath string) (*Operation, bool)

Match resolves a concrete request path to the operation that serves it. The request path may be absolute (including the API base path) or already relative to it.

When several templates match, the one with the fewest placeholders wins, so a literal path beats a templated one (`/documents/search` over `/documents/{id}`).

type SpecUnavailableError

type SpecUnavailableError struct {
	DocPath string
	// StatusCode is the HTTP status, or 0 when the request never completed.
	StatusCode int
	Err        error
}

SpecUnavailableError reports that a document the index listed could not be fetched.

It is typed, and carries the status, because "the index lists it but you cannot read it" is an ordinary property of an environment rather than a bug: a listed document may 404, and an environment may serve its specifications only to an interactive session, in which case an authenticated token gets a 403 whose body talks about SSO and explains nothing. The status is what lets a caller say something useful instead of forwarding that.

func (*SpecUnavailableError) Error

func (e *SpecUnavailableError) Error() string

func (*SpecUnavailableError) Unwrap

func (e *SpecUnavailableError) Unwrap() error

Jump to

Keyboard shortcuts

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