Claude API Golang Integration Example: Full Walkthrough
If you're searching for a Claude API Golang integration example, you're probably trying to figure out how to call Anthropic's models from a Go service without pulling in a heavy SDK or fighting with undocumented response shapes. This article walks through a minimal, production-ready Go client for the Claude API: making requests, handling streaming responses, parsing errors, and structuring the code so it's reusable across a codebase.
Go doesn't have an official first-party Anthropic SDK with the same maturity as the Python or TypeScript ones, so most Go teams either write a thin HTTP wrapper themselves or use a third-party package. We'll build the wrapper from scratch using only net/http and the standard library, which is enough for most use cases and gives you full control over timeouts, retries, and logging.
Setting Up the Project
Start with a standard Go module:
go mod init claude-client
You'll need an API key. If you're calling Anthropic directly, that's your ANTHROPIC_API_KEY. If you're going through SubToAPI to get a single HTTPS endpoint with usage metadata, team seats, and streaming already handled, your key will look like sub_live_... — same request shape, different base URL.
export CLAUDE_API_KEY=sub_live_xxxxxxxxxxxx
Basic Request Struct
Claude's Messages API expects a JSON body with a model, a list of messages, and a max token count. Define Go structs that mirror this:
package claude
type Message struct {
Role string `json:"role"`
Content string `json:"content"`
}
type Request struct {
Model string `json:"model"`
MaxTokens int `json:"max_tokens"`
Messages []Message `json:"messages"`
Stream bool `json:"stream,omitempty"`
}
type Response 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"`
}
Making a Non-Streaming Call
package claude
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"time"
)
const baseURL = "https://api.subtoapi.app/v1/messages"
func Send(req Request) (*Response, error) {
body, err := json.Marshal(req)
if err != nil {
return nil, fmt.Errorf("marshal request: %w", err)
}
httpReq, err := http.NewRequest("POST", baseURL, bytes.NewReader(body))
if err != nil {
return nil, fmt.Errorf("build request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("Authorization", "Bearer "+os.Getenv("CLAUDE_API_KEY"))
client := &http.Client{Timeout: 60 * time.Second}
resp, err := client.Do(httpReq)
if err != nil {
return nil, fmt.Errorf("send request: %w", err)
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("read response: %w", err)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("api error: status %d: %s", resp.StatusCode, string(data))
}
var out Response
if err := json.Unmarshal(data, &out); err != nil {
return nil, fmt.Errorf("unmarshal response: %w", err)
}
return &out, nil
}
Calling it is straightforward:
func main() {
resp, err := claude.Send(claude.Request{
Model: "claude-3-5-sonnet-latest",
MaxTokens: 1024,
Messages: []claude.Message{
{Role: "user", Content: "Summarize this error log in one sentence."},
},
})
if err != nil {
panic(err)
}
for _, block := range resp.Content {
fmt.Println(block.Text)
}
}
This same pattern works whether you're hitting Anthropic's API directly or routing through a gateway like SubToAPI — the request and response JSON shape stays consistent, which is the whole point of using an HTTPS-first wrapper instead of a model-specific SDK. See the messages documentation for the full field reference.
Handling Streaming Responses in Go
Streaming is where Go's concurrency model actually helps. Claude streams Server-Sent Events (SSE), and you can read them line by line from the response body without needing a third-party SSE library:
func Stream(req Request, onToken func(string)) error {
req.Stream = true
body, _ := json.Marshal(req)
httpReq, _ := http.NewRequest("POST", baseURL, bytes.NewReader(body))
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("Authorization", "Bearer "+os.Getenv("CLAUDE_API_KEY"))
httpReq.Header.Set("Accept", "text/event-stream")
client := &http.Client{Timeout: 0}
resp, err := client.Do(httpReq)
if err != nil {
return err
}
defer resp.Body.Close()
scanner := bufio.NewScanner(resp.Body)
for scanner.Scan() {
line := scanner.Text()
if !strings.HasPrefix(line, "data: ") {
continue
}
payload := strings.TrimPrefix(line, "data: ")
var event struct {
Delta struct {
Text string `json:"text"`
} `json:"delta"`
}
if err := json.Unmarshal([]byte(payload), &event); err == nil {
onToken(event.Delta.Text)
}
}
return scanner.Err()
}
Set client.Timeout to 0 for streaming calls — a fixed HTTP client timeout will kill a long-running connection before it finishes. Use context.WithTimeout instead if you need a cutoff. The streaming docs cover the full event schema, including message_start, content_block_delta, and message_stop events, which you'll want to parse explicitly in anything beyond a prototype.
Error Handling and Retries
Anthropic-compatible APIs return structured error bodies with a type field (rate_limit_error, overloaded_error, invalid_request_error, etc.). A production Go client should check the status code and back off on 429s and 529s:
if resp.StatusCode == 429 || resp.StatusCode == 529 {
time.Sleep(2 * time.Second)
// retry logic here
}
Wrap this in a small retry helper with exponential backoff and a max attempt count rather than hardcoding a single retry — it'll save you from cascading failures under load.
Why Route Through SubToAPI From Go
Teams building Go backends often want one HTTPS endpoint, per-application API keys, and usage visibility without wiring up Anthropic's console for every environment. SubToAPI gives you sub_live_... keys scoped per app, streaming and tool use support, and team seat management, while keeping the request/response format identical to what's shown above — so the Go code in this article doesn't change, only the base URL and key. Check pricing or start with the quickstart guide if you want to wire this into a Go service this week. Tool use follows the same JSON structure described in the tools documentation.
Wrapping Up
A Claude API Golang integration doesn't need a full SDK — a couple hundred lines of net/http code covering requests, streaming, and retries will cover most real-world services. Keep the client package small, inject the API key via environment variables, and test both the streaming and non-streaming paths before deploying, since they fail differently under load.
FAQ
Is there an official Anthropic Go SDK? Not an officially maintained one with full feature parity to the Python/TypeScript SDKs. Most Go teams write a thin HTTP client like the one above or use a community package.
Can I use context.Context for cancellation in streaming calls? Yes — pass a context into http.NewRequestWithContext instead of http.NewRequest, and cancel it on client disconnect or deadline to stop the stream cleanly.
Does switching between Anthropic's API and SubToAPI require changing my Go code? No. Only the base URL and API key change — the JSON request and response shapes are the same, so your structs and parsing logic stay identical.