broom

package module
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Jan 2, 2024 License: Apache-2.0 Imports: 29 Imported by: 0

README

Broom Build

Broom is an API client powered by OpenAPI.

Point it to an OpenAPI 3.0/3.1 spec, and it will provide a CLI for each defined operation. JSON output is colored and formatted, authentication is handled.

Install

go install github.com/bojanz/broom/cmd/broom@latest

or run make yourself inside the source directory, then copy the binary from bin/.

Usage

cd my-project/

# Generate a .broom.yaml with an "api" profile.
# See broom add --help for more examples.
broom add api openapi.yaml

# Run "broom" without arguments to get a list of profiles.
broom

# Specify a profile to get a list of operations.
broom api

# Run a specific operation.
broom api list-products

# Show the response code and headers.
broom api list-products -v

# Headers are passed via -H.
broom api list-products -H "X-MyHeader: Value" -H "X-Another: Value2"

# Optional parameters are passed via -q.
broom api list-products -q "filter[owner_id]=my-user&sort=-sku"

# Required parameters are passed directly.
broom api get-product 01FAZ7A1H11FW16WPQZP879YX3

# Request body parameters are passed via -b.
# The query string is auto-mapped to JSON if the service requires it.
broom api create-product -b "name=T-Shirt&price=999&currency_code=EUR"

# Get the list of all arguments and parameters via --help.
broom api create-product --help

Profiles

Broom allows creating multiple profiles for working with different environments, e.g. staging and production. Each profile has its own server url and authentication settings.

The auth type, API key header, and server url are auto-detected from the OpenAPI spec, when not provided via options.

cd my-project/
broom add prod openapi.json --auth=PRODUCTION_KEY
broom add staging openapi.json --auth=STAGING_KEY --server-url=htts://staging.my-api.io

# Proceed as usual.
broom prod list-products
broom staging list-products

Authentication

Broom supports authenticating using an API key, Basic auth, or a Bearer token.

Using an API key (X-API-Key header):

broom add api openapi.json --auth=MYKEY --auth-type=api-key

Using an API key (custom header):

broom add api openapi.json --auth=MYKEY --auth-type=api-key --api-key-header="X-MyApp-Key"

Using Basic auth:

broom add api openapi.json --auth="username:password" --auth-type=basic

Using a Bearer token:

broom add api openapi.json --auth=MYKEY --auth-type=bearer

For more advanced use cases, Broom supports fetching credentials through an external command:

    broom add api openapi.json --auth-cmd="sh get-token.sh" --auth-type=bearer

The external command can do a 2-legged OAuth request via curl, or it can retrieve an API key from a vault. It is run before each request to ensure freshness.

Name

Named after a curling broom, with bonus points for resembling the sound a car makes (in certain languages).

Alternatives

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Version = "dev"

Version is the current version, replaced at build time.

Functions

func AuthTypes added in v0.6.0

func AuthTypes() []string

AuthTypes returns a list of supported authentication types.

func Authenticate added in v0.6.1

func Authenticate(req *http.Request, cfg AuthConfig) error

Authenticate authenticates the given request.

func IsJSON

func IsJSON(mediaType string) bool

IsJSON checks whether the given media type matches a JSON format.

func LoadSpec added in v0.6.0

func LoadSpec(filename string) (v3.Document, error)

LoadSpec loads an OpenAPI 3.0/3.1 specification from disk.

func PrettyJSON

func PrettyJSON(json []byte) []byte

PrettyJSON pretty-prints the given JSON.

func RunCommand added in v0.6.0

func RunCommand(command string) (string, error)

RunCommand runs the given command and returns its output.

The command has access to environment variables.

func Sanitize

func Sanitize(s string) string

Sanitize sanitizes the given string, stripping HTML and trailing newlines.

func WriteConfig

func WriteConfig(filename string, cfg Config) error

WriteConfig writes the given config to the given filename.

Types

type AuthConfig added in v0.6.0

type AuthConfig struct {
	Credentials  string `yaml:"credentials"`
	Command      string `yaml:"command"`
	Type         string `yaml:"type"`
	APIKeyHeader string `yaml:"api_key_header"`
}

