JSON Schema & Registry
JSON Schema#
Using the default Huma config (or manually via the huma.SchemaLinkTransformer
), each resource operation returns a describedby
HTTP link relation header which references a JSON-Schema file. These schemas use the config.SchemasPath
to serve their content. For example:
Object resources (i.e. not arrays or simple scalars) can also optionally return a $schema
property with such a link, which enables the described-by relationship to outlive the HTTP request (i.e. saving the body to a file for later editing) and enables some editors like VSCode to provide code completion and validation as you type.
{
"$schema": "http://localhost:8888/schemas/Note.json",
"title": "I am a note title",
"contents": "Example note contents",
"labels": ["todo"]
}
Operations which accept objects as input will ignore the $schema
property, so it is safe to submit back to the API, aka "round-trip" the data.
Editing
The $schema
field is incredibly powerful when paired with Restish's edit command, giving you a quick and easy way to edit strongly-typed resources in your favorite editor.
Schema Registry#
Huma uses a customizable registry to keep track of all the schemas that have been generated from Go structs. This is used to avoid generating the same schema multiple times, and to provide a way to reference schemas by name for OpenAPI operations & hosted JSON Schemas.
The default schema implementation uses a map
to store schemas by name,generated from the Go type name without the package name. This supports recursive schemas and generates simple names like Thing
or ThingList
.
Schema Names
Note that by design the default registry does not support multiple models with the same name in different packages. For example, adding both foo.Thing
and bar.Thing
will result in a conflict. You can work around this by defining a new type like type BarThing bar.Thing
and using that instead, or using a custom registry naming function.
Custom Registry#
You can create your own registry with custom behavior by implementing the huma.Registry
interface and setting it on config.OpenAPI.Components.Schemas
when creating your API.
Dive Deeper#
- Reference
huma.Schema
is a JSON Schemahuma.Registry
generates & stores JSON Schemashuma.DefaultSchemaNamer
names schemas from typeshuma.Config
the API confighuma.DefaultConfig
the default API confighuma.OpenAPI
the OpenAPI spechuma.Components
contains theSchemas
registry
- External Links
- See Also
- Model Validation utility to validate custom JSON objects