github danielgtaylor/huma v2.21.0

latest releases: v2.39.1, v2.39.0, v2.38.0...
2 years ago

Overview

Better Support for Default/Example in Custom Schemas

Fixes an issue where custom schemas could have values overwritten by the default instead of using the given value. For example:

type GreetingType int

func (*GreetingType) Schema(r huma.Registry) *huma.Schema {
	schema := &huma.Schema{
		Type:     huma.TypeInteger,
		Default:  10,
		Examples: []any{1},
	}
	return schema
}

Better Errors When Using Discriminators

OpenAPI supports using a discriminator field in schemas that use oneOf to determine which of the included schemas to validate against. Huma now uses this information to generate better error messages like expected required property color to be present instead of just saying it expected one of the schemas to match. Also handles problems with the discriminator type and value mapping. Example https://go.dev/play/p/5gkNczNJ_jK:

type Cat struct {
	Name string `json:"name" minLength:"2" maxLength:"10"`
	Kind string `json:"kind" enum:"cat"`
}

type Dog struct {
	Color string `json:"color" enum:"black,white,brown"`
	Kind  string `json:"kind" enum:"dog"`
}

type DogOrCat struct {
	Kind string `json:"kind" enum:"cat,dog"`
}

func (v DogOrCat) Schema(r huma.Registry) *huma.Schema {
	catSchema := r.Schema(reflect.TypeOf(Cat{}), true, "Cat")
	dogSchema := r.Schema(reflect.TypeOf(Dog{}), true, "Dog")

	return &huma.Schema{
		Type:        huma.TypeObject,
		Description: "Animal",
		OneOf: []*huma.Schema{
			{Ref: catSchema.Ref},
			{Ref: dogSchema.Ref},
		},
		Discriminator: &huma.Discriminator{
			PropertyName: "kind",
			Mapping: map[string]string{
				"cat": catSchema.Ref,
				"dog": dogSchema.Ref,
			},
		},
	}
}

// ...

huma.Put(api, "/demo", func(ctx context.Context, input *struct {
	Body DogOrCat
}) (*DemoResponse, error) {
	resp := &DemoResponse{}
	resp.Body.Message = "You sent a " + input.Body.Kind
	return resp, nil
})

What's Changed

Full Changelog: v2.20.0...v2.21.0

Don't miss a new huma release

NewReleases is sending notifications on new releases.