AuthConfig represents a profile's authentication configuration.

type Config

type Config map[string]ProfileConfig

Config represents Broom's configuration.

func ReadConfig

func ReadConfig(filename string) (Config, error)

ReadConfig reads a config file with the given filename.

func (Config) Profiles

func (c Config) Profiles() []string

Profiles returns a list of all configured profiles.

type Operation

type Operation struct {
	ID          string
	Summary     string
	Description string
	Tag         string
	Method      string
	Path        string
	Parameters  Parameters
	BodyFormat  string
	Deprecated  bool
}

Operation represents an available operation.

func (Operation) HasBody

func (op Operation) HasBody() bool

HasBody returns whether the operation has a body.

func (Operation) Request added in v0.7.0

func (op Operation) Request(serverURL string, values RequestValues) (*http.Request, error)

Request creates a new request with the given values.

func (Operation) SummaryWithFlags added in v0.6.1

func (op Operation) SummaryWithFlags() string

SummaryWithFlags returns the operation summary with flags.

func (Operation) Validate added in v0.7.0

func (op Operation) Validate(values RequestValues) error

Validate validates the given values against the operation's parameters.

type Operations

type Operations []Operation

Operations represents a list of operations.

func LoadOperations

func LoadOperations(filename string) (Operations, error)

LoadOperations loads available operations from a specification on disk.

func (Operations) ByID

func (ops Operations) ByID(id string) (Operation, bool)

ByID returns an operation with the given ID.

func (Operations) ByTag

func (ops Operations) ByTag(tag string) Operations

ByTag returns a list of operations for the given tag.

func (Operations) Tags

func (ops Operations) Tags() []string

Tags returns a list of all available operation tags.

type Parameter

type Parameter struct {
	In          string
	Name        string
	Description string
	Style       string
	Type        string
	Enum        []string
	Example     string
	Default     string
	Deprecated  bool
	Required    bool
}

Parameter represents an operation parameter.

func (Parameter) CastString

func (p Parameter) CastString(str string) (any, error)

CastString casts the given string to the parameter type.

func (Parameter) FormattedFlags added in v0.8.0

func (p Parameter) FormattedFlags() string

Flags returns the formatted parameter flags (deprecated, required).

func (Parameter) Label

func (p Parameter) Label() string

Label returns a human-readable parameter label.

type ParameterList added in v0.6.1

type ParameterList []Parameter

ParameterList represents a list of parameters.

func (ParameterList) ByName added in v0.6.1

func (pl ParameterList) ByName(name string) (Parameter, bool)

ByName returns a parameter with the given name.

type Parameters

type Parameters struct {
	Header ParameterList
	Path   ParameterList
	Query  ParameterList
	Body   ParameterList
}

Parameters represents the operation's parameters.

func (*Parameters) Add added in v0.6.1

func (ps *Parameters) Add(params ...Parameter)

Add adds one or more parameters to the appropriate parameter list.

type ProfileConfig

type ProfileConfig struct {
	SpecFile  string     `yaml:"spec_file"`
	ServerURL string     `yaml:"server_url"`
	Auth      AuthConfig `yaml:"auth"`
}

ProfileConfig represents Broom's per-profile configuration.

type RequestValues added in v0.7.0

type RequestValues struct {
	Header http.Header
	Path   []string
	Query  url.Values
	Body   url.Values
}

RequestValues represent the values used to populate an operation request.

Header, query, and body values are added to the request even if they don't have matching parameters, unlike path values, where the parameter is used to determine the name of the placeholder to replace.

func ParseRequestValues added in v0.7.0

func ParseRequestValues(headers []string, pathValues []string, query string, body string) (RequestValues, error)

ParseRequestValues parses parameter values from the given strings.

type Result

type Result struct {
	StatusCode int
	Output     string
}

Result represents the result of executing an HTTP request.

func Execute

func Execute(req *http.Request, verbose bool) (Result, error)

Execute performs the given HTTP request and returns the result.

The output consists of the request body (pretty-printed if JSON), and optionally the status code and headers (when "verbose" is true).

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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