Documentation
¶
Overview ¶
Package pixlub is the official Go client for the Pixlub API.
import pixlub "github.com/pixlub/pixlub-go"
client, err := pixlub.NewClient() // reads PIXLUB_API_KEY
if err != nil {
log.Fatal(err)
}
result, err := client.Tools.Run(ctx, "removeBgApi", pixlub.RunRequest{
Image: pixlub.FromPath("photo.jpg"),
})
if err != nil {
log.Fatal(err)
}
if err := result.Save("photo-nobg"+result.Extension(), false); err != nil {
log.Fatal(err)
}
A Client is safe for concurrent use: create one and reuse it. Large files are uploaded automatically, and long runs are awaited until WithJobTimeout. Arguments are checked before anything is sent, so a mistake costs nothing.
Index ¶
- Constants
- Variables
- type APIError
- type Client
- type ConnectionError
- type ListOptions
- type Option
- type Output
- type Result
- type RunRequest
- type Source
- type Tool
- type ToolInput
- type ToolOutput
- type Tools
- func (t *Tools) List(ctx context.Context, opts ListOptions) ([]Tool, error)
- func (t *Tools) Retrieve(ctx context.Context, id string) (*Tool, error)
- func (t *Tools) Run(ctx context.Context, id string, req RunRequest) (*Result, error)
- func (t *Tools) Schema(ctx context.Context, id string) (map[string]any, error)
Constants ¶
const ( // APIKeyEnv is the environment variable read when no key is passed. APIKeyEnv = "PIXLUB_API_KEY" // BaseURLEnv is the environment variable read when no base URL is passed. BaseURLEnv = "PIXLUB_BASE_URL" // DefaultBaseURL is used when neither WithBaseURL nor BaseURLEnv is set. DefaultBaseURL = "https://api.pixlub.com" )
const DirectUploadMaxBytes = 90 << 20
DirectUploadMaxBytes is the largest total of files sent in one request. Larger files are uploaded automatically.
const Version = "0.3.0"
Version is the version of this SDK. It is sent in the User-Agent header.
Variables ¶
var ( // ErrConfiguration means the API key or base URL is missing or invalid. // Nothing was sent. ErrConfiguration = errors.New("pixlub: configuration error") // ErrInvalidInput means an argument was refused locally. Nothing was sent. ErrInvalidInput = errors.New("pixlub: invalid input") // ErrUnknownTool means the tool id is not in the catalog. It also matches // ErrInvalidInput. ErrUnknownTool = fmt.Errorf("%w: unknown tool", ErrInvalidInput) // ErrFileTooLarge means a file is too large, locally or for the tool or your // plan (HTTP 413, see APIError.MaxBytes). ErrFileTooLarge = errors.New("pixlub: file too large") // ErrNoData means the run produced no data output. ErrNoData = errors.New("pixlub: the run produced no data output") // ErrConnection means the API could not be reached, or the connection broke. ErrConnection = errors.New("pixlub: connection error") // ErrTimeout means the API did not answer in time. It also matches ErrConnection. ErrTimeout = fmt.Errorf("%w: timeout", ErrConnection) // ErrJobTimeout means a long run did not finish within the job timeout (see // WithJobTimeout). The run was accepted and may have been charged. It also // matches ErrTimeout. ErrJobTimeout = fmt.Errorf("%w: the job did not finish in time", ErrTimeout) // ErrUnexpectedResponse means the answer of the API could not be read. ErrUnexpectedResponse = errors.New("pixlub: unexpected response") // ErrAPI means the API answered with an error status. Every error below // matches it. ErrAPI = errors.New("pixlub: API error") // ErrInvalidRequest matches HTTP 4xx answers, such as invalid settings. ErrInvalidRequest = fmt.Errorf("%w: invalid request", ErrAPI) // ErrAuthentication matches HTTP 401: the key is unknown or revoked. ErrAuthentication = fmt.Errorf("%w: authentication failed", ErrAPI) // ErrPermissionDenied matches HTTP 403: the key is valid, but the account // may not do this, for example on a free plan. ErrPermissionDenied = fmt.Errorf("%w: permission denied", ErrAPI) // ErrNotFound matches HTTP 404. ErrNotFound = fmt.Errorf("%w: not found", ErrAPI) // ErrInsufficientCredits matches HTTP 402: not enough credits for the tool. ErrInsufficientCredits = fmt.Errorf("%w: insufficient credits", ErrAPI) // ErrRateLimited matches HTTP 429: too many requests. It is never charged. ErrRateLimited = fmt.Errorf("%w: rate limited", ErrAPI) // ErrServer matches HTTP 5xx: something failed on the server side. ErrServer = fmt.Errorf("%w: server error", ErrAPI) )
Sentinel errors: test them with errors.Is, and read details with errors.As into *APIError or *ConnectionError.
Functions ¶
This section is empty.
Types ¶
type APIError ¶
type APIError struct {
// HTTPStatus is the HTTP status code of the answer.
HTTPStatus int
// Code is the machine-readable code, such as "insufficient_credits", or "".
Code string
// Message is the message of the API.
Message string
// Details lists the invalid settings of an HTTP 400 answer, or is nil.
Details any
// RequiredCredits is the cost of the run (HTTP 402), or nil.
RequiredCredits *int64
// MaxBytes is the largest file accepted (HTTP 413), or nil.
MaxBytes *int64
// MaxPixels is the largest image accepted (Code "image_too_large"), or nil.
MaxPixels *int64
// Limit is the limit that was reached, such as the files of a batch for your
// plan (Code "batch_limit"), or nil.
Limit *int64
// ResetAt is when a quota resets, when the API says so. It is zero otherwise.
ResetAt time.Time
// RetryAfter is how long to wait before trying again, or zero.
RetryAfter time.Duration
// JobID is the id of the long run that failed, or "".
JobID string
// contains filtered or unexported fields
}
APIError is an error answer of the API.
type Client ¶
type Client struct {
// Tools lists, describes and runs tools.
Tools *Tools
// contains filtered or unexported fields
}
Client talks to the Pixlub API. Create one with NewClient and reuse it. It is safe for concurrent use.
type ConnectionError ¶
type ConnectionError struct {
// Message explains the failure.
Message string
// RequestSent is true when the run may have been charged: check your
// balance before running it again.
RequestSent bool
// contains filtered or unexported fields
}
ConnectionError means no usable answer came from the API.
func (*ConnectionError) Error ¶
func (e *ConnectionError) Error() string
func (*ConnectionError) Unwrap ¶
func (e *ConnectionError) Unwrap() error
Unwrap returns ErrConnection or ErrTimeout.
type ListOptions ¶
type ListOptions struct {
// ExecutableOnly leaves out tools that cannot be run through the API.
ExecutableOnly bool
}
ListOptions filters the result of Tools.List.
type Option ¶
type Option func(*settings)
Option configures a Client. Pass options to NewClient.
func WithAPIKey ¶
WithAPIKey sets the API key. The default is PIXLUB_API_KEY.
func WithBaseURL ¶
WithBaseURL sets the address of the API. The default is PIXLUB_BASE_URL, then https://api.pixlub.com. Plain http is accepted only for localhost.
func WithHTTPClient ¶
WithHTTPClient uses this *http.Client, for proxies or custom TLS settings. Its timeout, if any, becomes the default of WithTimeout.
func WithJobTimeout ¶
WithJobTimeout sets how long Run waits for a long run. The default is 30 minutes. After that, Run fails with ErrJobTimeout: the run may still finish, and may have been charged.
func WithMaxInputBytes ¶
WithMaxInputBytes sets the largest local file accepted. The default is 3 GiB.
func WithMaxRetries ¶
WithMaxRetries sets how many times a request is retried, from 0 to 5. The default is 2. A request that may have been charged is never retried.
func WithTimeout ¶
WithTimeout sets how long one request may wait. The default is five minutes. Use the context of each call to bound the whole call.
type Output ¶
type Output struct {
// Key is the tool output (see Tool.Outputs), such as "out". In a batch it
// ends with the rank of the file: "out#0", "out#1"...
Key string
// Name is "image" (the produced image), "data" (JSON) or "file" (another format, such as a PDF).
Name string
// URL is the download link, valid for one hour.
URL string
// ContentType is the media type of Content, such as "image/png".
ContentType string
// Bytes is the size of the file, len(Content).
Bytes int64
// Content holds the bytes of the file.
Content []byte
}
Output is one file of a run, already downloaded.
type Result ¶
type Result struct {
// Module is the id of the tool that ran.
Module string
// ID identifies the run. Quote it when you contact support.
ID string
// JobID identifies a long run, or is empty.
JobID string
// Outputs lists every file of the run, in the order the API gave them.
Outputs []Output
// ExpiresAt is when the download links expire.
ExpiresAt time.Time
// Cost is the number of credits the run charged, when the API reports it.
Cost *int64
// CreditsBalance is what is left on the account after the run, when reported.
CreditsBalance *int64
// Message is an optional note from the tool, such as a warning about the result.
Message string
}
Result is what a run produced. Outputs lists every file, already downloaded.
func (*Result) Data ¶
Data decodes the "data" output as JSON into v. It fails with ErrNoData when the tool returned no data.
func (*Result) Extension ¶
Extension returns the file extension of the produced file, such as ".png" or ".webp" (removeBgApi), or ".json" when the run produced only data.
func (*Result) File ¶
File returns the produced file: the image, or else the first output that is not data. It returns nil when the run produced neither.
func (*Result) Image ¶
Image returns the bytes of the produced file, or nil when the tool only returns data.
type RunRequest ¶
type RunRequest struct {
// Image is the file of a tool that takes one input.
Image Source
// Inputs gives one file per input name.
Inputs map[string]Source
// InputLists gives several files per input name, for inputs that take
// several (ToolInput.Multiple), up to ToolInput.MaxFiles each, and 64 files
// per run in all. A name may be in Inputs or in InputLists, not in both.
InputLists map[string][]Source
Params map[string]any
}
RunRequest describes one run. Set Image for a tool with a single input, or Inputs and InputLists for inputs keyed by name (see Tool.Inputs). Params holds the tool's settings, as JSON values (see Tools.Schema).
type Source ¶
type Source struct {
// contains filtered or unexported fields
}
Source is one input file. Build it with FromPath, FromBytes, FromReader, FromReaderSize or FromURL. The zero value means "not set".
func FromReader ¶
FromReader sends everything reader returns. name is optional. A reader that cannot seek is copied first; use FromPath for a file on disk.
func FromReaderSize ¶
FromReaderSize sends exactly size bytes read from reader. name is optional.
type Tool ¶
type Tool struct {
// ID is the identifier to pass to Tools.Run, such as "removeBgApi".
ID string
Name string
Description string
Category string
// Executable is false when the tool cannot be run through the API.
Executable bool
// Handler is "local", "remote" or "none".
Handler string
// Inputs lists the file inputs. Pass them by name with RunRequest.Inputs,
// or RunRequest.InputLists for several files.
Inputs []ToolInput
// Outputs lists the files a run may produce, by key (see Output.Key).
Outputs []ToolOutput
}
Tool is a tool of the catalog returned by Tools.List.
type ToolInput ¶
type ToolInput struct {
// ID is the name to use as a key of RunRequest.Inputs or RunRequest.InputLists.
ID string
Label string
Description string
// Required is true when the tool cannot run without this input.
Required bool
// Type is "image", "channel" (read as grayscale), "batch" or another kind
// of file the tool reads. A palette is not a file: its colors go in Params.
Type string
// Multiple is true when the input takes several files: pass them with
// RunRequest.InputLists.
Multiple bool
// PerFile is true when each file of the input is a run of its own, charged
// on its own: a batch. Its outputs are keyed by rank, such as "out#0".
PerFile bool
// MaxFiles is the most files the input takes in one run, for your plan, or 0.
MaxFiles int
// Accept lists the media types the input takes, such as "image/png".
Accept []string
}
ToolInput is one file input of a tool.
type ToolOutput ¶
type ToolOutput struct {
// Key identifies the output in Result.Outputs (Output.Key). In a batch,
// each file is keyed with its rank: "out#0", "out#1"...
Key string
Label string
Description string
// Kind is the kind of file, such as "image" or "data".
Kind string
// Multiple is true when a run may produce several files for this key.
Multiple bool
// ContentTypes lists the media types the output may have.
ContentTypes []string
}
ToolOutput is one kind of file a tool produces.
type Tools ¶
type Tools struct {
// contains filtered or unexported fields
}
Tools lists, describes and runs tools. Access it as client.Tools.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
quickstart
command
Command quickstart lists the tools of the Pixlub API, and runs one on an image.
|
Command quickstart lists the tools of the Pixlub API, and runs one on an image. |