huma

package module
v2.0.0-beta.3 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2023 License: MIT Imports: 35 Imported by: 77

README

Huma Rest API Framework

HUMA Powered CI codecov Docs Go Report Card

A modern, simple, fast & flexible micro framework for building HTTP REST/RPC APIs in Go backed by OpenAPI 3 and JSON Schema. Pronounced IPA: /'hjuːmɑ/. The goals of this project are to provide:

  • Incremental adoption for teams with existing services
    • Bring your own router, middleware, and logging/metrics
    • Extensible OpenAPI & JSON Schema layer to document existing routes
  • A modern REST or HTTP RPC API backend framework for Go developers
  • Guard rails to prevent common mistakes
  • Documentation that can't get out of date
  • High-quality generated developer tooling

Features include:

  • Declarative interface on top of your router of choice:
    • Operation & model documentation
    • Request params (path, query, or header)
    • Request body
    • Responses (including errors)
    • Response headers
  • JSON Errors using RFC7807 and application/problem+json by default (but can be changed)
  • Per-operation request size limits with sane defaults
  • Content negotiation between server and client
    • Support for JSON (RFC 8259) and CBOR (RFC 7049) content types via the Accept header with the default config.
  • Conditional requests support, e.g. If-Match or If-Unmodified-Since header utilities.
  • Optional automatic generation of PATCH operations that support:
  • Annotated Go types for input and output models
    • Generates JSON Schema from Go types
    • Static typing for path/query/header params, bodies, response headers, etc.
    • Automatic input model validation & error handling
  • Documentation generation using Stoplight Elements
  • Optional CLI built-in, configured via arguments or environment variables
    • Set via e.g. -p 8000, --port=8000, or SERVICE_PORT=8000
    • Startup actions & graceful shutdown built-in
  • Generates OpenAPI for access to a rich ecosystem of tools
  • Generates JSON Schema for each resource using optional describedby link relation headers as well as optional $schema properties in returned objects that integrate into editors for validation & completion.

This project was inspired by FastAPI. Logo & branding designed by Kari Taylor.

Install

# After: go mod init ...
go get -u github.com/danielgtaylor/huma/v2

Example

Here is a complete basic hello world example in Huma, that shows how to initialize a Huma app complete with CLI, declare a resource operation, and define its handler function.

package main

import (
	"context"
	"fmt"
	"net/http"

	"github.com/danielgtaylor/huma/v2"
	"github.com/danielgtaylor/huma/v2/adapters/humachi"
	"github.com/go-chi/chi/v5"
)

// Options for the CLI.
type Options struct {
	Port int `help:"Port to listen on" default:"8888"`
}

// GreetingInput represents the greeting operation request.
type GreetingInput struct {
	Name string `path:"name" doc:"Name to greet"`
}

// GreetingOutput represents the greeting operation response.
type GreetingOutput struct {
	Body struct {
		Message string `json:"message" doc:"Greeting message" example:"Hello, world!"`
	}
}

func main() {
	// Create a CLI app which takes a port option.
	cli := huma.NewCLI(func(hooks huma.Hooks, options *Options) {
		// Create a new router & API
		router := chi.NewMux()
		api := humachi.New(router, huma.DefaultConfig("My API", "1.0.0"))

		// Register GET /greeting/{name}
		huma.Register(api, huma.Operation{
			OperationID: "get-greeting",
			Summary:     "Get a greeting",
			Method:      http.MethodGet,
			Path:        "/greeting/{name}",
		}, func(ctx context.Context, input *GreetingInput) (*GreetingOutput, error) {
			resp := &GreetingOutput{}
			resp.Body.Message = fmt.Sprintf("Hello, %s!", input.Name)
			return resp, nil
		})

		// Tell the CLI how to start your router.
		hooks.OnStart(func() {
			http.ListenAndServe(fmt.Sprintf(":%d", options.Port), router)
		})
	})

	// Run the CLI. When passed no commands, it starts the server.
	cli.Run()
}

You can test it with go run greet.go (optionally pass --port to change the default) and make a sample request using Restish (or curl):

# Get the message from the server
$ restish :8888/greeting/world
HTTP/1.1 200 OK
...
{
	$schema: "http://localhost:8888/schemas/GreetingOutputBody.json",
	message: "Hello, world!"
}

Even though the example is tiny you can also see some generated documentation at http://localhost:8888/docs. The generated OpenAPI is available at http://localhost:8888/openapi.json or http://localhost:8888/openapi.yaml.

Documentation

Official Go package documentation can always be found at https://pkg.go.dev/github.com/danielgtaylor/huma/v2. Below is an introduction to the various features available in Huma.

🐳 Hi there! I'm the happy Huma whale here to provide help. You'll see me leave helpful tips down below.

BYOR (Bring Your Own Router)

Huma is designed to be router-agnostic to enable incremental adoption in existing and new services across a large number of organizations. This means you can use any router you want, or even write your own. The only requirement is and implementation of a small huma.Adapter interface. This is how Huma integrates with your router.

Adapters are in the adapters directory and named after the router they support. Many common routers are supported out of the box:

Adapters are instantiated by wrapping your router and providing a Huma configuration object which describes the API. Here is a simple example using Chi:

// Create your router.
app := chi.NewMux()

// Wrap the router with Huma to create an API instance.
api := humachi.New(app, huma.DefaultConfig("My API", "1.0.0"))

// Register your operations with the API.
// ...

// Start the server!
http.ListenAndServe(":8888", r)

🐳 Writing your own adapter is quick and simple, and PRs are accepted for additional adapters to be built-in.

Middleware

Huma v2 has support two variants of middlewares:

  1. Router-specific - works at the router level, i.e. before router-specific middleware, you can use any middleware that is implemented for your router.
  2. Router-agnostic - runs in the Huma processing chain, i.e. after calls to router-specific middleware.
Router-specific

Each router implementation has its own middlewares, you can use this middlewares with huma v2 framework.

Chi router example:

router := chi.NewMux()
router.Use(jwtauth.Verifier(tokenAuth))
api := humachi.New(router, defconfig)

🐳 Huma v1 middleware is compatible with Chi, so if you use that router with v2 you can continue to use the v1 middleware in a v2 application.

Router-agnostic

You can write you own huma v2 middleware without dependency to router implementation.

Example:

func MyMiddleware(ctx huma.Context, next func(huma.Context)) {
    // I don't do anything
    next(ctx)
}
func NewHumaAPI() huma.API {
    // ...
    api := humachi.New(router, config)
    // OR api := humagin.New(router, config)
    api.UseMiddleware(MyMiddleware)
}

Open API Generation & Extensibility

Huma generates Open API 3.1.0 compatible JSON/YAML specs and provides rendered documentation automatically. Every operation that is registered with the API is included in the spec by default. The operation's inputs and outputs are used to generate the request and response parameters / schemas.

The API config controls where the OpenAPI, docs, and schemas are available. The default config uses /openapi.json, /docs, and /schemas respectively. You can change these to whatever you want, or disable them entirely by leaving them blank.

You may want to customize the generated Open API spec. With Huma v2 you have full access and can modify it as needed in the API configuration or when registering operations. For example, to set up a security scheme:

config := huma.DefaultConfig("My API", "1.0.0")
config.Components.SecuritySchemes = map[string]*huma.SecurityScheme{
		"bearer": {
			Type: "http",
			Scheme: "bearer",
			BearerFormat: "JWT",
		},
	}
api := humachi.New(router, config)

huma.Register(api, huma.Operation{
	OperationID: "get-greeting",
	Method:      http.MethodGet,
	Path:        "/greeting/{name}",
	Summary:     "Get a greeting",
	Security: []map[string][]string{
		{"bearer": {}},
	},
}, func(ctx context.Context, input *GreetingInput) (*GreetingOutput, error) {
	// ...
})

🐳 See the OpenAPI 3.1 spec for everything that can be set and how it is expected to be used.

OpenAPI Settings Composition

Because you have full access to the OpenAPI spec, you can compose it however you want and write convenience functions to make things more straightforward. The above example could be made easier to read:

config := huma.DefaultConfig("My API", "1.0.0")
config = withBearerAuthScheme(config)

api := humachi.New(router, config)

huma.Register(api, withBearerAuth(huma.Operation{
	OperationID: "get-greeting",
	Method:      http.MethodGet,
	Path:        "/greeting/{name}",
	Summary:     "Get a greeting",
}), func(ctx context.Context, input *GreetingInput) (*GreetingOutput, error) {
	// ...
})

Set this up however you like. Even the huma.Register function can be wrapped by your organization to ensure that all operations are registered with the same settings.

Custom OpenAPI Extensions

Custom extensions to the OpenAPI are supported via the Extensions field on most OpenAPI structs:

config := huma.DefaultConfig("My API", "1.0.0")
config.Extensions = map[string]any{
	"my-extension": "my-value",
}

Anything in the Extensions map will be flattened during serialization so that its fields are peers with the Extensions peers in the OpenAPI spec. For example, the above would result in:

{
  "openapi": "3.1.0",
  "info": {
    "title": "My API",
    "version": "1.0.0"
  },
  "my-extension": "my-value"
}
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 the serve their content. For example:

Link: </schemas/Note.json>; rel="describedby"

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.

🐳 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. Note that by design it does not support multiple models with the same name in different packages.

You can create your own registry with custom behavior by implementing the huma.Registry interface and setting it on config.Components.Schemas when creating your API.

Operations

Operations are at the core of Huma. They map an HTTP method verb and resource path to a handler function with well-defined inputs and outputs. Operations are created using the huma.Register function:

huma.Register(api, huma.Operation{
	OperationID: "your-operation-name",
	Method:      http.MethodGet,
	Path:        "/path/to/resource/{id}",
	Summary:     "A short description of the operation",
}, func(ctx context.Context, input *YourInput) (*YourOutput, error) {
	// ... Implementation goes here ...
})

🐳 If following REST-ish conventions, operation paths should be nouns, and plural if they return more than one item. Good examples: /notes, /likes, /users/{user-id}, /videos/{video-id}/stats, etc. Huma does not enforce this or care, so RPC-style paths are also fine to use. Use what works best for you and your team.

The operation handler function always has the following generic format, where Input and Output are custom structs defined by the developer that represent the entirety of the request (path/query/header params & body) and response (headers & body), respectively:

func(context.Context, *Input) (*Output, error)

There are many options available for configuring OpenAPI settings for the operation, and custom extensions are supported as well. See the huma.Operation struct for more details.

🐳 Did you know? The OperationID is used to generate friendly CLI commands in Restish and used when generating SDKs! It should be unique, descriptive, and easy to type.

Input & Output Models

Inputs and outputs are always structs that represent the entirety of the incoming request or outgoing response. This is a deliberate design decision to make it easier to reason about the data flow in your application. It also makes it easier to share code as well as generate documentation and SDKs.

Request Model

Requests can have parameters and/or a body as input to the handler function. Inputs use standard Go structs with special fields and/or tags. Here are the available tags:

Tag Description Example
path Name of the path parameter path:"thing-id"
query Name of the query string parameter query:"q"
header Name of the header parameter header:"Authorization"
required Mark a query/header param as required required:"true"

🐳 The required tag is discouraged and is only used for query/header params, which should generally be optional for clients to send.

The following parameter types are supported out of the box:

Type Example Inputs
bool true, false
[u]int[16/32/64] 1234, 5, -1
float32/64 1.234, 1.0
string hello, t
time.Time 2020-01-01T12:00:00Z
slice, e.g. []int 1,2,3, tag1,tag2

For example, if the parameter is a query param and the type is []string it might look like ?tags=tag1,tag2 in the URI.

The special struct field Body will be treated as the input request body and can refer to any other type or you can embed a struct or slice inline. If the body is a pointer, then it is optional. All doc & validation tags are allowed on the body in addition to these tags:

Tag Description Example
contenttype Override the content type contenttype:"application/octet-stream"
required Mark the body as required required:"true"

RawBody []byte can also be used alongside Body or standalone to provide access to the []byte used to validate & parse Body, or to the raw input without any validation/parsing.

Example:

type MyInput struct {
	ID      string `path:"id"`
	Detail  bool   `query:"detail" doc:"Show full details"`
	Auth    string `header:"Authorization"`
	Body    MyBody
	RawBody []byte
}

A request to such an endpoint might look like:

# Via high-level operations:
$ restish api my-op 123 --detail=true --authorization=foo <body.json

# Via URL:
$ restish api/my-op/123?detail=true -H "Authorization: foo" <body.json

🐳 You can use RawBody []byte without a corresponding Body field in order to support file uploads.

Validation

Go struct tags are used to annotate inputs/output structs with information that gets turned into JSON Schema for documentation and validation.

The standard json tag is supported and can be used to rename a field and mark fields as optional using omitempty. The following additional tags are supported on model fields:

Tag Description Example
doc Describe the field doc:"Who to greet"
format Format hint for the field format:"date-time"
enum A comma-separated list of possible values enum:"one,two,three"
default Default value default:"123"
minimum Minimum (inclusive) minimum:"1"
exclusiveMinimum Minimum (exclusive) exclusiveMinimum:"0"
maximum Maximum (inclusive) maximum:"255"
exclusiveMaximum Maximum (exclusive) exclusiveMaximum:"100"
multipleOf Value must be a multiple of this value multipleOf:"2"
minLength Minimum string length minLength:"1"
maxLength Maximum string length maxLength:"80"
pattern Regular expression pattern pattern:"[a-z]+"
minItems Minimum number of array items minItems:"1"
maxItems Maximum number of array items maxItems:"20"
uniqueItems Array items must be unique uniqueItems:"true"
minProperties Minimum number of object properties minProperties:"1"
maxProperties Maximum number of object properties maxProperties:"20"
example Example value example:"123"
readOnly Sent in the response only readOnly:"true"
writeOnly Sent in the request only writeOnly:"true"
deprecated This field is deprecated deprecated:"true"

Parameters have some additional validation tags:

Tag Description Example
hidden Hide parameter from documentation hidden:"true"
Resolvers

Sometimes the built-in validation isn't sufficient for your use-case, or you want to do something more complex with the incoming request object. This is where resolvers come in.

Any input struct can be a resolver by implementing the huma.Resolver or huma.ResolverWithPath interface, including embedded structs. Each resolver takes the current context and can return a list of exhaustive errors. For example:

// MyInput demonstrates inputs/transformation
type MyInput struct {
	Host   string
	Name string `query:"name"`
}

func (m *MyInput) Resolve(ctx huma.Context) []error {
	// Get request info you don't normally have access to.
	m.Host = ctx.Host()

	// Transformations or other data validation
	m.Name = strings.Title(m.Name)

	return nil
}

// Then use it like any other input struct:
huma.Register(api, huma.Operation{
	OperationID: "list-things",
	Method:      http.MethodGet,
	Path:        "/things",
	Summary:     "Get a filtered list of things",
}, func(ctx context.Context, input *MyInput) (*YourOutput, error) {
	fmt.Printf("Host: %s\n", input.Host)
	fmt.Printf("Name: %s\n", input.Name)
})

It is recommended that you do not save the context object passed to the Resolve method for later use.

For deeply nested structs within the request body, you may not know the current location of the field being validated (e.g. it may appear in multiple places or be shared by multiple request objects). The huma.ResolverWithPath interface provides a path prefix that can be used to generate the full path to the field being validated. It uses a huma.PathBuffer for efficient path generation reusing a shared buffer. For example:

func (m *MyInput) Resolve(ctx huma.Context, prefix *huma.PathBuffer) []error {
	return []error{&huma.ErrorDetail{
		Message: "Foo has a bad value",
		Location: prefix.With("foo")
		Value: m.Foo,
	}}
}

🐳 Prefer using built-in validation over resolvers whenever possible, as it will be better documented and is also usable by OpenAPI tooling to provide a better developer experience.

Resolver Errors

Resolvers can set errors as needed and Huma will automatically return a 400-level error response before calling your handler. This makes resolvers a good place to run additional complex validation steps so you can provide the user with a set of exhaustive errors.

type MyInput struct {
	Host   string
}

func (m *MyInput) Resolve(ctx huma.Context) []error {
	if m.Host = ctx.Host(); m.Host == "localhost" {
		return []error{&huma.ErrorDetail{
			Message: "Unsupported host value!",
			Location: "request.host",
			Value: m.Host,
		}}
	}
	return nil
}

It is also possible for resolvers to return custom HTTP status codes for the response, by returning an error which satisfies the huma.StatusError interface. Errors are processed in the order they are returned and the last one wins, so this feature should be used sparingly. For example:

type MyInput struct{}

func (i *MyInput) Resolve(ctx huma.Context) []error {
	return []error{huma.Error403Forbidden("nope")}
}

🐳 Exhaustive errors lessen frustration for users. It's better to return three errors in response to one request than to have the user make three requests which each return a new different error.

Input Composition

Because inputs are just Go structs, they are composable and reusable. For example:

type AuthParam struct {
	Authorization string `header:"Authorization"`
}

type PaginationParams struct {
	Cursor string `query:"cursor"`
	Limit  int    `query:"limit"`
}

// ... Later in the code
huma.Register(api, huma.Operation{
	OperationID: "list-things",
	Method:      http.MethodGet,
	Path:        "/things",
	Summary:     "Get a filtered list of things",
}, func(ctx context.Context, input struct {
	// Embed both structs to compose your input.
	AuthParam
	PaginationParams
}) {
	fmt.Printf("Auth: %s, Cursor: %s, Limit: %d\n", input.Authorization, input.Cursor, input.Limit)
}
Request Deadlines & Timeouts

A combination of the server and the request context can be used to control deadlines & timeouts. Go's built-in HTTP server supports a few timeout settings:

srv := &http.Server{
	ReadTimeout:       5 * time.Second,
	WriteTimeout:      5 * time.Second,
	IdleTimeout:       30 * time.Second,
	ReadHeaderTimeout: 2 * time.Second,
	// ...
}

The Huma request context (accessible via resolvers) can be used to set a read deadline, which can be used to process large or streaming inputs:

type MyInput struct {}

func (m *MyInput) Resolve(ctx huma.Context) []error {
	ctx.SetReadDeadline(time.Now().Add(5 * time.Second))
}

Additionally, a context.Context can be used to set a deadline for dependencies like databases:

// Create a new context with a 10 second timeout.
newCtx, cancel := context.WithTimeout(ctx, 10 * time.Second)
defer cancel()

// Use the new context for any dependencies.
result, err := myDB.Get(newCtx, /* ... */)
if err != nil {
	// Deadline may have been hit, handle it here!
}
Request Body Size Limits

By default each operation has a 1 MiB request body size limit. This can be changed by setting huma.Operation.MaxBodyBytes to a different value when registering the operation. If the request body is larger than the limit then a 413 Request Entity Too Large error will be returned.

Response Model

Responses can have an optional status code, headers, and/or body. Like inputs, they use standard Go structs. Here are the available tags:

Tag Description Example
header Name of the response header header:"Authorization"

The special struct field Status with a type of int is used to optionally communicate a dynamic response status code from the handler (you should not need this most of the time!). If not present, the default is to use 200 for responses with bodies and 204 for responses without a body. Use huma.Operation.DefaultStatus at operation registration time to override. Note: it is much more common to set the default status code than to need a Status field in your response struct!

The special struct field Body will be treated as the response body and can refer to any other type or you can embed a struct or slice inline. Use a type of []byte to bypass serialization. A default Content-Type header will be set if none is present, selected via client-driven content negotiation with the server based on the registered serialization types.

Example:

type MyOutput struct {
	Status       int
	LastModified time.Time `header:"Last-Modified"`
	Body         MyBody
}
Streaming Responses

The response Body can also be a callback function taking a huma.Context to facilitate streaming. The huma.StreamResponse utility makes this easy to return:

func handler(ctx context.Context, input *MyInput) (*huma.StreamResponse, error) {
	return &huma.StreamResponse{
		Body: func(ctx huma.Context) {
			// Write header info before streaming the body.
			ctx.SetHeader("Content-Type", "text/my-stream")
			writer := ctx.BodyWriter()

			// Update the write deadline to give us extra time.
			if d, ok := bw.(interface{ SetWriteDeadline(time.Time) error }); ok {
				d.SetWriteDeadline(time.Now().Add(5 * time.Second))
			} else {
				fmt.Println("warning: unable to set write deadline")
			}

			// Write the first message, then flush and wait.
			writer.Write([]byte("Hello, I'm streaming!"))
			if f, ok := writer.(http.Flusher); ok {
				f.Flush()
			} else {
				fmt.Println("error: unable to flush")
			}

			time.Sleep(3 * time.Second)

			// Write the second message.
			writer.Write([]byte("Hello, I'm still streaming!"))
		},
	}, nil
}

Also take a look at http.ResponseController which can be used to set timeouts, flush, etc in one simple interface.

🐳 The sse package provides a helper for streaming Server-Sent Events (SSE) responses that is easier to use than the above example!

Generated Schema Customization

Schemas that are generated for input/output bodies can be customized in a couple of different ways. First, when registering your operation you can provide your own request and/or response schemas if you want to override the entire body. The automatic generation only applies when you have not provided your own schema in the OpenAPI.

Second, this can be done on a per-field basis by making a struct that implements a special interface to get a schema, allowing you to e.g. encapsulate additional functionality within that field. This is the interface:

// SchemaProvider is an interface that can be implemented by types to provide
// a custom schema for themselves, overriding the built-in schema generation.
// This can be used by custom types with their own special serialization rules.
type SchemaProvider interface {
	Schema(r huma.Registry) *huma.Schema
}

The huma.Registry is passed to you and can be used to get schemas or refs for any embedded structs. Here is an example, where we want to know if a field was omitted vs. null vs. a value when sent as part of a request body. First we start by defininig the custom generic struct:

// OmittableNullable is a field which can be omitted from the input,
// set to `null`, or set to a value. Each state is tracked and can
// be checked for in handling code.
type OmittableNullable[T any] struct {
	Sent  bool
	Null  bool
	Value T
}

// UnmarshalJSON unmarshals this value from JSON input.
func (o *OmittableNullable[T]) UnmarshalJSON(b []byte) error {
	if len(b) > 0 {
		o.Sent = true
		if bytes.Equal(b, []byte("null")) {
			o.Null = true
			return nil
		}
		return json.Unmarshal(b, &o.Value)
	}
	return nil
}

// Schema returns a schema representing this value on the wire.
// It returns the schema of the contained type.
func (o OmittableNullable[T]) Schema(r huma.Registry) *huma.Schema {
	return r.Schema(reflect.TypeOf(o.Value), true, "")
}

This is how it can be used in an operation:

type MyResponse struct {
	Body struct {
		Message string `json:"message"`
	}
}

huma.Register(api, huma.Operation{
	OperationID: "omittable",
	Method:      http.MethodPost,
	Path:        "/omittable",
	Summary:     "Omittable / nullable example",
}, func(ctx context.Context, input *struct {
	// Making the body a pointer makes it optional, as it may be `nil`.
	Body *struct {
		Name OmittableNullable[string] `json:"name,omitempty" maxLength:"10"`
	}
}) (*MyResponse, error) {
	resp := &MyResponse{}
	if input.Body == nil {
		resp.Body.Message = "Body was not sent"
	} else if !input.Body.Name.Sent {
		resp.Body.Message = "Name was omitted from the request"
	} else if input.Body.Name.Null {
		resp.Body.Message = "Name was set to null"
	} else {
		resp.Body.Message = "Name was set to: " + input.Body.Name.Value
	}
	return resp, nil
})

If you go to view the generated docs, you will see that the type of the name field is string and that it is optional, with a max length of 10, indicating that the custom schema was correctly used in place of one generated for the OmittableNullable[string] struct.

See https://github.com/danielgtaylor/huma/blob/main/examples/omit/main.go for a full example along with how to call it. This just scratches the surface of what's possible with custom schemas for fields.

Exhaustive Errors

Errors use RFC 7807 and return a structure that looks like:

{
  "status": 504,
  "title": "Gateway Timeout",
  "detail": "Problem with HTTP request",
  "errors": [
    {
      "message": "Get \"https://httpstat.us/418?sleep=5000\": context deadline exceeded"
    }
  ]
}

The errors field is optional and may contain more details about which specific errors occurred.

It is recommended to return exhaustive errors whenever possible to prevent user frustration with having to keep retrying a bad request and getting back a different error. Input parameters validation, body validation, resolvers, etc all support returning exhaustive errors.

While every attempt is made to return exhaustive errors within Huma, each individual response can only contain a single HTTP status code. The following chart describes which codes get returned and when:

flowchart TD
	Request[Request has errors?] -->|yes| Panic
	Request -->|no| Continue[Continue to handler]
	Panic[Panic?] -->|yes| 500
	Panic -->|no| RequestBody[Request body too large?]
	RequestBody -->|yes| 413
	RequestBody -->|no| RequestTimeout[Request took too long to read?]
	RequestTimeout -->|yes| 408
	RequestTimeout -->|no| ParseFailure[Cannot parse input?]
	ParseFailure -->|yes| 400
	ParseFailure -->|no| ValidationFailure[Validation failed?]
	ValidationFailure -->|yes| 422
	ValidationFailure -->|no| 400

This means it is possible to, for example, get an HTTP 408 Request Timeout response that also contains an error detail with a validation error for one of the input headers. Since request timeout has higher priority, that will be the response status code that is returned.

Response Transformers

Router middleware operates on router-specific request & response objects whose bodies are []byte slices or streams. Huma operations operate on specific struct instances. Sometimes there is a need to generically operate on structured response data after the operation handler has run but before the response is serialized to bytes. This is where response transformers come in.

flowchart LR
	Request --> Middleware
	Middleware --> Unmarshal
	subgraph Huma
		Unmarshal --> Handler
		Handler --> Transformer
		Transformer --> Marshal
	end
	Marshal --> Response

	style Transformer stroke:#f9f,stroke-width:2px,stroke-dasharray: 5 5

Response transformers enable you to modify the response on the fly. For example, you could add a Link header to the response to indicate that the response body is described by a JSON Schema. This is done by implementing the huma.Transformer interface and registering it with the API. See the huma.SchemaLinkTransformer for an example.

Serialization Formats

Huma supports custom serialization formats by implementing the huma.Format interface. Serialization formats are set on the API configuration at API creation time and selected by client-driven content negotiation using the Accept or Content-Type headers. The config.Formats maps either a content type name or extension (suffix) to a huma.Format instance.

The default configuration for Huma includes support for JSON (RFC 8259) and CBOR (RFC 7049) content types via the Accept header. This is done by registering the following content types using huma.DefaultJSONFormat & huma.DefaultCBORFormat:

  • application/json
  • Anything ending with +json
  • application/cbor
  • Anything ending with +cbor

🐳 You can easily add support for additional serialization formats, including binary formats like Protobuf if desired.

Content Negotiation

Content negotiation allows clients to select the content type they are most comfortable working with when talking to the API. For request bodies, this uses the Content-Type header. For response bodies, it uses the Accept header. If none are present then JSON is usually selected as the default / preferred content type.

See the negotiation package for more info.

CLI

Huma ships with a built-in lightweight utility to wrap your service with a CLI, enabling you to run it with different arguments and easily write custom commands to do things like print out the OpenAPI or run on-demand database migrations.

The CLI options use a similar strategy to input & output structs, enabling you to use the same pattern for validation and documentation of command line arguments. It uses Cobra & Viper under the hood, enabling automatic environment variable binding and more.

// First, define your input options.
type Options struct {
	Debug bool   `doc:"Enable debug logging"`
	Host  string `doc:"Hostname to listen on."`
	Port  int    `doc:"Port to listen on." short:"p" default:"8888"`
}

func main() {
	// Then, create the CLI.
	cli := huma.NewCLI(func(hooks huma.Hooks, opts *Options) {
		fmt.Printf("I was run with debug:%v host:%v port%v\n",
			opts.Debug, opts.Host, opts.Port)
	})

	// Run the thing!
	cli.Run()
}

You can then run the CLI with and see the results:

$ go run main.go
I was run with debug:false host: port:8888

To do useful work, you will want to register a handler for the default start command and optionally a way to gracefully shutdown the server:

cli := huma.NewCLI(func(hooks huma.Hooks, opts *Options) {
	hooks.OnStart(func() {
		// Start your server here
		http.ListenAndServe(
			fmt.Sprintf("%s:%d", opts.Host, opts.Port), myRouter,
		)
	})

	hooks.OnStop(func() {
		// Gracefully shutdown your server here
		// ...
	})
})

🐳 Option fields are automatically converted to --kebab-casing for use on the command line. If you want to use a different name, use the name struct tag to override the default behavior!

Custom Options

Custom options are defined by adding to your options struct. The following types are supported:

Type Example Inputs
bool true, false
int / int64 1234, 5, -1
string prod, http://api.example.tld/

The following struct tags are available:

Tag Description Example
default Default value (parsed automatically) default:"123"
doc Describe the option doc:"Who to greet"
name Override the name of the option name:"my-option-name"
short Single letter short name for the option short:"p" for -p
Custom Commands

You can access the root cobra.Command via cli.Root() and add new custom commands via cli.Root().AddCommand(...). For example, to have a command print out the generated OpenAPI:

var api huma.API

// ... set up the CLI, create the API wrapping the router ...

cli.Root().AddCommand(&cobra.Command{
	Use:   "openapi",
	Short: "Print the OpenAPI spec",
	Run: func(cmd *cobra.Command, args []string) {
		b, _ := yaml.Marshal(api.OpenAPI())
		fmt.Println(string(b))
	},
})

Now you can run your service and use the new command: go run main.go openapi.

If you want to access your custom options struct with custom commands, use the huma.WithOptions(func(cmd *cobra.Command, args []string, options *YourOptions)) func(cmd *cobra.Command, args []string) utitity function. It ensures the options are parsed and available before running your command.

🐳 You can also overwite cli.Root().Run to completely customize how you run the server. Or just ditch the cli package altogether!

Additional Features

Conditional Requests

There are built-in utilities for handling conditional requests, which serve two broad purposes:

  1. Sparing bandwidth on reading a document that has not changed, i.e. "only send if the version is different from what I already have"
  2. Preventing multiple writers from clobbering each other's changes, i.e. "only save if the version on the server matches what I saw last"

Adding support for handling conditional requests requires four steps:

  1. Import the github.com/danielgtaylor/huma/conditional package.
  2. (optional) Add the response definition (304 Not Modified for reads or 412 Precondition Failed for writes)
  3. Add conditional.Params to your input struct.
  4. Check if conditional params were passed and handle them. The HasConditionalParams() and PreconditionFailed(...) methods can help with this.

Implementing a conditional read might look like:

huma.Register(api, huma.Operation{
	OperationID: "get-resource",
	Method:      http.MethodGet,
	Path:        "/resource",
	Summary:     "Get a resource",
}, func(ctx context.Context, input struct {
	conditional.Params
}) (*YourOutput, error) {
	if input.HasConditionalParams() {
		// TODO: Get the ETag and last modified time from the resource.
		etag := ""
		modified := time.Time{}

		// If preconditions fail, abort the request processing. Response status
		// codes are already set for you, but you can optionally provide a body.
		// Returns an HTTP 304 not modified.
		if err := input.PreconditionFailed(etag, modified); err != nil {
			return err
		}

		// Otherwise do the normal request processing here...
		// ...
	}
})

🐳 Note that it is more efficient to construct custom DB queries to handle conditional requests, however Huma is not aware of your database. The built-in conditional utilities are designed to be generic and work with any data source, and are a quick and easy way to get started with conditional request handling.

Auto Patch Operations

If a GET and a PUT exist for the same resource, but no PATCH exists at server start up, then a PATCH operation can be generated for you to make editing more convenient for clients. You can opt-in to this behavior with the autopatch package:

import "github.com/danielgtaylor/huma/autopatch"

// ...

// Later in the code *after* registering operations...
autopatch.AutoPatch(api)

If the GET returns an ETag or Last-Modified header, then these will be used to make conditional requests on the PUT operation to prevent distributed write conflicts that might otherwise overwrite someone else's changes.

The following formats are supported out of the box, selected via the Content-Type header:

If the PATCH request has no Content-Type header, or uses application/json or a variant thereof, then JSON Merge Patch is assumed.

🐳 You can think of the Shorthand Merge Patch as an extension to the JSON merge patch with support for field paths, arrays, and a few other features. Patches like this are possible, appending an item to an array (creating it if needed):

{
  foo.bar[]: "baz",
}

Server Sent Events (SSE)

The sse package provides a helper for streaming Server-Sent Events (SSE) responses. It provides a simple API for sending events to the client and documents the event types and data structures in the OpenAPI spec if you provide a mapping of message type names to Go structs:

// Register using sse.Register instead of huma.Register
sse.Register(api, huma.Operation{
	OperationID: "sse",
	Method:      http.MethodGet,
	Path:        "/sse",
	Summary:     "Server sent events example",
}, map[string]any{
	// Mapping of event type name to Go struct for that event.
	"message":      DefaultMessage{},
	"userCreate":   UserCreatedEvent{},
	"mailRecieved": MailReceivedEvent{},
}, func(ctx context.Context, input *struct{}, send sse.Sender) {
	// Send an event every second for 10 seconds.
	for x := 0; x < 10; x++ {
		send.Data(MailReceivedEvent{UserID: "abc123"})
		time.Sleep(1 * time.Second)
	}
})

🐳 Each event model must be a unique Go type. If you want to reuse Go type definitions, you can define a new type referencing another type, e.g. type MySpecificEvent MyBaseEvent and it will work as expected.

CLI AutoConfig

Huma includes built-in support for an OpenAPI 3 extension that enables CLI autoconfiguration. This allows tools like Restish to automatically configure themselves to talk to your API with the correct endpoints, authentication mechanism, etc without the user needing to know anything about your API.

o := api.OpenAPI()
o.Components.SecuritySchemes["my-scheme"] = &huma.SecurityScheme{
	Type: "oauth2",
	// ... security scheme definition ...
}
o.Extensions["x-cli-autoconfig"] = huma.AutoConfig{
	Security: "my-scheme",
	Params: map[string]string{
		"client_id": "abc123",
		"authorize_url": "https://example.tld/authorize",
		"token_url": "https://example.tld/token",
		"scopes": "read,write",
	}
}

See the CLI AutoConfiguration documentation for more info, including how to ask the user for custom parameters.

Model Validation

Huma includes a utility to make it a little easier to validate models outside of the normal HTTP request/response flow, for example on app startup to load example or default data and verify it is correct. This is just a thin wrapper around the built-in validation functionality, but abstracts away some of the boilerplate required for efficient operation and provides a simple API.

type MyExample struct {
	Name string `json:"name" maxLength:"5"`
	Age int `json:"age" minimum:"25"`
}

var value any
json.Unmarshal([]byte(`{"name": "abcdefg", "age": 1}`), &value)

validator := huma.ModelValidator()
errs := validator.Validate(reflect.TypeOf(MyExample{}), value)
if errs != nil {
	fmt.Println("Validation error", errs)
}

🐳 The huma.ModelValidator is not goroutine-safe! For more flexible validation, use the huma.Validate function directly and provide your own registry, path buffer, validation result struct, etc.

Low-Level API

Huma v2 is written so that you can use the low-level API directly if you want to. This is useful if you want to add some new feature or abstraction that Huma doesn't support out of the box. Huma's own huma.Register function, automatic HTTP PATCH handlers, and the sse package are all built on top of the public low-level API.

huma.Adapter

The adapter is the core of Huma's bring-your-own-router functionality. It is an abstraction on top of routers and HTTP libraries that operates on a generic huma.Context described below. The adapter interface is simple and allows registering operation handlers and serving standard library HTTP requests:

type Adapter interface {
	Handle(op *Operation, handler func(ctx Context))
	ServeHTTP(http.ResponseWriter, *http.Request)
}
huma.Context

The context provides a generic HTTP layer which is translated into specific router operations when called by the adapter.

type Context interface {
	Operation() *Operation
	Context() context.Context
	Method() string
	Host() string
	URL() url.URL
	Param(name string) string
	Query(name string) string
	Header(name string) string
	EachHeader(cb func(name, value string))
	BodyReader() io.Reader
	SetReadDeadline(time.Time) error
	SetStatus(code int)
	SetHeader(name, value string)
	AppendHeader(name, value string)
	BodyWriter() io.Writer
}
huma.Register

The huma.Register function is a highly-optimized wrapper around the low-level API that handles all the OpenAPI generation, validation, and serialization for you. It is a good example of how to use the low-level API. At a high level it does the following:

  1. Adds OpenAPI descriptions of the operation to the OpenAPI spec
  2. Registers an operation handler with the adapter
    1. Reads request parameters (ctx.Param, ctx.Query, ctx.Header)
    2. Parses request body if present (ctx.BodyReader)
    3. Calls the user's handler function with all inputs
    4. Handles errors returned from the handler by writing to the ctx
    5. Writes success response (ctx.SetStatus, ctx.SetHeader, ctx.BodyWriter)

🐳 Because huma.Register uses only the public interfaces of the low-level API, you can easily wrap it or write your own register function to provide new functionality.

Migrating from Huma v1

  1. Import github.com/danielgtaylor/huma/v2 instead of github.com/danielgtaylor/huma.
  2. Use the humachi.NewV4 adapter as Huma v1 uses Chi v4 under the hood
  3. Attach your middleware to the chi instance.
  4. Replace resource & operation creation with huma.Register
  5. Rewrite handlers to be like func(context.Context, *Input) (*Output, error)
    1. Return errors instead of ctx.WriteError(...)
    2. Return instances instead of ctx.WriteModel(...)
  6. Define options via a struct and use huma.NewCLI to wrap the service

Note that GraphQL support from Huma v1 has been removed. Take a look at alternative tools like https://www.npmjs.com/package/openapi-to-graphql which will automatically generate a GraphQL endpoint from Huma's generated OpenAPI spec.

Benchmarks

Significant performance improvements have been made since Huma v1, as shown by the following basic benchmark operation with a few input parameters, a small input body, some output headers and an output body (see adapters/humachi/humachi_test.go).

# Huma v1
BenchmarkHumaV1Chi-10         16285  112086 ns/op  852209 B/op  258 allocs/op

# Huma v2
BenchmarkHumaV2ChiNormal-10  431028    2777 ns/op    1718 B/op   29 allocs/op

# Chi without Huma (raw)
BenchmarkRawChi-10           552764    2143 ns/op    2370 B/op   29 allocs/op

These improvements are due to a number of factors, including changes to the Huma API, precomputation of reflection data when possible, low or zero-allocation validation & URL parsing, using shared buffer pools to limit garbage collector pressure, and more.

Since you bring your own router, you are free to "escape" Huma by using the router directly, but as you can see above it's rarely needed with v2.

🐳 Thanks for reading!

Documentation

Index

Examples

Constants

View Source
const (
	TypeBoolean = "boolean"
	TypeInteger = "integer"
	TypeNumber  = "number"
	TypeString  = "string"
	TypeArray   = "array"
	TypeObject  = "object"
)

JSON Schema type constants

Variables

View Source
var DefaultCBORFormat = Format{
	Marshal: func(w io.Writer, v any) error {
		return cborEncMode.NewEncoder(w).Encode(v)
	},
	Unmarshal: cbor.Unmarshal,
}

DefaultCBORFormat is the default CBOR formatter that can be set in the API's `Config.Formats` map. This is used by the `DefaultConfig` function.

config := huma.Config{}
config.Formats = map[string]huma.Format{
	"application/cbor": huma.DefaultCBORFormat,
	"cbor":             huma.DefaultCBORFormat,
}
View Source
var DefaultJSONFormat = Format{
	Marshal: func(w io.Writer, v any) error {
		return json.NewEncoder(w).Encode(v)
	},
	Unmarshal: json.Unmarshal,
}

DefaultJSONFormat is the default JSON formatter that can be set in the API's `Config.Formats` map. This is used by the `DefaultConfig` function.

config := huma.Config{}
config.Formats = map[string]huma.Format{
	"application/json": huma.DefaultJSONFormat,
	"json":             huma.DefaultJSONFormat,
}
View Source
var ErrSchemaInvalid = errors.New("schema is invalid")

ErrSchemaInvalid is sent when there is a problem building the schema.

View Source
var NewError = func(status int, msg string, errs ...error) StatusError {
	details := make([]*ErrorDetail, len(errs))
	for i := 0; i < len(errs); i++ {
		if converted, ok := errs[i].(ErrorDetailer); ok {
			details[i] = converted.ErrorDetail()
		} else {
			details[i] = &ErrorDetail{Message: errs[i].Error()}
		}
	}
	return &ErrorModel{
		Status: status,
		Title:  http.StatusText(status),
		Detail: msg,
		Errors: details,
	}
}

NewError creates a new instance of an error model with the given status code, message, and optional error details. If the error details implement the `ErrorDetailer` interface, the error details will be used. Otherwise, the error string will be used as the message. This function is used by all the error response utility functions, like `huma.Error400BadRequest`.

Replace this function to use your own error type. Example:

type MyDetail struct {
	Message string	`json:"message"`
	Location string	`json:"location"`
}

type MyError struct {
	status  int
	Message string	`json:"message"`
	Errors  []error	`json:"errors"`
}

func (e *MyError) Error() string {
	return e.Message
}

func (e *MyError) GetStatus() int {
	return e.status
}

huma.NewError = func(status int, msg string, errs ...error) StatusError {
	return &MyError{
		status:  status,
		Message: msg,
		Errors:  errs,
	}
}

Functions

func AutoRegister

func AutoRegister(api API, server any)

AutoRegister auto-detects operation registration methods and registers them with the given API. Any method named `Register...` will be called and passed the API as the only argument. Since registration happens at service startup, no errors are returned and methods should panic on error.

type ItemServer struct {}

func (s *ItemServer) RegisterListItems(api API) {
	huma.Register(api, huma.Operation{
		OperationID: "ListItems",
		Method: http.MethodGet,
		Path: "/items",
	}, s.ListItems)
}

func main() {
	api := huma.NewAPI("My Service", "1.0.0")
	itemServer := &ItemServer{}
	huma.AutoRegister(api, itemServer)
}

func DefaultSchemaNamer

func DefaultSchemaNamer(t reflect.Type, hint string) string

DefaultSchemaNamer provides schema names for types. It uses the type name when possible, ignoring the package name. If the type is generic, e.g. `MyType[SubType]`, then the brackets are removed like `MyTypeSubType`. If the type is unnamed, then the name hint is used. Note: if you plan to use types with the same name from different packages, you should implement your own namer function to prevent issues. Nested anonymous types can also present naming issues.

func FieldSelectTransform

func FieldSelectTransform(ctx Context, status string, v any) (any, error)

FieldSelectTransform is an example of a transform that can use an input header value to modify the response on the server, providing a GraphQL-like way to send only the fields that the client wants over the wire.

func Register

func Register[I, O any](api API, op Operation, handler func(context.Context, *I) (*O, error))

Register an operation handler for an API. The handler must be a function that takes a context and a pointer to the input struct and returns a pointer to the output struct and an error. The input struct must be a struct with fields for the request path/query/header parameters and/or body. The output struct must be a struct with fields for the output headers and body of the operation, if any.

func SetReadDeadline

func SetReadDeadline(w http.ResponseWriter, deadline time.Time) error

SetReadDeadline is a utility to set the read deadline on a response writer, if possible. If not, it will not incur any allocations (unlike the stdlib `http.ResponseController`). This is mostly a convenience function for adapters so they can be more efficient.

huma.SetReadDeadline(w, time.Now().Add(5*time.Second))

func Validate

func Validate(r Registry, s *Schema, path *PathBuffer, mode ValidateMode, v any, res *ValidateResult)

Validate an input value against a schema, collecting errors in the validation result object. If successful, `res.Errors` will be empty. It is suggested to use a `sync.Pool` to reuse the PathBuffer and ValidateResult objects, making sure to call `Reset()` on them before returning them to the pool.

registry := huma.NewMapRegistry("#/prefix", huma.DefaultSchemaNamer)
schema := huma.SchemaFromType(registry, reflect.TypeOf(MyType{}))
pb := huma.NewPathBuffer([]byte(""), 0)
res := &huma.ValidateResult{}

var value any
json.Unmarshal([]byte(`{"foo": "bar"}`), &v)
huma.Validate(registry, schema, pb, huma.ModeWriteToServer, value, res)
for _, err := range res.Errors {
	fmt.Println(err.Error())
}

func WithOptions

func WithOptions[Options any](f func(cmd *cobra.Command, args []string, options *Options)) func(*cobra.Command, []string)

WithOptions is a helper for custom commands that need to access the options.

cli.Root().AddCommand(&cobra.Command{
	Use: "my-custom-command",
	Run: huma.WithOptions(func(cmd *cobra.Command, args []string, opts *Options) {
		fmt.Println("Hello " + opts.Name)
	}),
})

func WriteErr

func WriteErr(api API, ctx Context, status int, msg string, errs ...error) error

WriteErr writes an error response with the given context, using the configured error type and with the given status code and message. It is marshaled using the API's content negotiation methods.

Types

type API

type API interface {
	// Adapter returns the router adapter for this API, providing a generic
	// interface to get request information and write responses.
	Adapter() Adapter

	// OpenAPI returns the OpenAPI spec for this API. You may edit this spec
	// until the server starts.
	OpenAPI() *OpenAPI

	// Negotiate returns the selected content type given the client's `accept`
	// header and the server's supported content types. If the client does not
	// send an `accept` header, then JSON is used.
	Negotiate(accept string) (string, error)

	// Marshal marshals the given value into the given writer. The content type
	// is used to determine which format to use. Use `Negotiate` to get the
	// content type from an accept header. TODO: update
	Marshal(ctx Context, respKey string, contentType string, v any) error

	// Unmarshal unmarshals the given data into the given value. The content type
	Unmarshal(contentType string, data []byte, v any) error

	// UseMiddleware appends a middleware handler to the API middleware stack.
	//
	// The middleware stack for any API will execute before searching for a matching
	// route to a specific handler, which provides opportunity to respond early,
	// change the course of the request execution, or set request-scoped values for
	// the next Middleware.
	UseMiddleware(middlewares ...func(ctx Context, next func(Context)))

	// Middlewares returns a slice of middleware handler functions.
	Middlewares() Middlewares
}

API represents a Huma API wrapping a specific router.

func NewAPI

func NewAPI(config Config, a Adapter) API

type Adapter

type Adapter interface {
	Handle(op *Operation, handler func(ctx Context))
	ServeHTTP(http.ResponseWriter, *http.Request)
}

Adapter is an interface that allows the API to be used with different HTTP routers and frameworks. It is designed to work with the standard library `http.Request` and `http.ResponseWriter` types as well as types like `gin.Context` or `fiber.Ctx` that provide both request and response functionality in one place.

type AddOpFunc

type AddOpFunc func(oapi *OpenAPI, op *Operation)

type AutoConfig

type AutoConfig struct {
	Security string                   `json:"security"`
	Headers  map[string]string        `json:"headers,omitempty"`
	Prompt   map[string]AutoConfigVar `json:"prompt,omitempty"`
	Params   map[string]string        `json:"params"`
}

AutoConfig holds an API's automatic configuration settings for the CLI. These are advertised via OpenAPI extension and picked up by the CLI to make it easier to get started using an API. This struct should be put into the `OpenAPI.Extensions` map under the key `x-cli-config`. See also: https://rest.sh/#/openapi?id=autoconfiguration

type AutoConfigVar

type AutoConfigVar struct {
	Description string        `json:"description,omitempty"`
	Example     string        `json:"example,omitempty"`
	Default     interface{}   `json:"default,omitempty"`
	Enum        []interface{} `json:"enum,omitempty"`

	// Exclude the value from being sent to the server. This essentially makes
	// it a value which is only used in param templates.
	Exclude bool `json:"exclude,omitempty"`
}

AutoConfigVar represents a variable given by the user when prompted during auto-configuration setup of an API.

type CLI

type CLI interface {
	// Run the CLI. This will parse the command-line arguments and environment
	// variables and then run the appropriate command. If no command is given,
	// the default command will call the `OnStart` function to start a server.
	Run()

	// Root returns the root Cobra command. This can be used to add additional
	// commands or flags. Customize it however you like.
	Root() *cobra.Command
}

CLI is an optional command-line interface for a Huma service. It is provided as a convenience for quickly building a service with configuration from the environment and/or command-line options, all tied to a simple type-safe Go struct.

func NewCLI

func NewCLI[O any](onParsed func(Hooks, *O)) CLI

NewCLI creates a new CLI. The `onParsed` callback is called after the command options have been parsed and the options struct has been populated. You should set up a `hooks.OnStart` callback to start the server with your chosen router.

// First, define your input options.
type Options struct {
	Debug bool   `doc:"Enable debug logging"`
	Host  string `doc:"Hostname to listen on."`
	Port  int    `doc:"Port to listen on." short:"p" default:"8888"`
}

// Then, create the CLI.
cli := huma.NewCLI(func(hooks huma.Hooks, opts *Options) {
	fmt.Printf("Options are debug:%v host:%v port%v\n",
		opts.Debug, opts.Host, opts.Port)

	// Set up the router & API
	router := chi.NewRouter()
	api := humachi.New(router, huma.DefaultConfig("My API", "1.0.0"))
	srv := &http.Server{
		Addr: fmt.Sprintf("%s:%d", opts.Host, opts.Port),
		Handler: router,
		// TODO: Set up timeouts!
	}

	hooks.OnStart(func() {
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("listen: %s\n", err)
		}
	})

	hooks.OnStop(func() {
		srv.Shutdown(context.Background())
	})
})

