api

package
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package api calls a JSON server — a Nimbus app — with typed endpoints. Declare each endpoint once, in a package both the server and the app import, and every call is checked by the compiler on both sides:

// shared/api.go
var ListOrders  = api.GET[ListOrdersReq, []Order]("/api/orders")
var GetOrder    = api.GET[OrderRef, Order]("/api/orders/{id}")
var CreateOrder = api.POST[NewOrder, Order]("/api/orders")

// in the app
client := api.New("https://example.com")
orders, err := api.Call(ctx, client, ListOrders, ListOrdersReq{Status: "paid"})

The package depends only on the standard library, so it is safe to import from shared code that also builds into the app.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Call

func Call[Req, Resp any](ctx context.Context, c *Client, e Endpoint[Req, Resp], req Req) (Resp, error)

Call sends req to the endpoint and decodes the response. GET and DELETE send the request as query parameters (by json name, without the path parameters); the others as a JSON body — tag path fields json:"-" to keep them out of it.

Types

type Client

type Client struct {
	BaseURL string
	HTTP    *http.Client
	// Token, when set, is sent as "Authorization: Bearer <token>" (e.g. a
	// Nimbus session or API token).
	Token func() string
	// Header adds headers to every request.
	Header http.Header
}

Client sends requests to one server.

func New

func New(baseURL string) *Client

New is a client for the server at baseURL, with a 30-second timeout.

type Endpoint

type Endpoint[Req, Resp any] struct {
	Method string
	Path   string
}

Endpoint is one route: its method and path, and the Go types of its request and response. Path parameters are written {name} and filled from the request field tagged `path:"name"`.

func DELETE

func DELETE[Req, Resp any](path string) Endpoint[Req, Resp]

func GET

func GET[Req, Resp any](path string) Endpoint[Req, Resp]

func PATCH

func PATCH[Req, Resp any](path string) Endpoint[Req, Resp]

func POST

func POST[Req, Resp any](path string) Endpoint[Req, Resp]

func PUT

func PUT[Req, Resp any](path string) Endpoint[Req, Resp]

type Error

type Error struct {
	Status  int
	Message string
	Fields  map[string][]string
	Body    []byte
}

Error is a response with a non-2xx status. Fields holds a Nimbus 422's validation errors, so ui.FieldErrorsOf(err) puts them on a form.

func (*Error) Error

func (e *Error) Error() string

func (*Error) ToMap

func (e *Error) ToMap() map[string][]string

ToMap returns the field errors (the shape Nimbus validation uses).

type None

type None struct{}

None is the request or response type of an endpoint that has none.

Jump to

Keyboard shortcuts

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