Claude API Golang Client Library: Setup & Example
If you're building a backend in Go and want to call Claude, the short answer is: there is no official Anthropic Go SDK. Anthropic maintains first-party libraries for Python and TypeScript, but Go developers have to either use a community-maintained wrapper or talk to the HTTP API directly. Both are straightforward because the Claude API is a plain JSON-over-HTTPS REST API — there's nothing Go-specific blocking you.
This article shows exactly how to build a minimal, production-usable Go client for Claude, including request/response structs, streaming via Server-Sent Events, and tool use. It also covers the community library options so you can decide whether to roll your own or depend on a third party.
Why there's no official Go SDK
Anthropic prioritizes Python and JavaScript/TypeScript for official tooling because that's where most LLM app development happens. Go is common for backend services, CLIs, and infrastructure, but Anthropic hasn't shipped a go-anthropic package. A few community projects exist on GitHub (search "anthropic-sdk-go" or similar), but they vary in maintenance quality, and pulling in a third-party dependency for something this simple is often unnecessary.
Because the API itself is just HTTP + JSON, writing your own thin client takes under 100 lines and gives you full control over timeouts, retries, and error handling — which matters more in Go backends than in scripting languages.
Minimal Go client for the Messages API
Here's a self-contained client that sends a request to the /v1/messages endpoint and decodes the response:
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
type Message struct {
Role string `json:"role"`
Content string `json:"content"`
}
type MessagesRequest struct {
Model string `json:"model"`
MaxTokens int `json:"max_tokens"`
Messages []Message `json:"messages"`
}
type MessagesResponse struct {
ID string `json:"id"`
Content []struct {
Type string `json:"type"`
Text string `json:"text"`
} `json:"content"`
Usage struct {
InputTokens int `json:"input_tokens"`
OutputTokens int `json:"output_tokens"`
} `json:"usage"`
}
func main() {
reqBody := MessagesRequest{
Model: "claude-3-5-sonnet-20241022",
MaxTokens: 1024,
Messages: []Message{
{Role: "user", Content: "Explain Go channels in two sentences."},
},
}
payload, _ := json.Marshal(reqBody)
req, _ := http.NewRequest("POST", "https://api.anthropic.com/v1/messages", bytes.NewBuffer(payload))
req.Header.Set("content-type", "application/json")
req.Header.Set("x-api-key", os.Getenv("ANTHROPIC_API_KEY"))
req.Header.Set("anthropic-version", "2023-06-01")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var result MessagesResponse
json.Unmarshal(body, &result)
for _, block := range result.Content {
fmt.Println(block.Text)
}
}
This is the whole shape of the pattern: build a struct, marshal it, set three headers, send, decode. You can wrap this in a small package with a Client struct holding the API key and base URL, and add typed methods per endpoint as needed.
Streaming in Go
Claude's streaming responses are Server-Sent Events. Go's net/http doesn't parse SSE natively, so you read the response body line by line and split on data: prefixes:
req.Header.Set("accept", "text/event-stream")
// add "stream": true to the request body
resp, _ := client.Do(req)
scanner := bufio.NewScanner(resp.Body)
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "data: ") {
var event map[string]interface{}
json.Unmarshal([]byte(line[6:]), &event)
if event["type"] == "content_block_delta" {
delta := event["delta"].(map[string]interface{})
fmt.Print(delta["text"])
}
}
}
This gives you token-by-token output in a CLI tool or server-sent response to your own frontend. It's a bit more manual than the Python/TS SDKs, which abstract the event parsing, but it's not complicated once you've seen the event shape once.
Handling tool use in Go
Tool calls come back as content blocks with type: "tool_use", containing a name and input object. In Go you'll typically decode into map[string]interface{} or a more specific struct per tool, execute the function, then send a follow-up request with a tool_result block. The logic is identical to any other language — only the decoding syntax changes.
When a raw client isn't worth maintaining
Writing your own Go client is fine for a single service, but it gets tedious once you need retries, rate-limit backoff, streaming reconnects, per-key usage tracking, and multiple team members hitting the same Claude access from different services. That's the maintenance burden a lot of teams underestimate.
SubToAPI sits in front of Claude and exposes the same request/response shape over HTTPS, so your existing Go struct definitions above work unchanged — you just point at a different host and use a sub_live_... key instead of your raw Anthropic key:
req.Header.Set("Authorization", "Bearer "+os.Getenv("SUBTOAPI_KEY"))
req, _ = http.NewRequest("POST", "https://api.subtoapi.app/v1/messages", bytes.NewBuffer(payload))
You get streaming, tool use, and usage metadata the same way (see the messages docs, streaming docs, and tools docs), plus per-key usage visibility and team seats in a dashboard rather than one shared Anthropic key passed around in environment variables. There's a free trial at /signup and plans starting at €9/month on the pricing page if that fits your setup better than managing raw Anthropic credentials across services.
Recommended approach
- For a single internal tool: write the ~100-line raw HTTP client shown above. No dependency, full control.
- For a growing team with multiple services calling Claude: wrap the client in an internal package, add retry/backoff with exponential jitter, and centralize key management.
- For multi-key, multi-team setups: route through a layer like SubToAPI so each Go service gets its own key, scoped usage tracking, and you avoid building billing/seat logic yourself. Start at /docs/quickstart to see the exact request format.
Is there an official Anthropic Go SDK?
No. Anthropic officially supports Python and TypeScript. For Go, you either use a community-maintained package or call the REST API directly with net/http, which is only a few dozen lines of code as shown above.
How do I handle streaming responses in Go?
Set stream: true in the request body and accept: text/event-stream in the headers, then read the response body with bufio.Scanner, parsing lines prefixed with data: as JSON events and extracting content_block_delta text fields.
Can I use the same Go code against SubToAPI instead of raw Anthropic?
Yes. The request and response JSON shapes match, so you only change the base URL to https://api.subtoapi.app/v1/... and the Authorization: Bearer sub_live_... header — your structs and parsing logic stay the same.