// Run the thing!
cli.Run()

type Components

type Components struct {
	Schemas         Registry                   `yaml:"schemas,omitempty"`
	Responses       map[string]*Response       `yaml:"responses,omitempty"`
	Parameters      map[string]*Param          `yaml:"parameters,omitempty"`
	Examples        map[string]*Example        `yaml:"examples,omitempty"`
	RequestBodies   map[string]*RequestBody    `yaml:"requestBodies,omitempty"`
	Headers         map[string]*Header         `yaml:"headers,omitempty"`
	SecuritySchemes map[string]*SecurityScheme `yaml:"securitySchemes,omitempty"`
	Links           map[string]*Link           `yaml:"links,omitempty"`
	Callbacks       map[string]*PathItem       `yaml:"callbacks,omitempty"`
	PathItems       map[string]*PathItem       `yaml:"pathItems,omitempty"`
	Extensions      map[string]any             `yaml:",inline"`
}

type Config

type Config struct {
	// OpenAPI spec for the API. You should set at least the `Info.Title` and
	// `Info.Version` fields.
	*OpenAPI

	// OpenAPIPath is the path to the OpenAPI spec without extension. If set
	// to `/openapi` it will allow clients to get `/openapi.json` or
	// `/openapi.yaml`, for example.
	OpenAPIPath string
	DocsPath    string
	SchemasPath string

	// Formats defines the supported request/response formats by content type or
	// extension (e.g. `json` for `application/my-format+json`).
	Formats map[string]Format

	// DefaultFormat specifies the default content type to use when the client
	// does not specify one. If unset, the default type will be randomly
	// chosen from the keys of `Formats`.
	DefaultFormat string

	// Transformers are a way to modify a response body before it is serialized.
	Transformers []Transformer
}

