Skip to content

Releases: danielgtaylor/huma

v2.18.0

03 Jun 16:35
158b076
Compare
Choose a tag to compare

Overview

Better Multipart Files Uploads

You can now use huma.MultipartFormFiles[YourType] as the request's RawBody in order to handle multipart file uploads. Files can be limited to specific content types and required or optional. Example:

type FileData struct {
        // This is an example, any number of `multipart.File` fields can be defined.
        // Nested structs are not supported.
	SomeFile multipart.File   `form-data:"some_file" content-type:"image/png" required:"true"`
	SeveralFiles []multipart.File `form-data:"several_files" content-type:"image/png,image/jpeg" required:"true"`
}

type FileHandlerInput struct {
	RawBody huma.MultipartFormFiles[FileData]
}

func FileHandler(ctx context.Context, input *FileHandlerInput) (*struct{}, error) {
  fileData := input.RawBody.Data()
  DoSomeThingWith(fileData.SomeFile)
  OrSomethingElseWith(fileData.SeveralFiles)
}

huma.Register(api,
  huma.Operation{
	  Path:             "/handle-files",
	  Method:        http.MethodPost,
	  OperationID:     "Handle files",
  }, FileHandler)

Schema Transformers

It's now possible to have types implement a schema transformer, which lets them modify the generated schema for the type. This option lives in between using the generated types and providing your own schema, and makes it a bit easier to modify the generated schema by not needing you to call into the registry manually. This is the interface:

type SchemaTransformer interface {
	TransformSchema(r Registry, s *Schema) *Schema
}

Simple example:

type MyInput struct {
	Field string `json:"field"`
}

func (i *MyInput) TransformSchema(r huma.Registry, s *huma.Schema) *huma.Schema {
	s.Description = "I am an override"
	return s
}

What's Changed

  • Fix typo in SSE doc by @op-tmplt in #448
  • Feature: handling files from multipart/form-data request by @lsdch in #415
  • feat: allow modifying generated schema by implementing SchemaTransformer interface by @lsdch in #456
  • fix: type schema description not work by @fourcels in #462

New Contributors

Full Changelog: v2.17.0...v2.18.0

v2.17.0

20 May 17:10
b318810
Compare
Choose a tag to compare

Overview

Convenience Method Operation Modifiers

You can now add modifier functions when registering operations using convenience methods like huma.Get:

func OperationTags(tags ...string) func(o *Operation) {
	return func(o *Operation) {
		o.Tags = tags
	}
}

huma.Get(api, "/demo", myHandler, OperationTags("one", "two"))

Use this to build out whatever functionality you need to simplify registration. These can also be composed & joined easily to give a concise way to register operations without falling back to huma.Register directly.

Request Remote Address Access

It's now possible to access the requests's RemoteAddr field through huma.Context for use in middleware and/or resolvers, which works with all routers:

func MyMiddleware(ctx huma.Context, next func(huma.Context)) {
	fmt.Println("Request address", ctx.RemoteAddr())
	next(ctx)
}

Fix Unmarshaling of Embedded Body

Unmarshaling of embedded structs with a body field now works as expected:

type BodyContainer struct {
	Body struct {
		Name string `json:"name"`
	}
}

huma.Register(api, huma.Operation{
	Method: http.MethodPost,
	Path:   "/body",
}, func(ctx context.Context, input *struct {
	BodyContainer
}) (*struct{}, error) {
	// Do something with `input.Body.Name`...
	return nil, nil
})

What's Changed

New Contributors

Full Changelog: v2.16.0...v2.17.0

v2.16.0

06 May 15:56
1796483
Compare
Choose a tag to compare

Overview

Drop Deprecated Chi v4 Adapter

This release drops Chi v4 support. Chi v4 has been deprecated & replaced with Chi v5 since 2021, and was included to help migrate from Huma v1 to v2. Huma v2 has now been out for about six months. Keeping Chi v4 in the main package results in extra dependencies and deprecation warnings from automated tools like dependabot. It is highly recommended to discontinue using Chi v4.

If you wish to continue using Chi v4, please copy the v4 adapter from https://github.com/danielgtaylor/huma/blob/v2.15.0/adapters/humachi/humachi.go into your own project. With that simple change you can migrate off at your own pace while continuing to get new Huma releases.

Better Panics

Some panic messages have been improved to be more helpful for users, for example letting them know that the response type must be a struct rather than some confusing reflection panic.

What's Changed

Full Changelog: v2.15.0...v2.16.0

v2.15.0

29 Apr 15:48
3abb70d
Compare
Choose a tag to compare

Sponsors

A big thank you to our new sponsor:

Overview

Schema Discriminator Support

Basic support for the OpenAPI 3.1 discriminator which gives hints to clients that the value of a field defines the type of the response. This is not currently exposed via tags but can be used when manually creating schemas:

s := &huma.Schema{
	OneOf: []*huma.Schema{
		{Type: "object", Properties: map[string]*huma.Schema{
			"type": {Type: "string", Enum: []any{"foo"}},
			"foo":  {Type: "string"},
		}},
		{Type: "object", Properties: map[string]*huma.Schema{
			"type": {Type: "string", Enum: []any{"bar"}},
			"bar":  {Type: "string"},
		}},
	},
	Discriminator: &huma.Discriminator{
		PropertyName: "type",
		Mapping: map[string]string{
			"foo": "#/components/schemas/Foo",
			"bar": "#/components/schemas/Bar",
		},
	},
}

Anonymous Struct Name Hints

Allow providing name hints via field tags for anonymous structs defined inline. This gives a bit more control over the JSON Schema type names:

type EndpointInput struct {
  Body struct {
    SomeData string `json:"some_data"`
  } `name-hint:"SomeName"`
}

Better File Upload UI Support

A contentMediaType field is generated for fields which are format: "binary" which enables a better UI for uploading files in the generated docs.

file upload in docs

Bug Fixes

The generated $schema field now uses http instead of https when the host is 127.0.0.1. Previously this was only the case for localhost.

Pointer types with custom schemas are now better supported by dereferencing the pointer to the underlying type before checking for the custom schema interface implementation.

The built-in Flow router has a fix applied to handle path params that are percent encoded with slashes. Fix has also been submitted upstream.

Fixed a possible panic in the schema link transformer when passed nil body types.

Updated the precondition error locations to match the rest of the project. request.headers.If-Matchheaders.If-Match as we no longer explicitly state it's in the request. It's always in the request.

Fixed an example in the docs that was resulting in an error due to a typo.

What's Changed

New Contributors

Full Changelog: v2.14.0...v2.15.0

v2.14.0

22 Apr 16:05
be8cf67
Compare
Choose a tag to compare

Overview

Support for netip.Addr Type

In addition to a net.IP, request inputs can now use a netip.Addr type, passing in a value like 127.0.0.1 from the client in e.g. query params and it will parse into the correct type with validation.

Error Wrapping Improvements

Arbitrary headers can now be added if needed by wrapping errors. For example:

return nil, huma.ErrorWithHeaders(
	huma.Error404NotFound("thing not found"),
	http.Header{
		"Cache-Control": {"no-store"},
	},
)

This uses Go's built-in error wrapping functionality and works via errors.Is/errors.As for any error which satisfies the huma.HeadersError interface.

What's Changed

New Contributors

Full Changelog: v2.13.1...v2.14.0

v2.13.1

19 Apr 05:19
e66ddf3
Compare
Choose a tag to compare

Overview

This patch release fixes a small bug where a 204 No Content or 304 Not Modified which included a body would result in a panic. After this fix the body is ignored, making it easier to use the huma.Status304NotModified() utility.

What's Changed

New Contributors

Full Changelog: v2.13.0...v2.13.1

v2.13.0

15 Apr 05:16
00fc8c3
Compare
Choose a tag to compare

Overview

This release includes some minor but important changes that may break some existing users by removing deprecated functionality. I'm really sorry for the potential breaks and will do my best to adhere more strictly to semantic versioning in the future. Be aware that these changes are not taken lightly and possible alternatives were considered. I have also tried to group all the small breaks/changes into a single release to mitigate repeated painful upgrades. Building this type of library is hard and I feel for your frustrations and appreciate your understanding!

As of this release, you can now build a full-fledged Huma service with zero additional hard dependencies (if using the Go 1.22+ built-in huma.ServeMux router and only JSON).

Removal of deprecated huma.NewCLI

Back in version 2.8.0 the huma.NewCLI functionality was deprecated in favor of humacli.New. The deprecated call is now removed.

