How to Call Anthropic Claude API from Go

Web
Initialize the Anthropic Go SDK client with your API key and call Messages.Create to send a prompt and receive a response from Claude.

Use the anthropic-go-sdk library to initialize a client with your API key and call CreateMessage to send prompts to Claude.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/anthropics/anthropic-sdk-go"
	"github.com/anthropics/anthropic-sdk-go/option"
)

func main() {
	client := anthropic.NewClient(
		option.WithAPIKey("YOUR_API_KEY"),
	)

	ctx := context.Background()
	resp, err := client.Messages.Create(ctx, anthropic.MessageParam{
		Model: "claude-3-5-sonnet-20241022",
		MaxTokens: 1024,
		System: []anthropic.MessageSystemContentParam{
			{Type: "text", Text: "You are a helpful assistant."},
		},
		Messages: []anthropic.MessageParam{
			{
				Role: "user",
				Content: []anthropic.MessageContentParam{
					{Type: "text", Text: "Hello, Claude!"},
				},
			},
		},
	})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(resp.Content[0].(anthropic.TextBlock).Text)
}