Config represents a configuration for a new API. See `huma.DefaultConfig()` as a starting point.

func DefaultConfig

func DefaultConfig(title, version string) Config

DefaultConfig returns a default configuration for a new API. It is a good starting point for creating your own configuration. It supports JSON and CBOR formats out of the box. The registry uses references for structs and a link transformer is included to add `$schema` fields and links into responses. The `/openapi.[json|yaml]`, `/docs`, and `/schemas` paths are set up to serve the OpenAPI spec, docs UI, and schemas respectively.

// Create and customize the config (if desired).
config := huma.DefaultConfig("My API", "1.0.0")

// Create the API using the config.
router := chi.NewMux()
api := humachi.New(router, config)

type Contact

type Contact struct {
	// Name of the contact person/organization.
	Name string `yaml:"name,omitempty"`

	// URL pointing to the contact information.
	URL string `yaml:"url,omitempty"`

	// Email address of the contact person/organization.
	Email string `yaml:"email,omitempty"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

Contact information to get support for the API.

type ContentTypeFilter

type ContentTypeFilter interface {
	ContentType(string) string
}

ContentTypeFilter allows you to override the content type for responses, allowing you to return a different content type like `application/problem+json` after using the `application/json` marshaller. This should be implemented by the response body struct.

type Context

type Context interface {
	Operation() *Operation
	Context() context.Context
	Method() string
	Host() string
	URL() url.URL
	Param(name string) string
	Query(name string) string
	Header(name string) string
	EachHeader(cb func(name, value string))
	BodyReader() io.Reader
	GetMultipartForm() (*multipart.Form, error)
	SetReadDeadline(time.Time) error
	SetStatus(code int)
	SetHeader(name, value string)
	AppendHeader(name, value string)
	BodyWriter() io.Writer
}

Context is the current request/response context. It provides a generic interface to get request information and write responses.

type Encoding

type Encoding struct {
	ContentType   string             `yaml:"contentType,omitempty"`
	Headers       map[string]*Header `yaml:"headers,omitempty"`
	Style         string             `yaml:"style,omitempty"`
	Explode       *bool              `yaml:"explode,omitempty"`
	AllowReserved bool               `yaml:"allowReserved,omitempty"`
	Extensions    map[string]any     `yaml:",inline"`
}

type ErrorDetail

type ErrorDetail struct {
	// Message is a human-readable explanation of the error.
	Message string `json:"message,omitempty" doc:"Error message text"`

	// Location is a path-like string indicating where the error occurred.
	// It typically begins with `path`, `query`, `header`, or `body`. Example:
	// `body.items[3].tags` or `path.thing-id`.
	Location string `json:"location,omitempty" doc:"Where the error occurred, e.g. 'body.items[3].tags' or 'path.thing-id'"`

	// Value is the value at the given location, echoed back to the client
	// to help with debugging. This can be useful for e.g. validating that
	// the client didn't send extra whitespace or help when the client
	// did not log an outgoing request.
	Value any `json:"value,omitempty" doc:"The value at the given location"`
}

ErrorDetail provides details about a specific error.

func (*ErrorDetail) Error

func (e *ErrorDetail) Error() string

Error returns the error message / satisfies the `error` interface. If a location and value are set, they will be included in the error message, otherwise just the message is returned.

func (*ErrorDetail) ErrorDetail

func (e *ErrorDetail) ErrorDetail() *ErrorDetail

ErrorDetail satisfies the `ErrorDetailer` interface.

type ErrorDetailer

type ErrorDetailer interface {
	ErrorDetail() *ErrorDetail
}

ErrorDetailer returns error details for responses & debugging. This enables the use of custom error types. See `NewError` for more details.

type ErrorModel

type ErrorModel struct {
	// Type is a URI to get more information about the error type.
	Type string `` /* 170-byte string literal not displayed */

	// Title provides a short static summary of the problem. Huma will default this
	// to the HTTP response status code text if not present.
	Title string `` /* 166-byte string literal not displayed */

	// Status provides the HTTP status code for client convenience. Huma will
	// default this to the response status code if unset. This SHOULD match the
	// response status code (though proxies may modify the actual status code).
	Status int `json:"status,omitempty" example:"400" doc:"HTTP status code"`

	// Detail is an explanation specific to this error occurrence.
	Detail string `` /* 153-byte string literal not displayed */

	// Instance is a URI to get more info about this error occurrence.
	Instance string `` /* 163-byte string literal not displayed */

	// Errors provides an optional mechanism of passing additional error details
	// as a list.
	Errors []*ErrorDetail `json:"errors,omitempty" doc:"Optional list of individual error details"`
}

ErrorModel defines a basic error message model based on RFC 7807 Problem Details for HTTP APIs (https://datatracker.ietf.org/doc/html/rfc7807). It is augmented with an `errors` field of `huma.ErrorDetail` objects that can help provide exhaustive & descriptive errors.

err := &huma.ErrorModel{
	Title: http.StatusText(http.StatusBadRequest),
	Status http.StatusBadRequest,
	Detail: "Validation failed",
	Errors: []*huma.ErrorDetail{
		&huma.ErrorDetail{
			Message: "expected required property id to be present",
			Location: "body.friends[0]",
			Value: nil,
		},
		&huma.ErrorDetail{
			Message: "expected boolean",
			Location: "body.friends[1].active",
			Value: 5,
		},
	},
}

func (*ErrorModel) Add

func (e *ErrorModel) Add(err error)

Add an error to the `Errors` slice. If passed a struct that satisfies the `huma.ErrorDetailer` interface, then it is used, otherwise the error string is used as the error detail message.

err := &ErrorModel{ /* ... */ }
err.Add(&huma.ErrorDetail{
	Message: "expected boolean",
	Location: "body.friends[1].active",
	Value: 5
})

func (*ErrorModel) ContentType

func (e *ErrorModel) ContentType(ct string) string

ContentType provides a filter to adjust response content types. This is used to ensure e.g. `application/problem+json` content types defined in RFC 7807 Problem Details for HTTP APIs are used in responses to clients.

func (*ErrorModel) Error

func (e *ErrorModel) Error() string

Error satisfies the `error` interface. It returns the error's detail field.

func (*ErrorModel) GetStatus

func (e *ErrorModel) GetStatus() int

GetStatus returns the HTTP status that should be returned to the client for this error.

type Example

type Example struct {
	Ref           string         `yaml:"$ref,omitempty"`
	Summary       string         `yaml:"summary,omitempty"`
	Description   string         `yaml:"description,omitempty"`
	Value         any            `yaml:"value,omitempty"`
	ExternalValue string         `yaml:"externalValue,omitempty"`
	Extensions    map[string]any `yaml:",inline"`
}

type ExternalDocs

type ExternalDocs struct {
	Description string         `yaml:"description,omitempty"`
	URL         string         `yaml:"url"`
	Extensions  map[string]any `yaml:",inline"`
}

type Format

type Format struct {
	// Marshal a value to a given writer (e.g. response body).
	Marshal func(writer io.Writer, v any) error

	// Unmarshal a value into `v` from the given bytes (e.g. request body).
	Unmarshal func(data []byte, v any) error
}

Format represents a request / response format. It is used to marshal and unmarshal data.

type Header = Param

type Hooks

type Hooks interface {
	// OnStart sets a function to call when the service should be started. This
	// is called by the default command if no command is given. The callback
	// should take whatever steps are necessary to start the server, such as
	// `httpServer.ListenAndServer(...)`.
	OnStart(func())

	// OnStop sets a function to call when the service should be stopped. This
	// is called by the default command if no command is given. The callback
	// should take whatever steps are necessary to stop the server, such as
	// `httpServer.Shutdown(...)`.
	OnStop(func())
}

Hooks is an interface for setting up callbacks for the CLI. It is used to start and stop the service.

type Info

type Info struct {
	// Title of the API.
	Title string `yaml:"title"`

	// Description of the API. CommonMark syntax MAY be used for rich text representation.
	Description string `yaml:"description,omitempty"`

	// TermsOfService URL for the API.
	TermsOfService string `yaml:"termsOfService,omitempty"`

	// Contact information to get support for the API.
	Contact *Contact `yaml:"contact,omitempty"`

	// License name & link for using the API.
	License *License `yaml:"license,omitempty"`

	// Version of the OpenAPI document (which is distinct from the OpenAPI Specification version or the API implementation version).
	Version string `yaml:"version"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

Info object that provides metadata about the API. The metadata MAY be used by the clients if needed, and MAY be presented in editing or documentation generation tools for convenience.

type License

type License struct {
	// Name of the license.
	Name string `yaml:"name"`

	// Identifier SPDX license expression for the API. This field is mutually
	// exclusive with the URL field.
	Identifier string `yaml:"identifier,omitempty"`

	// URL pointing to the license. This field is mutually exclusive with the
	// Identifier field.
	URL string `yaml:"url,omitempty"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

License name & link for using the API.

type Link struct {
	Ref          string         `yaml:"$ref,omitempty"`
	OperationRef string         `yaml:"operationRef,omitempty"`
	OperationID  string         `yaml:"operationId,omitempty"`
	Parameters   map[string]any `yaml:"parameters,omitempty"`
	RequestBody  any            `yaml:"requestBody,omitempty"`
	Description  string         `yaml:"description,omitempty"`
	Server       *Server        `yaml:"server,omitempty"`
	Extensions   map[string]any `yaml:",inline"`
}

type MediaType

type MediaType struct {
	Schema     *Schema              `yaml:"schema,omitempty"`
	Example    any                  `yaml:"example,omitempty"`
	Examples   map[string]*Example  `yaml:"examples,omitempty"`
	Encoding   map[string]*Encoding `yaml:"encoding,omitempty"`
	Extensions map[string]any       `yaml:",inline"`
}

type Middlewares

type Middlewares []func(ctx Context, next func(Context))

func (Middlewares) Handler

func (m Middlewares) Handler(endpoint func(Context)) func(Context)

Handler builds and returns a handler func from the chain of middlewares, with `endpoint func` as the final handler.

type ModelValidator

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

ModelValidator is a utility for validating e.g. JSON loaded data against a Go struct model. It is not goroutine-safe and should not be used in HTTP handlers! Schemas are generated on-the-fly on first use and re-used on subsequent calls. This utility can be used to easily validate data outside of the normal request/response flow, for example on application startup:

type MyExample struct {
	Name string `json:"name" maxLength:"5"`
	Age int `json:"age" minimum:"25"`
}

var value any
json.Unmarshal([]byte(`{"name": "abcdefg", "age": 1}`), &value)

validator := ModelValidator()
errs := validator.Validate(reflect.TypeOf(MyExample{}), value)
if errs != nil {
	fmt.Println("Validation error", errs)
}
Example
// Define a type you want to validate.
type Model struct {
	Name string `json:"name" maxLength:"5"`
	Age  int    `json:"age" minimum:"25"`
}

typ := reflect.TypeOf(Model{})

// Unmarshal some JSON into an `any` for validation. This input should not
// validate against the schema for the struct above.
var val any
json.Unmarshal([]byte(`{"name": "abcdefg", "age": 1}`), &val)

// Validate the unmarshaled data against the type and print errors.
validator := NewModelValidator()
errs := validator.Validate(typ, val)
fmt.Println(errs)

// Try again with valid data!
json.Unmarshal([]byte(`{"name": "foo", "age": 25}`), &val)
errs = validator.Validate(typ, val)
fmt.Println(errs)
Output:

[expected length <= 5 (name: abcdefg) expected number >= 25 (age: 1)]
[]

func NewModelValidator

func NewModelValidator() *ModelValidator

NewModelValidator creates a new model validator with all the components it needs to create schemas, validate them, and return any errors.

func (*ModelValidator) Validate

func (v *ModelValidator) Validate(typ reflect.Type, value any) []error

Validate the inputs. The type should be the Go struct with validation field tags and the value should be e.g. JSON loaded into an `any`. A list of errors is returned if validation failed, otherwise `nil`.

type MyExample struct {
	Name string `json:"name" maxLength:"5"`
	Age int `json:"age" minimum:"25"`
}

var value any
json.Unmarshal([]byte(`{"name": "abcdefg", "age": 1}`), &value)

validator := ModelValidator()
errs := validator.Validate(reflect.TypeOf(MyExample{}), value)
if errs != nil {
	fmt.Println("Validation error", errs)
}

type OAuthFlow

type OAuthFlow struct {
	AuthorizationURL string            `yaml:"authorizationUrl"`
	TokenURL         string            `yaml:"tokenUrl"`
	RefreshURL       string            `yaml:"refreshUrl,omitempty"`
	Scopes           map[string]string `yaml:"scopes"`
	Extensions       map[string]any    `yaml:",inline"`
}

type OAuthFlows

type OAuthFlows struct {
	Implicit          *OAuthFlow     `yaml:"implicit,omitempty"`
	Password          *OAuthFlow     `yaml:"password,omitempty"`
	ClientCredentials *OAuthFlow     `yaml:"clientCredentials,omitempty"`
	AuthorizationCode *OAuthFlow     `yaml:"authorizationCode,omitempty"`
	Extensions        map[string]any `yaml:",inline"`
}

type OpenAPI

type OpenAPI struct {
	OpenAPI           string                `yaml:"openapi"`
	Info              *Info                 `yaml:"info"`
	Servers           []*Server             `yaml:"servers,omitempty"`
	JSONSchemaDialect string                `yaml:"jsonSchemaDialect,omitempty"`
	Paths             map[string]*PathItem  `yaml:"paths,omitempty"`
	Webhooks          map[string]*PathItem  `yaml:"webhooks,omitempty"`
	Components        *Components           `yaml:"components,omitempty"`
	Security          []map[string][]string `yaml:"security,omitempty"`
	Tags              []*Tag                `yaml:"tags,omitempty"`
	ExternalDocs      *ExternalDocs         `yaml:"externalDocs,omitempty"`
	Extensions        map[string]any        `yaml:",inline"`

	// OnAddOperation is called when an operation is added to the OpenAPI via
	// `AddOperation`. You may bypass this by directly writing to the `Paths`
	// map instead.
	OnAddOperation []AddOpFunc `yaml:"-"`
}

func (*OpenAPI) AddOperation

func (o *OpenAPI) AddOperation(op *Operation)

func (*OpenAPI) MarshalJSON

func (o *OpenAPI) MarshalJSON() ([]byte, error)

type Operation

type Operation struct {

	// Method is the HTTP method for this operation
	Method string `yaml:"-"`

	// Path is the URL path for this operation
	Path string `yaml:"-"`

	// DefaultStatus is the default HTTP status code for this operation. It will
	// be set to 200 or 204 if not specified, depending on whether the handler
	// returns a response body.
	DefaultStatus int `yaml:"-"`

	// MaxBodyBytes is the maximum number of bytes to read from the request
	// body. If not specified, the default is 1MB. Use -1 for unlimited. If
	// the limit is reached, then an HTTP 413 error is returned.
	MaxBodyBytes int64 `yaml:"-"`

	// BodyReadTimeout is the maximum amount of time to wait for the request
	// body to be read. If not specified, the default is 5 seconds. Use -1
	// for unlimited. If the timeout is reached, then an HTTP 408 error is
	// returned. This value supercedes the server's read timeout, and a value
	// of -1 can unset the server's timeout.
	BodyReadTimeout time.Duration `yaml:"-"`

	// Errors is a list of HTTP status codes that the handler may return. If
	// not specified, then a default error response is added to the OpenAPI.
	Errors []int `yaml:"-"`

	// SkipValidateParams disables validation of path, query, and header
	// parameters. This can speed up request processing if you want to handle
	// your own validation. Use with caution!
	SkipValidateParams bool `yaml:"-"`

	// SkipValidateBody disables validation of the request body. This can speed
	// up request processing if you want to handle your own validation. Use with
	// caution!
	SkipValidateBody bool `yaml:"-"`

	// Hidden will skip documenting this operation in the OpenAPI. This is
	// useful for operations that are not intended to be used by clients but
	// you'd still like the benefits of using Huma. Generally not recommended.
	Hidden bool `yaml:"-"`

	Tags         []string              `yaml:"tags,omitempty"`
	Summary      string                `yaml:"summary,omitempty"`
	Description  string                `yaml:"description,omitempty"`
	ExternalDocs *ExternalDocs         `yaml:"externalDocs,omitempty"`
	OperationID  string                `yaml:"operationId,omitempty"`
	Parameters   []*Param              `yaml:"parameters,omitempty"`
	RequestBody  *RequestBody          `yaml:"requestBody,omitempty"`
	Responses    map[string]*Response  `yaml:"responses,omitempty"`
	Callbacks    map[string]*PathItem  `yaml:"callbacks,omitempty"`
	Deprecated   bool                  `yaml:"deprecated,omitempty"`
	Security     []map[string][]string `yaml:"security,omitempty"`
	Servers      []*Server             `yaml:"servers,omitempty"`
	Extensions   map[string]any        `yaml:",inline"`
}

type Param

type Param struct {
	Ref           string              `yaml:"$ref,omitempty"`
	Name          string              `yaml:"name,omitempty"`
	In            string              `yaml:"in,omitempty"`
	Description   string              `yaml:"description,omitempty"`
	Required      bool                `yaml:"required,omitempty"`
	Deprecated    bool                `yaml:"deprecated,omitempty"`
	Style         string              `yaml:"style,omitempty"`
	Explode       *bool               `yaml:"explode,omitempty"`
	AllowReserved bool                `yaml:"allowReserved,omitempty"`
	Schema        *Schema             `yaml:"schema,omitempty"`
	Example       any                 `yaml:"example,omitempty"`
	Examples      map[string]*Example `yaml:"examples,omitempty"`
	Extensions    map[string]any      `yaml:",inline"`
}

type PathBuffer

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

PathBuffer is a low-allocation helper for building a path string like `foo.bar.baz`. It is not goroutine-safe. Combined with `sync.Pool` it can result in zero allocations, and is used for validation. It is significantly better than `strings.Builder` and `bytes.Buffer` for this use case.

Path buffers can be converted to strings for use in responses or printing using either the `pb.String()` or `pb.With("field")` methods.

pb := NewPathBuffer([]byte{}, 0)
pb.Push("foo")  // foo
pb.PushIndex(1) // foo[1]
pb.Push("bar")  // foo[1].bar
pb.Pop()        // foo[1]
pb.Pop()        // foo

func NewPathBuffer

func NewPathBuffer(buf []byte, offset int) *PathBuffer

NewPathBuffer creates a new path buffer given an existing byte slice. Tip: using `sync.Pool` can significantly reduce buffer allocations.

pb := NewPathBuffer([]byte{}, 0)
pb.Push("foo")

func (*PathBuffer) Bytes

func (b *PathBuffer) Bytes() []byte

Bytes returns the underlying slice of bytes of the path.

func (*PathBuffer) Len

func (b *PathBuffer) Len() int

Len returns the length of the current path.

func (*PathBuffer) Pop

func (b *PathBuffer) Pop()

Pop the latest entry off the path.

pb.Push("foo")  // foo
pb.PushIndex(1) // foo[1]
pb.Push("bar")  // foo[1].bar
pb.Pop()        // foo[1]
pb.Pop()        // foo

func (*PathBuffer) Push

func (b *PathBuffer) Push(s string)

Push an entry onto the path, adding a `.` separator as needed.

pb.Push("foo") // foo
pb.Push("bar") // foo.bar

func (*PathBuffer) PushIndex

func (b *PathBuffer) PushIndex(i int)

PushIndex pushes an entry onto the path surrounded by `[` and `]`.

pb.Push("foo")  // foo
pb.PushIndex(1) // foo[1]

func (*PathBuffer) Reset

func (b *PathBuffer) Reset()

Reset the path buffer to empty, keeping and reusing the underlying bytes.

func (*PathBuffer) String

func (b *PathBuffer) String() string

String converts the path buffer to a string.

func (*PathBuffer) With

func (b *PathBuffer) With(s string) string

With is shorthand for push, convert to string, and pop. This is useful when you want the location of a field given a path buffer as a prefix.

pb.Push("foo")
pb.With("bar") // returns foo.bar

type PathItem

type PathItem struct {
	Ref         string         `yaml:"$ref,omitempty"`
	Summary     string         `yaml:"summary,omitempty"`
	Description string         `yaml:"description,omitempty"`
	Get         *Operation     `yaml:"get,omitempty"`
	Put         *Operation     `yaml:"put,omitempty"`
	Post        *Operation     `yaml:"post,omitempty"`
	Delete      *Operation     `yaml:"delete,omitempty"`
	Options     *Operation     `yaml:"options,omitempty"`
	Head        *Operation     `yaml:"head,omitempty"`
	Patch       *Operation     `yaml:"patch,omitempty"`
	Trace       *Operation     `yaml:"trace,omitempty"`
	Servers     []*Server      `yaml:"servers,omitempty"`
	Parameters  []*Param       `yaml:"parameters,omitempty"`
	Extensions  map[string]any `yaml:",inline"`
}

type Registry

type Registry interface {
	Schema(t reflect.Type, allowRef bool, hint string) *Schema
	SchemaFromRef(ref string) *Schema
	TypeFromRef(ref string) reflect.Type
	Map() map[string]*Schema
}

Registry creates and stores schemas and their references, and supports marshalling to JSON/YAML for use as an OpenAPI #/components/schemas object. Behavior is implementation-dependent, but the design allows for recursive schemas to exist while being flexible enough to support other use cases like only inline objects (no refs) or always using refs for structs.

func NewMapRegistry

func NewMapRegistry(prefix string, namer func(t reflect.Type, hint string) string) Registry

NewMapRegistry creates a new registry that stores schemas in a map and returns references to them using the given prefix.

type RequestBody

type RequestBody struct {
	Ref         string                `yaml:"$ref,omitempty"`
	Description string                `yaml:"description,omitempty"`
	Content     map[string]*MediaType `yaml:"content"`
	Required    bool                  `yaml:"required,omitempty"`
	Extensions  map[string]any        `yaml:",inline"`
}

type Resolver

type Resolver interface {
	Resolve(ctx Context) []error
}

Resolver runs a `Resolve` function after a request has been parsed, enabling you to run custom validation or other code that can modify the request and / or return errors.

type ResolverWithPath

type ResolverWithPath interface {
	Resolve(ctx Context, prefix *PathBuffer) []error
}

ResolverWithPath runs a `Resolve` function after a request has been parsed, enabling you to run custom validation or other code that can modify the request and / or return errors. The `prefix` is the path to the current location for errors, e.g. `body.foo[0].bar`.

type Response

type Response struct {
	Ref         string                `yaml:"$ref,omitempty"`
	Description string                `yaml:"description,omitempty"`
	Headers     map[string]*Param     `yaml:"headers,omitempty"`
	Content     map[string]*MediaType `yaml:"content,omitempty"`
	Links       map[string]*Link      `yaml:"links,omitempty"`
	Extensions  map[string]any        `yaml:",inline"`
}

type Schema

type Schema struct {
	Type                 string             `yaml:"type,omitempty"`
	Title                string             `yaml:"title,omitempty"`
	Description          string             `yaml:"description,omitempty"`
	Ref                  string             `yaml:"$ref,omitempty"`
	Format               string             `yaml:"format,omitempty"`
	ContentEncoding      string             `yaml:"contentEncoding,omitempty"`
	Default              any                `yaml:"default,omitempty"`
	Examples             []any              `yaml:"examples,omitempty"`
	Items                *Schema            `yaml:"items,omitempty"`
	AdditionalProperties any                `yaml:"additionalProperties,omitempty"`
	Properties           map[string]*Schema `yaml:"properties,omitempty"`
	Enum                 []any              `yaml:"enum,omitempty"`
	Minimum              *float64           `yaml:"minimum,omitempty"`
	ExclusiveMinimum     *float64           `yaml:"exclusiveMinimum,omitempty"`
	Maximum              *float64           `yaml:"maximum,omitempty"`
	ExclusiveMaximum     *float64           `yaml:"exclusiveMaximum,omitempty"`
	MultipleOf           *float64           `yaml:"multipleOf,omitempty"`
	MinLength            *int               `yaml:"minLength,omitempty"`
	MaxLength            *int               `yaml:"maxLength,omitempty"`
	Pattern              string             `yaml:"pattern,omitempty"`
	MinItems             *int               `yaml:"minItems,omitempty"`
	MaxItems             *int               `yaml:"maxItems,omitempty"`
	UniqueItems          bool               `yaml:"uniqueItems,omitempty"`
	Required             []string           `yaml:"required,omitempty"`
	MinProperties        *int               `yaml:"minProperties,omitempty"`
	MaxProperties        *int               `yaml:"maxProperties,omitempty"`
	ReadOnly             bool               `yaml:"readOnly,omitempty"`
	WriteOnly            bool               `yaml:"writeOnly,omitempty"`
	Deprecated           bool               `yaml:"deprecated,omitempty"`
	Extensions           map[string]any     `yaml:",inline"`

	OneOf []*Schema `yaml:"oneOf,omitempty"`
	AnyOf []*Schema `yaml:"anyOf,omitempty"`
	AllOf []*Schema `yaml:"allOf,omitempty"`
	Not   *Schema   `yaml:"not,omitempty"`
	// contains filtered or unexported fields
}

Schema represents a JSON Schema compatible with OpenAPI 3.1. It is extensible with your own custom properties. It supports a subset of the full JSON Schema spec, designed specifically for use with Go structs and to enable fast zero or near-zero allocation happy-path validation for incoming requests.

Typically you will use a registry and `huma.SchemaFromType` to generate schemas for your types. You can then use `huma.Validate` to validate incoming requests.

// Create a registry and register a type.
registry := huma.NewMapRegistry("#/prefix", huma.DefaultSchemaNamer)
schema := huma.SchemaFromType(registry, reflect.TypeOf(MyType{}))

Note that the registry may create references for your types.

func SchemaFromField

func SchemaFromField(registry Registry, f reflect.StructField, hint string) *Schema

SchemaFromField generates a schema for a given struct field. If the field is a struct (or slice/map of structs) then the registry is used to potentially get a reference to that type.

This is used by `huma.SchemaFromType` when it encounters a struct, and is used to generate schemas for path/query/header parameters.

func SchemaFromType

func SchemaFromType(r Registry, t reflect.Type) *Schema

SchemaFromType returns a schema for a given type, using the registry to possibly create references for nested structs. The schema that is returned can then be passed to `huma.Validate` to efficiently validate incoming requests.

// Create a registry and register a type.
registry := huma.NewMapRegistry("#/prefix", huma.DefaultSchemaNamer)
schema := huma.SchemaFromType(registry, reflect.TypeOf(MyType{}))

func (*Schema) MarshalJSON

func (s *Schema) MarshalJSON() ([]byte, error)

MarshalJSON marshals the schema into JSON, respecting the `Extensions` map to marshal extensions inline.

func (*Schema) PrecomputeMessages

func (s *Schema) PrecomputeMessages()

PrecomputeMessages tries to precompute as many validation error messages as possible so that new strings aren't allocated during request validation.

type SchemaLinkTransformer

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

SchemaLinkTransformer is a transform that adds a `$schema` field to the response (if it is a struct) and a Link header pointing to the JSON Schema that describes the response structure. This is useful for clients to understand the structure of the response and enables things like as-you-type validation & completion of HTTP resources in editors like VSCode.

func NewSchemaLinkTransformer

func NewSchemaLinkTransformer(prefix, schemasPath string) *SchemaLinkTransformer

NewSchemaLinkTransformer creates a new transformer that will add a `$schema` field to the response (if it is a struct) and a Link header pointing to the JSON Schema that describes the response structure. This is useful for clients to understand the structure of the response and enables things like as-you-type validation & completion of HTTP resources in editors like VSCode.

func (*SchemaLinkTransformer) OnAddOperation

func (t *SchemaLinkTransformer) OnAddOperation(oapi *OpenAPI, op *Operation)

OnAddOperation is triggered whenever a new operation is added to the API, enabling this transformer to precompute & cache information about the response and schema.

func (*SchemaLinkTransformer) Transform

func (t *SchemaLinkTransformer) Transform(ctx Context, status string, v any) (any, error)

Transform is called for every response to add the `$schema` field and/or the Link header pointing to the JSON Schema.

type SchemaProvider

type SchemaProvider interface {
	Schema(r Registry) *Schema
}

SchemaProvider is an interface that can be implemented by types to provide a custom schema for themselves, overriding the built-in schema generation. This can be used by custom types with their own special serialization rules.

type SecurityScheme

type SecurityScheme struct {
	Type             string         `yaml:"type"`
	Description      string         `yaml:"description,omitempty"`
	Name             string         `yaml:"name,omitempty"`
	In               string         `yaml:"in,omitempty"`
	Scheme           string         `yaml:"scheme,omitempty"`
	BearerFormat     string         `yaml:"bearerFormat,omitempty"`
	Flows            *OAuthFlows    `yaml:"flows,omitempty"`
	OpenIDConnectURL string         `yaml:"openIdConnectUrl,omitempty"`
	Extensions       map[string]any `yaml:",inline"`
}

type Server

type Server struct {
	// URL to the target host. This URL supports Server Variables and MAY be relative, to indicate that the host location is relative to the location where the OpenAPI document is being served. Variable substitutions will be made when a variable is named in {brackets}.
	URL string `yaml:"url"`

	// Description of the host designated by the URL. CommonMark syntax MAY be used for rich text representation.
	Description string `yaml:"description,omitempty"`

	// Variables map between a variable name and its value. The value is used for substitution in the server’s URL template.
	Variables map[string]*ServerVariable `yaml:"variables,omitempty"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

Server URL, optionally with variables.

type ServerVariable

type ServerVariable struct {
	// Enumeration of string values to be used if the substitution options are from a limited set. The array MUST NOT be empty.
	Enum []string `yaml:"enum,omitempty"`

	// Default value to use for substitution, which SHALL be sent if an alternate value is not supplied.
	Default string `yaml:"default"`

	// Description for the server variable. CommonMark syntax MAY be used for rich text representation.
	Description string `yaml:"description,omitempty"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

ServerVariable for server URL template substitution.

type StatusError

type StatusError interface {
	GetStatus() int
	Error() string
}

StatusError is an error that has an HTTP status code. When returned from an operation handler, this sets the response status code before sending it to the client.

func Error400BadRequest

func Error400BadRequest(msg string, errs ...error) StatusError

Error400BadRequest returns a 400.

func Error401Unauthorized

func Error401Unauthorized(msg string, errs ...error) StatusError

Error401Unauthorized returns a 401.

func Error403Forbidden

func Error403Forbidden(msg string, errs ...error) StatusError

Error403Forbidden returns a 403.

func Error404NotFound

func Error404NotFound(msg string, errs ...error) StatusError

Error404NotFound returns a 404.

func Error405MethodNotAllowed

func Error405MethodNotAllowed(msg string, errs ...error) StatusError

Error405MethodNotAllowed returns a 405.

func Error406NotAcceptable

func Error406NotAcceptable(msg string, errs ...error) StatusError

Error406NotAcceptable returns a 406.

func Error409Conflict

func Error409Conflict(msg string, errs ...error) StatusError

Error409Conflict returns a 409.

func Error410Gone

func Error410Gone(msg string, errs ...error) StatusError

Error410Gone returns a 410.

func Error412PreconditionFailed

func Error412PreconditionFailed(msg string, errs ...error) StatusError

Error412PreconditionFailed returns a 412.

func Error415UnsupportedMediaType

func Error415UnsupportedMediaType(msg string, errs ...error) StatusError

Error415UnsupportedMediaType returns a 415.

func Error422UnprocessableEntity

func Error422UnprocessableEntity(msg string, errs ...error) StatusError

Error422UnprocessableEntity returns a 422.

func Error429TooManyRequests

func Error429TooManyRequests(msg string, errs ...error) StatusError

Error429TooManyRequests returns a 429.

func Error500InternalServerError

func Error500InternalServerError(msg string, errs ...error) StatusError

Error500InternalServerError returns a 500.

func Error501NotImplemented

func Error501NotImplemented(msg string, errs ...error) StatusError

Error501NotImplemented returns a 501.

func Error502BadGateway

func Error502BadGateway(msg string, errs ...error) StatusError

Error502BadGateway returns a 502.

func Error503ServiceUnavailable

func Error503ServiceUnavailable(msg string, errs ...error) StatusError

Error503ServiceUnavailable returns a 503.

func Error504GatewayTimeout

func Error504GatewayTimeout(msg string, errs ...error) StatusError

Error504GatewayTimeout returns a 504.

func Status304NotModified

func Status304NotModified() StatusError

Status304NotModified returns a 304. This is not really an error, but provides a way to send non-default responses.

type StreamResponse

type StreamResponse struct {
	Body func(ctx Context)
}

StreamResponse is a response that streams data to the client. The body function will be called once the response headers have been written and the body writer is ready to be written to.

func handler(ctx context.Context, input *struct{}) (*huma.StreamResponse, error) {
	return &huma.StreamResponse{
		Body: func(ctx huma.Context) {
			ctx.SetHeader("Content-Type", "text/my-type")

			// Write some data to the stream.
			writer := ctx.BodyWriter()
			writer.Write([]byte("Hello "))

			// Flush the stream to the client.
			if f, ok := writer.(http.Flusher); ok {
				f.Flush()
			}

			// Write some more...
			writer.Write([]byte("world!"))
		}
	}
}

type Tag

type Tag struct {
	Name         string         `yaml:"name"`
	Description  string         `yaml:"description,omitempty"`
	ExternalDocs *ExternalDocs  `yaml:"externalDocs,omitempty"`
	Extensions   map[string]any `yaml:",inline"`
}

type Transformer

type Transformer func(ctx Context, status string, v any) (any, error)

Transformer is a function that can modify a response body before it is serialized. The `status` is the HTTP status code for the response and `v` is the value to be serialized. The return value is the new value to be serialized or an error.

type ValidateMode

type ValidateMode int

ValidateMode describes the direction of validation (server -> client or client -> server). It impacts things like how read-only or write-only fields are handled.

const (
	// ModeReadFromServer is a read mode (response output) that may ignore or
	// reject write-only fields that are non-zero, as these write-only fields
	// are meant to be sent by the client.
	ModeReadFromServer ValidateMode = iota

	// ModeWriteToServer is a write mode (request input) that may ignore or
	// reject read-only fields that are non-zero, as these are owned by the
	// server and the client should not try to modify them.
	ModeWriteToServer
)

type ValidateResult

type ValidateResult struct {
	Errors []error
}

ValidateResult tracks validation errors. It is safe to use for multiple validations as long as `Reset()` is called between uses.

func (*ValidateResult) Add

func (r *ValidateResult) Add(path *PathBuffer, v any, msg string)

Add an error to the validation result at the given path and with the given value.

func (*ValidateResult) Addf

func (r *ValidateResult) Addf(path *PathBuffer, v any, format string, args ...any)

Addf adds an error to the validation result at the given path and with the given value, allowing for fmt.Printf-style formatting.

func (*ValidateResult) Reset

func (r *ValidateResult) Reset()

Reset the validation error so it can be used again.

Directories

Path Synopsis
adapters
examples
cmd
omit
This example shows how to handle omittable/nullable fields and an optional body in JSON input.
This example shows how to handle omittable/nullable fields and an optional body in JSON input.
oneof-response
This example show how to respond to API requests with different versions of the response body.
This example show how to respond to API requests with different versions of the response body.
param-reuse
This example shows how to reuse a parameter in the path and body.
This example shows how to reuse a parameter in the path and body.
v1-middleware
An example showing how to use Huma v1 middleware in a Huma v2 project.
An example showing how to use Huma v1 middleware in a Huma v2 project.
Package humatest provides testing utilities for Huma services.
Package humatest provides testing utilities for Huma services.
Package queryparam provides utilities for efficiently working with query parameters in URLs.
Package queryparam provides utilities for efficiently working with query parameters in URLs.
Package sse provides utilities for working with Server Sent Events (SSE).
Package sse provides utilities for working with Server Sent Events (SSE).

Jump to

Keyboard shortcuts

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