← Blog

Claude API Go Integration Tutorial

2026-11-22 · 5 min read · SubToAPI Team

Go doesn't have an official Claude SDK maintained by Anthropic, so integrating the Claude API in a Go application means working directly with HTTP requests and JSON encoding/decoding. This is actually straightforward: Claude's API is a clean REST interface, and Go's standard library (net/http, encoding/json) handles everything you need without external dependencies.

This tutorial walks through building a working Claude API client in Go — sending messages, parsing responses, handling streaming, and dealing with errors — plus a faster path using an HTTP-based gateway if you want to skip SDK maintenance entirely.

Setting Up the Project

Start with a standard Go module:

mkdir claude-go-client && cd claude-go-client
go mod init claude-go-client

No external packages are required for a basic implementation. You'll use net/http, encoding/json, bytes, and os from the standard library.

Defining the Request and Response Structs

Claude's Messages API expects a JSON body with a model, messages array, and max_tokens. Define Go structs that map to this shape:

package main

type Message struct {
    Role    string `json:"role"`
    Content string `json:"content"`
}

type ChatRequest struct {
    Model     string    `json:"model"`
    MaxTokens int       `json:"max_tokens"`
    Messages  []Message `json:"messages"`
}

type ContentBlock struct {
    Type string `json:"type"`
    Text string `json:"text"`
}

type ChatResponse struct {
    ID      string         `json:"id"`
    Content []ContentBlock `json:"content"`
    Usage   struct {
        InputTokens  int `json:"input_tokens"`
        OutputTokens int `json:"output_tokens"`
    } `json:"usage"`
}

Keeping these as explicit structs rather than map[string]interface{} gives you compile-time safety and makes it easy to extract the final text from Content[0].Text.

Making the API Call

Here's a complete function that sends a message and returns the response text:

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "os"
)

func sendMessage(prompt string) (string, error) {
    reqBody := ChatRequest{
        Model:     "claude-sonnet-4-20250514",
        MaxTokens: 1024,
        Messages: []Message{
            {Role: "user", Content: prompt},
        },
    }

    jsonBody, err := json.Marshal(reqBody)
    if err != nil {
        return "", err
    }

    req, err := http.NewRequest(
        "POST",
        "https://api.anthropic.com/v1/messages",
        bytes.NewBuffer(jsonBody),
    )
    if err != nil {
        return "", err
    }

    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 {
        return "", err
    }
    defer resp.Body.Close()

    body, err := io.ReadAll(resp.Body)
    if err != nil {
        return "", err
    }

    if resp.StatusCode != http.StatusOK {
        return "", fmt.Errorf("api error: %s", string(body))
    }

    var chatResp ChatResponse
    if err := json.Unmarshal(body, &chatResp); err != nil {
        return "", err
    }

    if len(chatResp.Content) == 0 {
        return "", fmt.Errorf("empty response content")
    }

    return chatResp.Content[0].Text, nil
}

func main() {
    text, err := sendMessage("Explain goroutines in two sentences.")
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    fmt.Println(text)
}

Run it with ANTHROPIC_API_KEY=your_key go run main.go. This is enough for most backend services — a single function you can call from any handler or worker.

Handling Streaming Responses

For chat UIs or long completions, you'll want streaming instead of waiting for the full response. Claude streams responses as Server-Sent Events, which means reading the HTTP body line by line and parsing data: chunks:

func streamMessage(prompt string) error {
    reqBody := map[string]interface{}{
        "model":      "claude-sonnet-4-20250514",
        "max_tokens": 1024,
        "stream":     true,
        "messages":   []Message{{Role: "user", Content: prompt}},
    }

    jsonBody, _ := json.Marshal(reqBody)
    req, _ := http.NewRequest("POST", "https://api.anthropic.com/v1/messages", bytes.NewBuffer(jsonBody))
    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")

    resp, err := http.DefaultClient.Do(req)
    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: ") {
            fmt.Println(strings.TrimPrefix(line, "data: "))
        }
    }
    return scanner.Err()
}

In production you'd parse each event type (content_block_delta, message_stop, etc.) and append text deltas to a buffer instead of printing raw JSON.

Error Handling and Retries

Claude's API returns standard HTTP status codes: 429 for rate limits, 401 for auth errors, 529 for overload. In Go, wrap your request logic with a retry helper for transient failures:

func withRetry(fn func() error, attempts int) error {
    var err error
    for i := 0; i < attempts; i++ {
        if err = fn(); err == nil {
            return nil
        }
        time.Sleep(time.Duration(i+1) * time.Second)
    }
    return err
}

This covers the basics, but building reliable production infrastructure around raw API calls — retries, rate limit backoff, key rotation, usage tracking — adds up quickly in maintenance time.

A Simpler Alternative: One HTTP Endpoint

If you'd rather skip writing and maintaining your own Claude client wrapper, SubToAPI turns your existing Claude access into a straightforward HTTPS API with sub_live_... application keys. The Go code above barely changes — you just point the request at a different host:

req, _ := http.NewRequest(
    "POST",
    "https://api.subtoapi.app/v1/messages",
    bytes.NewBuffer(jsonBody),
)
req.Header.Set("Authorization", "Bearer "+os.Getenv("SUBTOAPI_KEY"))
req.Header.Set("Content-Type", "application/json")

You get streaming, tool use, and per-key usage metadata out of the box, with team seats if you're sharing access across a Go backend team. Check the quickstart guide and messages endpoint docs for request formats, or streaming docs for the SSE event reference. Plans start at €9/month on the pricing page, with a free trial at signup.

Wrapping Up

Integrating Claude in Go doesn't require a third-party SDK — the standard library's net/http and encoding/json packages handle request construction, JSON marshaling, and response parsing cleanly. Define typed structs for your requests and responses, handle streaming with a buffered scanner on SSE chunks, and wrap calls in retry logic for production resilience.

FAQ

Does Anthropic provide an official Go SDK for Claude? No. Anthropic maintains official SDKs for Python and TypeScript. For Go, you work directly with the REST API using net/http, which is simple given Claude's clean JSON interface.

How do I handle streaming responses in Go? Read the HTTP response body with bufio.Scanner, filter lines prefixed with data: , and parse each SSE event's JSON payload to extract content deltas as they arrive.

Can I use a gateway instead of calling the Anthropic API directly from Go? Yes. Services like SubToAPI expose a drop-in HTTPS endpoint with API keys, streaming, and usage tracking, so your existing Go request code works with minimal changes — just swap the host and auth header.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →