The official Go SDK for the ChartQuery chart and QR code API.
Generate chart images, diagrams, barcodes, QR codes and thermal labels on demand. PNG, SVG or PDF output.
The SDK exposes 20 typed methods, one per documented endpoint, plus a generic Request(). It has no dependencies outside the standard library.
- Go 1.22 or newer
go get github.com/chartquery/chartquery-goSign up for ChartQuery or sign in, then copy your API key from the dashboard. NewClient("", nil) reads the CHARTQUERY_API_KEY environment variable.
package main
import (
"context"
"fmt"
"log"
"github.com/chartquery/chartquery-go"
)
func main() {
client, err := chartquery.NewClient("", nil) // reads CHARTQUERY_API_KEY
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
response, err := client.ChartAI(ctx, &chartquery.ChartAIParams{Prompt: "Monthly revenue 2026 as a bar chart: Jan 10, Feb 14, Mar 18"})
if err != nil {
log.Fatal(err)
}
data, err := response.Map()
if err != nil {
log.Fatal(err)
}
fmt.Println(data)
}Parameter structs mirror the API reference. Required fields are plain values; optional fields are pointers — use chartquery.String, chartquery.Float, chartquery.Int and chartquery.Bool.
Decode into your own types with response.Decode(&value).
Endpoints that return a file (image, PDF…) give you the bytes in Body; IsJSON tells both cases apart:
response, err := client.Qrcode(ctx, &chartquery.QrcodeParams{Data: "https://chartquery.com", Format: chartquery.String("png")})
if err != nil {
log.Fatal(err)
}
if !response.IsJSON {
err = os.WriteFile("qrcode.png", response.Body, 0o644)
}Any call accepts is_async: true (useful past the 60-second server limit): the response is then a job_id. WaitForJob polls GET /v1/jobs/{id} until a terminal status (CompletedJob, Error, NotFound, BadRequest):
submitted, err := client.ChartAI(ctx, &chartquery.ChartAIParams{Prompt: "Monthly revenue 2026 as a bar chart: Jan 10, Feb 14, Mar 18", IsAsync: chartquery.Bool(true)})
if err != nil {
log.Fatal(err)
}
var accepted struct{ JobID string `json:"job_id"` }
if err := submitted.Decode(&accepted); err != nil {
log.Fatal(err)
}
job, err := client.WaitForJob(ctx, accepted.JobID, &chartquery.WaitForJobOptions{
OnProgress: func(job map[string]any) { fmt.Println(job["status"], job["progress"]) },
})Methods use GET when the endpoint supports it (parameters in the query string); WithMethod("POST") sends them as a JSON body.
response, err := client.Barcode(ctx, &chartquery.BarcodeParams{Data: "test"}, chartquery.WithMethod("POST"))response, err := client.Request(ctx, "GET", "/v1/usage", nil)response, err := client.ChartAI(ctx, &chartquery.ChartAIParams{Prompt: "Monthly revenue 2026 as a bar chart: Jan 10, Feb 14, Mar 18"})
if apiError, ok := chartquery.IsAPIError(err); ok {
log.Printf("HTTP %d: %s", apiError.StatusCode, apiError.Message)
}| Error | When |
|---|---|
*ConfigurationError |
Missing API key, invalid options or unsupported method. |
*SerializationError |
A required parameter is missing or a value can't be sent. |
*TransportError |
Network failure, timeout or cancelled context (errors.Is(err, context.DeadlineExceeded)). |
*APIError |
Non-2xx status (StatusCode, Message, Response). |
*ResponseDecodingError |
A success response could not be decoded. |
Requests are retried up to 3 times after a network error, a 408, 500, 502, 503 or 504, or a rate limit — which the API returns as 401 (or 429) with a Rate limit exceeded message. Per-key quota errors (…: quota daily) are not retried, nor are 400, 402, 404 or client-side timeouts. The delay starts at 1 second and grows 1.5× per retry (capped at 30 seconds); a Retry-After header wins.
client, err := chartquery.NewClient("", &chartquery.ClientOptions{
MaxRetries: 5, // negative disables retries
RetryDelay: 500 * time.Millisecond,
})
// or for one request
response, err := client.ChartAI(ctx, &chartquery.ChartAIParams{Prompt: "Monthly revenue 2026 as a bar chart: Jan 10, Feb 14, Mar 18"}, chartquery.WithMaxRetries(0))chartquery.Batch runs a function per item with at most 10 calls in flight and returns one BatchResult per item, in input order. A failing item never stops the others.
inputs := []string{"Monthly revenue 2026 as a bar chart: Jan 10, Feb 14, Mar 18", "Market share as a pie chart: A 40, B 35, C 25"}
results := chartquery.Batch(ctx, inputs, 5, func(ctx context.Context, value string) (*chartquery.Response, error) {
return client.ChartAI(ctx, &chartquery.ChartAIParams{Prompt: value})
})
for _, result := range results {
if result.Err != nil {
log.Printf("%s: %v", inputs[result.Index], result.Err)
continue
}
fmt.Println(string(result.Value.Body))
}| Constant | Default | Description |
|---|---|---|
DefaultConcurrency |
10 |
Tasks run at the same time by batch |
DefaultTimeout |
120 * time.Second |
Request timeout |
MaxRetries |
3 |
Retry attempts after a network error, a 408/5xx or a rate limit |
RetryBackoffFactor |
1.5 |
Exponential backoff multiplier |
DefaultRetryDelay |
time.Second |
Delay before the first retry |
client, err := chartquery.NewClient("", &chartquery.ClientOptions{
Timeout: 60 * time.Second, // default 120 s; negative disables
HTTPClient: &http.Client{Transport: myTransport},
})Every method also honours the deadline and cancellation of the context.Context you pass.
20 methods, generated from the OpenAPI document.
| Method | HTTP | Description |
|---|---|---|
Barcode |
GET / POST /v1/barcode |
Generate a barcode image via GET. Output: SVG (default) or PNG. Supports 25+ formats: EAN-13, Code 128, ITF-14, GS1-128, postal codes and m… |
Chart |
GET / POST /v1/chart |
Render a Chart.js image via GET. Pass the full chart object as URL-encoded JSON in query. Prefer format png for ChatGPT. POST sends the sam… |
ChartAI |
GET / POST /v1/chart/ai |
Describe a chart in plain English via GET and get a rendered image back. Powered by AI. |
ChartRender |
GET /v1/chart/render/{id} |
Render a previously saved chart by ID. Public, no API key required. Supports URL overrides for templates (?data1=, ?labels=, ?title=…). |
ChartView |
GET /v1/chart/view/{id} |
View a previously saved chart as an interactive HTML page. Public, no API key required. Iframe-embeddable. |
Diagram |
GET / POST /v1/diagram |
Render a diagram via GET. Use type (mermaid, d2, …), query (source code), and format=png for ChatGPT. POST uses diagram_type and diagram_so… |
DiagramAI |
GET / POST /v1/diagram/ai |
Describe a diagram in plain English via GET and get a rendered image back. Powered by AI. |
DiagramRender |
GET /v1/diagram/render/{id} |
Render a previously saved diagram by ID. Public, no API key required. Supports ?format= and ?query= overrides. |
DiagramView |
GET /v1/diagram/view/{id} |
View a previously saved diagram as an HTML page. Public, no API key required. Iframe-embeddable with inline SVG rendering. |
Jobs |
GET /v1/jobs/{id} |
Poll the status, progress (0–100) and result of a job started with is_async=true. Polling is free. Poll until status is terminal: Completed… |
Label |
GET / POST /v1/label |
Preview a thermal label via GET. Pass the same label object as a URL-encoded JSON string in query. Inside that JSON, text items use content… |
LabelCompile |
POST /v1/label/compile |
Compile a label to printer commands (tsc, zpl, epl, …). POST width, language, and elements. Text uses content and size (1-10), not text or… |
LabelConvert |
POST /v1/label/convert |
Convert printer commands from one language to another. POST source, from, and to. from is the source language (tsc, zpl, epl, …). to is the… |
LabelParse |
POST /v1/label/parse |
Parse printer commands into structured elements. POST source and language (tsc, zpl, epl, …). |
LabelRender |
GET /v1/label/render/{id} |
Render a previously saved label by ID. Public, no API key required. Supports ?format= override. |
LabelValidate |
POST /v1/label/validate |
Validate printer commands. POST source (the raw commands) and language (tsc, zpl, epl, …). |
LabelView |
GET /v1/label/view/{id} |
View a previously saved label as an HTML page. Public, no API key required. Iframe-embeddable with inline SVG rendering. |
Qrcode |
GET / POST /v1/qrcode |
Generate a styled QR code via GET. Output: SVG (default) or PNG. Supports dot styles, gradients, custom corners and all QR versions. |
Stats |
GET /v1/stats |
Infrastructure health for an engine or endpoint over the last hour. Not scoped to your account or tenant. Enabled per account: HTTP 403 mea… |
Usage |
GET /v1/usage |
Return this account's Chartquery usage and credit balance. No body. Requires an API key. |
| SDK | Package | Install |
|---|---|---|
| Node.js | @chartquery/sdk |
npm install @chartquery/sdk |
| Python | chartquery |
pip install chartquery |
| Go | chartquery-go |
go get github.com/chartquery/chartquery-go |
| .NET | ChartQuery |
dotnet add package ChartQuery |
| Ruby | chartquery |
gem install chartquery |
| PHP | chartquery/sdk |
composer require chartquery/sdk |
| Java | chartquery-java |
build from source, see its README |
| CLI | @chartquery/cli |
npm install -g @chartquery/cli |
| MCP server | @chartquery/mcp |
npx -y @chartquery/mcp |
MIT — see LICENSE.