Caution

This has the potential to break existing users, but is being treated as a bug fix to remove a hard dependency on spf13/cobra. If you are already using humacli.New there is no need to change anything.

Make CBOR support optional

CBOR is now made optional in the default config. If you wish to continue using it, you must opt-in to a new import, which automatically registers the format with the default configuration:

import (
  "github.com/danielgtaylor/huma/v2"

  _ "github.com/danielgtaylor/huma/v2/formats/cbor"
)

This new behavior is documented at https://huma.rocks/features/response-serialization/#default-formats. In the future this also makes it easier to support other additional formats without adding hard dependencies.

Warning

While not a breaking change per se, without adding the new import your clients will no longer be able to request CBOR and will get JSON responses instead.

humatest no longer requires Chi

The humatest package now uses a tiny internal router rather than relying on the Chi router, which introduced extra dependencies especially for people not using Chi as their main router package. You can continue to use humatest.Wrap to wrap any router you like.

Also new are humatest.DumpRequest/humatest.DumpResponse and humatest.PrintRequest/humatest.PrintResponse utility functions which function similar to httptest.DumpRequest/httptest.DumpResponse but pretty print the body JSON to make debugging and showing examples easier. Usage example: https://go.dev/play/p/QQ9Bi7iws12.

Caution

This is technically a small breaking change, but is being treated as a bug fix to remove the dependency and make the package more future-proof by not relying on any single external router package and returning http.Handler for the router instead.

Per-operation Middleware

You can now attach middleware to a huma.Operation during registration. These middlewares will only run for that specific operation rather than for all operations:

huma.Register(api, huma.Operation{
	Method: http.MethodGet,
	Path:   "/demo",
	Middlewares: huma.Middlewares{
		func(ctx huma.Context, next func(huma.Context)) {
			// TODO: implement middleware here...
			next(ctx)
		},
	},
}, func(ctx context.Context, input *struct{}) (*struct{}, error) {
	// TODO: implement handler here...
	return nil, nil
})

See also https://huma.rocks/features/middleware/#operations.

Add ctx.Status()

You can now get the response status from a huma.Context in router-agnostic middleware, enabling easier logging/metrics/traces of the response status code.

func MyMiddleware(ctx huma.Context, next func(huma.Context)) {
	next(ctx)
	fmt.Println("Response status is", ctx.Status())
}

Better parameter descriptions

Some tools, notably SwaggerUI, require parameters to have descriptions to display properly (descriptions in the schema are not sufficient). These are now generated by Huma, so users opting to render docs with SwaggerUI should now get nicer output.

Bug Fixes

  • The humafiber adapter accepts the correct group interface now.
  • Schema name text transformations for generics are now applied to hints as well as generated names
  • Do not crash when reflect.StructOf fails in schema link transformer
  • Use errors.As when looking for huma.StatusError to enable error wrapping
  • Better error messages when missing OpenAPI config

What's Changed

New Contributors

Full Changelog: v2.12.0...v2.13.0

v2.12.0

08 Apr 15:38
6247e82
Compare
Choose a tag to compare

Overview

Support json.RawMessage

There is now better support in the validator for json.RawMessage, which turns into an empty schema (allow anything).

type Demo struct {
  Field1 string          `json:"field1"`
  Field2 json.RawMessage `json:"field2"`
}

OpenAPI 3.0.3

It's now easy to get OpenAPI 3.0.3 from a Huma service for tools that aren't completely compatible with OpenAPI 3.1 just yet. See https://huma.rocks/features/openapi-generation/. The new specs are available at /openapi-3.0.json and /openapi-3.0.yaml by default. Programmatic access is available via api.OpenAPI().Downgrade().

Better Support for Optional / Nullable Types

Huma now has better support for optional/nullable schemas. Broadly speaking, omitempty controls whether a field is optional/required and the use of a pointer controls nullability. As described in:

Huma generates type arrays from pointers to simple scalar types (boolean, integer, number, string) like "type": ["string", "null"]. This is especially useful for frontend languages like Javascript/Typescript where there is a distinction between explicit null vs. undefined and an SDK generator might produce a type union like:

// Generated Typescript example
type GreetingOutputBody = {
  message: string | null;
};

