• Stars
    star
    1,895
  • Rank 24,480 (Top 0.5 %)
  • Language
    Go
  • License
    MIT License
  • Created over 4 years ago
  • Updated 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Huma REST/HTTP API Framework for Golang with OpenAPI 3.1
Huma Logo

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 (including Go 1.22+), 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, header, or cookie)
    • Request body
    • Responses (including errors)
    • Response headers
  • JSON Errors using RFC9457 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 optionally 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.

Sponsors

A big thank you to our current & former sponsors:

Testimonials

This is by far my favorite web framework for Go. It is inspired by FastAPI, which is also amazing, and conforms to many RFCs for common web things ... I really like the feature set, the fact that it [can use] Chi, and the fact that it is still somehow relatively simple to use. I've tried other frameworks and they do not spark joy for me. - Jeb_Jenky

After working with #Golang for over a year, I stumbled upon Huma, the #FastAPI-inspired web framework. Itโ€™s the Christmas miracle Iโ€™ve been hoping for! This framework has everything! - Hana Mohan

I love Huma. Thank you, sincerely, for this awesome package. Iโ€™ve been using it for some time now and itโ€™s been great! - plscott

Thank you Daniel for Huma. Superbly useful project and saves us a lot of time and hassle thanks to the OpenAPI gen โ€” similar to FastAPI in Python. - WolvesOfAllStreets

Huma is wonderful, I've started working with it recently, and it's a pleasure, so thank you very much for your efforts ๐Ÿ™ - callmemicah

Install

Install via go get. Note that Go 1.20 or newer is required.

# 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/danielgtaylor/huma/v2/humacli"
	"github.com/go-chi/chi/v5"

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

// Options for the CLI. Pass `--port` or set the `SERVICE_PORT` env var.
type Options struct {
	Port int `help:"Port to listen on" short:"p" default:"8888"`
}

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

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

		// Add the operation handler to the API.
		huma.Get(api, "/greeting/{name}", func(ctx context.Context, input *struct{
			Name string `path:"name" maxLength:"30" example:"world" doc:"Name to greet"`
		}) (*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()
}

Tip

Replace chi.NewMux() โ†’ http.NewServeMux() and humachi.New โ†’ humago.New to use the standard library router from Go 1.22+. Just make sure your go.mod has go 1.22 or newer listed in it. Everything else stays the same! Switch whenever you are ready.

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.

Check out the Huma tutorial for a step-by-step guide to get started.

Documentation

See the https://huma.rocks/ website for full documentation in a presentation that's easier to navigate and search then this README. You can find the source for the site in the docs directory of this repo.

Official Go package documentation can always be found at https://pkg.go.dev/github.com/danielgtaylor/huma/v2.

Articles & Mentions

Be sure to star the project if you find it useful!

Star History Chart

More Repositories

1

aglio

An API Blueprint renderer with theme support that outputs static HTML
CoffeeScript
4,746
star
2

python-betterproto

Clean, modern, Python 3.6+ code generator & library for Protobuf 3 and async gRPC
Python
1,513
star
3

jpeg-archive

Utilities for archiving JPEGs for long term storage.
C
1,161
star
4

apisprout

Lightweight, blazing fast, cross-platform OpenAPI 3 mock server with validation
Go
639
star
5

restish

Restish is a CLI for interacting with REST-ish HTTP APIs with some nice features built-in
Go
497
star
6

qtfaststart

Quicktime atom positioning in Python for fast streaming
Python
450
star
7

nesh

An enhanced, extensible interactive shell for Node.js and CoffeeScript
CoffeeScript
287
star
8

openapi-cli-generator

Generate a CLI from an OpenAPI 3 specification
Go
154
star
9

arista

Arista Transcoder
Python
120
star
10

ladon

A small, simple cross-platform utility to process many files in parallel.
JavaScript
81
star
11

braintree_django

Braintree Django Module
Python
52
star
12

atom-api-blueprint-preview

Live preview API Blueprint in Atom
CoffeeScript
45
star
13

html5-space-fighter

HTML5 Space Fighter Game
JavaScript
30
star
14

apilint

Extensible REST API linter utility
JavaScript
27
star
15

malt.io

Malt.io free community for brewers
Python
26
star
16

qtrotate

Tools for handling rotated Quicktime/MP4 files
Python
26
star
17

qtfaststart.js

Javascript version of qt-faststart
JavaScript
21
star
18

guid-tool-web

GUID conversion tool website
Python
18
star
19

atom-language-api-blueprint

API Blueprint and MSON grammars for the Atom.io text editor.
CoffeeScript
14
star
20

django-ccss

Django CleverCSS
Python
13
star
21

tech-talk

Markdown slideshows with a built-in terminal that just works
JavaScript
13
star
22

mexpr

Micro expression parser library for Go
Go
12
star
23

node-desktop-uploader

Recursively watch directories and upload new/updated files
CoffeeScript
11
star
24

shorthand

Structured data & CLI shorthand syntax for Go
Go
10
star
25

atom-monokai-extended

Extended Monokai theme for the Atom text editor
CSS
9
star
26

unistyle

โ„ฑ๐’ถ๐“ƒ๐’ธ๐“Ž ๐˜๐—ฒ๐˜…๐˜ ๐˜ด๐˜ต๐˜บ๐˜ญ๐˜ฆ๐˜ด ๐”ฃ๐”ฌ๐”ฏ Gฬณoฬณlฬณaฬณnฬณgฬณ in a compact, zero dependency library.
Go
7
star
27

guid-tool

A tool to convert between various forms of GUID
Python
7
star
28

ffmpeg

FFmpeg + patches
C
7
star
29

eidolon

Generate JSON or JSON Schema from Refract & MSON data structures
CoffeeScript
6
star
30

paodate

Simpler Python date handling
Python
5
star
31

mateo

A simple API description interface library
JavaScript
5
star
32

sdt

Structured Data Templates
Go
4
star
33

peasant

An opinionated Node.js ES6 module lint/build/test/coverage helper
JavaScript
3
star
34

dotfiles

My public dotfiles to help bootstrap a new machine
Shell
3
star
35

polaris

Lightweight backend utilities for static websites
CoffeeScript
3
star
36

apiscrub

OpenAPI Scrubber
Python
3
star
37

bible-ref

Utilities for handling Bible references
CoffeeScript
2
star
38

homebrew-restish

Homebrew Tap for Restish https://rest.sh/
Ruby
2
star
39

casing

An intelligent casing conversion library for Go
Go
2
star
40

injectobot

Developer-friendly programmable IRC bot
CoffeeScript
2
star
41

huma-build

Docker build utility for Huma REST OpenAPI projects
Go
2
star
42

rhs-color

R.H.S. color conversion utilities
JavaScript
2
star
43

apibin

Example API with modern features
Go
2
star
44

nesh-hello

A simple example plugin for Nesh, the Node.js enhanced shell.
JavaScript
1
star
45

arista-website

Arista Transcoder Website
JavaScript
1
star
46

gaaflora-website

http://www.gaaflora.com/
HTML
1
star
47

vscode-sdt

Visual Studio Code support for Structured Data Templates
JavaScript
1
star