In addition to the default automatic behavior for determining optional/nullable, these can be manually overridden by the user via the required:"true|false" and nullable:"true|false" field tags, ensuring you have full control over how the schema is generated.

Important

Types which result in a JSON array or object are not marked as nullable by default, due to the complexity of modeling this in JSON Schema and poor support from SDK generators for Go and some other languages. This may change in a future release. You can mark a struct as nullable manually using a _ field with a nullable:"true" tag as described in the docs linked above.

What's Changed

New Contributors

Full Changelog: v2.11.0...v2.12.0

v2.11.0

01 Apr 15:30
ee299ec
Compare
Choose a tag to compare

Overview

Sponsors

Big shout out to our new sponsors. Thank you so much! ❤️

Stoplight Elements 8.1.0

Stoplight Elements is upgraded to the latest release, version 8.1.0.

Fix omitempty Without Name

Providing a JSON tag without a name but with ,omitempty would result in fields without a name. This is now fixed and uses the same behavior as encoding/json.

type Demo struct {
  Field string `json:",omitempty"`
}

The field name would then be Field in the JSON.

Route Groups & Servers Base Path

There is now better support for route groups in various routers, as well as smart routing for fetching the OpenAPI / JSON schemas when the OpenAPI servers field is set with a base path.

mux := chi.NewMux()
mux.Route("/api", func(r chi.Router) {
	config := huma.DefaultConfig("My API", "1.0.0")
	config.Servers = []*huma.Server{
		{URL: "https://example.com/api"},
	}
	api = humachi.New(r, config)

	// Register operations...
	huma.Get(api, "/demo", func(ctx context.Context, input *struct{}) (*struct{}, error) {
		// TODO: Implement me!
		return nil, nil
	})
})
http.ListenAndServe("localhost:8888", mux)

More docs at https://huma.rocks/features/bring-your-own-router/#route-groups-base-urls.

Schema Field Example

The generated $schema field now shows an example in the docs to help make it easy to see the JSON schema path on the server.

Docs Page Title

If an OpenAPI title is provided, then the docs page title will use it now.

What's Changed

New Contributors

Full Changelog: v2.10.0...v2.11.0

v2.10.0

25 Mar 15:51
38cf30c
Compare
Choose a tag to compare

Overview

Sponsors

Big shout out to our new sponsors. Thank you so much! ❤️

Better Support For Recursive Structs

Request/response bodies now have better support for recursive data structures, for example:

type Node struct {
	Value string `json:"value"`
	Left  *Node  `json:"left,omitempty"`
	Right *Node  `json:"right,omitempty"`
}

Multipart Form Support

You can now more easily access the incoming request's multipart form via the RawBody field:

huma.Register(api, huma.Operation{
	OperationID: "upload-files",
	Method:      http.MethodPost,
	Path:        "/upload",
	Summary:     "Example to upload a file",
}, func(ctx context.Context, input struct {
	RawBody multipart.Form
}) (*struct{}, error) {
	// Process multipart form here.
	return nil, nil
})

https://huma.rocks/features/request-inputs/#multipart-form-data

Body Fields Can Be Hidden

You can now hide body fields just like you could e.g. query/header params.

type MyObject struct {
	Public  string `json:"public"`
	Private string `json:"private" hidden:"true"`
}

This is useful if you want the field hidden from the docs but still serialized on the wire, so json:"-" would be inappropriate.

Type Aliases

Besides huma.SchemaProvider, you can now override schema generation behavior by registering known types with aliases, making it possible to override types used in structs from other packages.

registry := huma.NewMapRegistry("#/components/schemas", huma.DefaultSchemaNamer)

registry.RegisterTypeAlias(reflect.TypeFor[some_external_pkg.OptionalStr](), reflect.TypeFor[string]())
registry.RegisterTypeAlias(reflect.TypeFor[some_external_pkg.OptionalDateTime](), reflect.TypeFor[time.Time]())

What's Changed

  • feat: breaks infinite cycle when looking for fields in recursive structures. by @yuridevx in #306
  • Multipart Form RawBody Type Support by @jamelt in #324
  • feat: hidden body field support by @bekabaz in #328
  • fix: allow multipart with body; prevent double status by @danielgtaylor in #329
  • Allow specifying type aliases to provide schema definitions by @lsdch in #330

New Contributors

Full Changelog: v2.9.0...v2.10.0