Go SDK
Go SDK
Anthropic Go 라이브러리는 Go로 작성된 애플리케이션에서 Claude API에 편리하게 접근할 수 있게 해줘요. 이 페이지에서는 설치, 사용법, 요청 필드, 응답 객체, 에러 처리, 재시도, 타임아웃, 파일 업로드, 페이지네이션, 플랫폼 통합 등을 다뤄요.
API 기능 문서와 코드 예시는 API 참조를 보세요. 이 페이지는 Go 특정 SDK 기능과 설정을 다뤄요.
출처: 문서
본문
설치 (Installation)
import (
"github.com/anthropics/anthropic-sdk-go" // anthropic으로 import
)
go get으로 설치하세요:
go get github.com/anthropics/anthropic-sdk-go
요구사항 (Requirements)
이 라이브러리는 Go 1.24+가 필요해요.
사용법 (Usage)
package main
import (
"context"
"fmt"
"github.com/anthropics/anthropic-sdk-go"
"github.com/anthropics/anthropic-sdk-go/option"
)
func main() {
client := anthropic.NewClient(
option.WithAPIKey("my-anthropic-api-key"), // os.LookupEnv("ANTHROPIC_API_KEY")로 기본값 설정
)
message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
MaxTokens: 1024,
Messages: []anthropic.MessageParam{
anthropic.NewUserMessage(anthropic.NewTextBlock("What is a quaternion?")),
},
Model: anthropic.ModelClaudeOpus5_5,
})
if err != nil {
panic(err.Error())
}
for _, block := range message.Content {
if textBlock, ok := block.AsAny().(anthropic.TextBlock); ok {
fmt.Println(textBlock.Text)
}
}
}
인증 옵션(Workload Identity Federation 포함)은 인증을 보세요. API 키가 개인 또는 서비스 계정 키로서 여러 워크스페이스에 접근할 수 있다면 anthropic-workspace-id 요청 헤더에 워크스페이스 ID를 설정하세요. 워크스페이스 선택에서 이 SDK의 요청별 옵션을 보여줘요.
대화 (Conversations)
messages := []anthropic.MessageParam{
anthropic.NewUserMessage(anthropic.NewTextBlock("What is my first name?")),
}
message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
Model: anthropic.ModelClaudeOpus5_5,
Messages: messages,
MaxTokens: 1024,
})
if err != nil {
panic(err)
}
fmt.Printf("%+v\n", message.Content)
messages = append(messages, message.ToParam())
messages = append(messages, anthropic.NewUserMessage(
anthropic.NewTextBlock("My full name is John Doe"),
))
message, err = client.Messages.New(context.TODO(), anthropic.MessageNewParams{
Model: anthropic.ModelClaudeOpus5_5,
Messages: messages,
MaxTokens: 1024,
})
if err != nil {
panic(err)
}
fmt.Printf("%+v\n", message.Content)
시스템 프롬프트 (System prompts)
message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
Model: anthropic.ModelClaudeOpus5_5,
MaxTokens: 1024,
System: []anthropic.TextBlockParam{
{Text: "Be very serious at all times."},
},
Messages: messages,
})
if err != nil {
panic(err)
}
fmt.Printf("%+v\n", message.Content)
스트리밍 (Streaming)
content := "What is a quaternion?"
stream := client.Messages.NewStreaming(context.TODO(), anthropic.MessageNewParams{
Model: anthropic.ModelClaudeOpus5_5,
MaxTokens: 1024,
Messages: []anthropic.MessageParam{
anthropic.NewUserMessage(anthropic.NewTextBlock(content)),
},
})
message := anthropic.Message{}
for stream.Next() {
event := stream.Current()
err := message.Accumulate(event)
if err != nil {
panic(err)
}
switch eventVariant := event.AsAny().(type) {
case anthropic.ContentBlockDeltaEvent:
switch deltaVariant := eventVariant.Delta.AsAny().(type) {
case anthropic.TextDelta:
print(deltaVariant.Text)
}
}
}
if stream.Err() != nil {
panic(stream.Err())
}
도구 호출 (Tool calling)
messages := []anthropic.MessageParam{
anthropic.NewUserMessage(anthropic.NewTextBlock(content)),
}
toolParams := []anthropic.ToolParam{
{
Name: "get_coordinates",
Description: anthropic.String("Accepts a place as an address, then returns the latitude and longitude coordinates."),
InputSchema: GetCoordinatesInputSchema,
},
}
tools := make([]anthropic.ToolUnionParam, len(toolParams))
for i, toolParam := range toolParams {
tools[i] = anthropic.ToolUnionParam{OfTool: &toolParam}
}
for {
message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
Model: anthropic.ModelClaudeOpus5_5,
MaxTokens: 1024,
Messages: messages,
Tools: tools,
})
if err != nil {
panic(err)
}
print(color("[assistant]: "))
for _, block := range message.Content {
switch block := block.AsAny().(type) {
case anthropic.TextBlock:
println(block.Text)
println()
case anthropic.ToolUseBlock:
inputJSON, _ := json.Marshal(block.Input)
println(block.Name + ": " + string(inputJSON))
println()
}
}
messages = append(messages, message.ToParam())
toolResults := []anthropic.ContentBlockParamUnion{}
for _, block := range message.Content {
switch variant := block.AsAny().(type) {
case anthropic.ToolUseBlock:
print(color("[user (" + block.Name + ")]: "))
var response interface{}
switch block.Name {
case "get_coordinates":
var input struct {
Location string `json:"location"`
}
err := json.Unmarshal([]byte(variant.JSON.Input.Raw()), &input)
if err != nil {
panic(err)
}
response = GetCoordinates(input.Location)
}
b, err := json.Marshal(response)
if err != nil {
panic(err)
}
println(string(b))
toolResults = append(toolResults, anthropic.NewToolResultBlock(block.ID, string(b), false))
}
}
if len(toolResults) == 0 {
break
}
messages = append(messages, anthropic.NewUserMessage(toolResults...))
}
요청 필드 (Request fields)
anthropic 라이브러리는 요청 필드에 Go 1.24+ encoding/json 릴리스의 omitzero 시맨틱을 사용해요.
필수 프리미티브 필드(int64나 string 같은)는 `json:"...,required"` 태그를 사용해요. 이 필드는 언제나 직렬화되며, 0값도 포함해요.
선택 프리미티브 타입은 param.Opt[T]로 감싸요. anthropic.String(string)이나 anthropic.Int(int64) 같은 제공된 생성자로 설정할 수 있어요.
param.Opt[T], map, slice, struct, string enum은 `json:"...,omitzero"` 태그를 사용해요. 0값은 생략된 것으로 간주돼요.
param.IsOmitted(any) 함수로 어떤 omitzero 필드의 존재를 확인할 수 있어요.
p := anthropic.ExampleParams{
ID: "id_xxx", // required property
Name: anthropic.String("..."), // optional property
Point: anthropic.Point{
X: 0, // required field will serialize as 0
Y: anthropic.Int(1), // optional field will serialize as 1
// ... omitted non-required fields will not be serialized
},
Origin: anthropic.Origin{}, // the zero value of [Origin] is considered omitted
}
param.Opt[T] 대신 null을 보내려면 param.Null[T]()를 쓰세요. struct T 대신 null을 보내려면 param.NullStruct[T]()를 쓰세요.
p.Name = param.Null[string]() // 'null' instead of string
p.Point = param.NullStruct[Point]() // 'null' instead of struct
param.IsNull(p.Name) // true
param.IsNull(p.Point) // true
요청 struct에는 요청 본문에 비표준 필드를 보낼 수 있는 .SetExtraFields(map[string]any) 메서드가 있어요. Extra 필드는 일치하는 키의 어떤 struct 필드든 덮어써요.
주의: 보안상의 이유로
SetExtraFields는 신뢰할 수 있는 데이터에만 사용하세요.
struct 대신 커스텀 값을 보내려면 제네릭 함수 param.Override를 쓰세요(예: param.Override[anthropic.FooParams](12)).
// API가 특정 타입을 지정하지만 다른 것을 보내고 싶은 경우 [SetExtraFields]를 사용하세요:
p.SetExtraFields(map[string]any{
"x": 0.01, // send "x" as a float instead of int
})
// 객체 대신 숫자 보내기
custom := param.Override[anthropic.FooParams](12)
요청 유니언 (Request unions)
유니언은 각 변형에 대해 "Of" 접두사가 붙은 필드가 있는 struct로 표현돼요. 하나의 필드만 0이 아닐 수 있고, 0이 아닌 필드가 직렬화돼요.
유니언의 하위 프로퍼티는 유니언 struct의 메서드로 접근할 수 있어요. 이 메서드는 존재한다면 기저 데이터에 대한 변경 가능한 포인터를 반환해요.
// 하나의 필드만 non-zero일 수 있어요. 필드가 설정되었는지 확인하려면 param.IsOmitted()를 사용하세요.
type AnimalUnionParam struct {
OfCat *Cat `json:",omitzero,inline"`
OfDog *Dog `json:",omitzero,inline"`
}
animal := AnimalUnionParam{
OfCat: &Cat{
Name: "Whiskers",
Owner: PersonParam{
Address: AddressParam{Street: "3333 Coyote Hill Rd", ZipCode: 0},
},
},
}
// 필드 변경하기
if address := animal.GetOwner().GetAddress(); address != nil {
address.ZipCode = 94304
}
Params 역직렬화 (Deserializing params)
참고:
param.SetJSON은 SDK v1.20.0 이상이 필요해요.
Param 타입(MessageNewParams나 ToolUnionParam처럼 Param으로 끝나는 타입)은 나가는 요청 전용으로 설계됐어요. JSON으로는 올바르게 마샬링되지만 라운드트립 역직렬화는 완전히 지원하지 않아요. 원시 JSON을 param struct로 언마샬링하면 기저 JSON이 유효해도 OfBashTool20250124 같은 타입 유니언 필드가 nil이 돼요.
원시 JSON에서 params를 재구성해야 한다면(데이터베이스, 미들웨어, 이전 요청에서 등) UnmarshalJSON을 호출해 non-union 필드를 채우고, 올바른 재직렬화를 위해 param.SetJSON으로 원시 바이트를 붙이세요:
// Params 직렬화 (예: 저장 또는 전달용)
b, err := json.Marshal(original)
if err != nil {
panic(err)
}
// 나중에 저장된 JSON에서 params 재구성
var params anthropic.MessageNewParams
if err := params.UnmarshalJSON(b); err != nil {
panic(err)
}
param.SetJSON(b, ¶ms)
// params.Model 및 기타 스칼라 필드는 UnmarshalJSON으로 채워져요.
// params.Tools[0].OfBashTool20250124는 nil이지만(유니언 제한),
// 원시 JSON은 보존돼요. params가 API 호출을 위해 다시 마샬링되면
// 도구들이 올바르게 직렬화돼요.
b2, _ := json.Marshal(params)
fmt.Println(string(b) == string(b2)) // true
이 사용 사례에서는 더 일반적인 param.Override[T](any)보다 param.SetJSON(v1.20.0부터 사용 가능)이 선호돼요. 타입 파라미터를 적을 필요가 없고 라운드트립 의도를 명확히 하기 때문이에요.
응답 객체 (Response objects)
응답 struct의 모든 필드는 일반 값 타입(포인터나 래퍼가 아니라)이에요. 응답 struct에는 각 프로퍼티에 대한 메타데이터를 담은 특별한 JSON 필드도 있어요.
type Animal struct {
Name string `json:"name,nullable"`
Owners int `json:"owners"`
Age int `json:"age"`
JSON struct {
Name respjson.Field
Owners respjson.Field
Age respjson.Field
ExtraFields map[string]respjson.Field
} `json:"-"`
}
선택 데이터를 처리하려면 JSON 필드에서 .Valid() 메서드를 쓰세요. .Valid()는 필드가 존재하고, null이 아니며, 성공적으로 언마샬링되었을 때 true를 반환해요.
.Valid()가 false면 해당 필드는 0값이에요.
raw := `{"owners": 1, "name": null}`
var res Animal
json.Unmarshal([]byte(raw), &res)
// 일반 필드 접근
res.Owners // 1
res.Name // ""
res.Age // 0
// 선택 필드 확인
res.JSON.Owners.Valid() // true
res.JSON.Name.Valid() // false
res.JSON.Age.Valid() // false
// 원시 JSON 값
res.JSON.Owners.Raw() // "1"
res.JSON.Name.Raw() == "null" // true
res.JSON.Name.Raw() == respjson.Null // true
res.JSON.Age.Raw() == "" // true
res.JSON.Age.Raw() == respjson.Omitted // true
이 .JSON struct에는 json 응답에서 struct에 명시되지 않은 프로퍼티를 담은 ExtraFields map도 포함돼요. 이는 SDK에 아직 없는 API 기능에 유용해요.
body := res.JSON.ExtraFields["my_unexpected_field"].Raw()
응답 유니언 (Response unions)
응답에서 유니언은 각 객체 변형의 모든 가능한 필드를 담은 평평한 struct로 표현돼요. 변형으로 변환하려면 .AsFooVariant() 메서드나, 있다면 .AsAny() 메서드를 쓰세요.
응답 값 유니언에 프리미티브 값이 포함되면 프리미티브 필드는 프로퍼티와 나란히 있되 Of 접두사가 붙고 `json:"...,inline"` 태그를 사용해요.
type AnimalUnion struct {
// [Dog], [Cat] 변형에서 나온 것
Owner Person `json:"owner"`
// [Dog] 변형에서 나온 것
DogBreed string `json:"dog_breed"`
// [Cat] 변형에서 나온 것
CatBreed string `json:"cat_breed"`
// ...
JSON struct {
Owner respjson.Field
// ...
} `json:"-"`
}
// animal 변형이면
if animal.Owner.Address.ZipCode == "" {
panic("missing zip code")
}
// 변형 스위치
switch variant := animal.AsAny().(type) {
case Dog:
case Cat:
default:
panic("unexpected type")
}
에러 처리 (Error handling)
API가 성공이 아닌 상태 코드를 반환하면 SDK는 *anthropic.Error 타입의 에러를 반환해요. 여기에는 요청의 StatusCode, *http.Request, *http.Response 값과 에러 본문의 JSON(SDK의 다른 응답 객체와 마찬가지로)이 담겨요. 에러에는 응답 헤더의 RequestID도 포함되는데, Anthropic 지원팀과 문제를 해결할 때 유용해요.
에러를 처리하려면 errors.As 패턴을 쓰세요:
_, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
MaxTokens: 1024,
Messages: []anthropic.MessageParam{{
Content: []anthropic.ContentBlockParamUnion{{
OfText: &anthropic.TextBlockParam{
Text: "What is a quaternion?",
},
}},
Role: anthropic.MessageParamRoleUser,
}},
Model: anthropic.ModelClaudeOpus5_5,
})
if err != nil {
var apierr *anthropic.Error
if errors.As(err, &apierr) {
println("Request ID:", apierr.RequestID)
println(string(apierr.DumpRequest(true))) // Prints the serialized HTTP request
println(string(apierr.DumpResponse(true))) // Prints the serialized HTTP response
}
panic(err.Error()) // POST "/v1/messages": 400 Bad Request (Request-ID: req_xxx) { ... }
}
다른 에러가 발생하면 unwrapped로 반환돼요. 예를 들어 HTTP 전송이 실패하면 *net.OpError를 감싼 *url.Error를 받을 수 있어요.
재시도 (Retries)
특정 에러는 기본적으로 2번 자동 재시도되며, 짧은 지수 백오프를 사용해요. SDK는 모든 연결 에러, 408 Request Timeout, 409 Conflict, 429 Rate Limit, >=500 Internal 에러를 기본적으로 재시도해요.
WithMaxRetries 옵션으로 설정하거나 비활성화할 수 있어요:
// 모든 요청의 기본값 설정:
client := anthropic.NewClient(
option.WithMaxRetries(0), // default is 2
)
// 요청별로 덮어쓰기:
// ...
client.Messages.New(
context.TODO(),
anthropic.MessageNewParams{
MaxTokens: 1024,
Messages: []anthropic.MessageParam{{
Content: []anthropic.ContentBlockParamUnion{{
OfText: &anthropic.TextBlockParam{
Text: "What is a quaternion?",
},
}},
Role: anthropic.MessageParamRoleUser,
}},
Model: anthropic.ModelClaudeOpus5_5,
},
option.WithMaxRetries(5),
)
타임아웃 (Timeouts)
non-streaming Messages 요청은 기본적으로 10분 후에 타임아웃돼요. 다른 요청에는 기본 타임아웃이 없어요. 요청 수명주기에 대한 타임아웃을 설정하려면 context를 쓰세요.
요청이 재시도되면 context 타임아웃이 다시 시작되지 않는다는 점을 유의하세요. 재시도별 타임아웃을 설정하려면 option.WithRequestTimeout()을 쓰세요.
// 재시도를 포함한 요청에 대한 타임아웃 설정
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
// ...
client.Messages.New(
ctx,
anthropic.MessageNewParams{
MaxTokens: 1024,
Messages: []anthropic.MessageParam{{
Content: []anthropic.ContentBlockParamUnion{{
OfText: &anthropic.TextBlockParam{
Text: "What is a quaternion?",
},
}},
Role: anthropic.MessageParamRoleUser,
}},
Model: anthropic.ModelClaudeOpus5_5,
},
// 재시도별 타임아웃 설정
option.WithRequestTimeout(20*time.Second),
)
긴 요청 (Long requests)
주의: 더 긴 실행 요청에는 스트리밍 Messages API 사용을 고려하세요.
스트리밍 없이 큰 MaxTokens 값을 설정하는 것은 피하세요. 일부 네트워크는 일정 시간 후 유휴 연결을 끊을 수 있어 Anthropic으로부터 응답을 받지 못하고 요청이 실패하거나 타임아웃될 수 있기 때문이에요.
이 SDK는 non-streaming 요청이 약 10분 이상 걸릴 것으로 예상되면 에러도 반환해요. .Messages.NewStreaming()을 호출하거나 커스텀 타임아웃을 설정하면 이 에러가 비활성화돼요.
파일 업로드 (File uploads)
multipart 요청에서 파일 업로드에 해당하는 요청 파라미터는 io.Reader로 타입화돼요. io.Reader의 내용은 기본적으로 "anonymous_file" 파일 이름과 "application/octet-stream" content-type의 multipart 폼 파트로 보내져요. 그래서 권장하는 방법은 적절한 파일 이름과 content type으로 어떤 io.Reader든 감싸는 anthropic.File(reader io.Reader, filename string, contentType string) 헬퍼로 커스텀 content-type을 지정하는 거예요.
// 파일 시스템의 파일
file, err := os.Open("/path/to/file.json")
anthropic.FileUploadParams{
File: anthropic.File(file, "custom-name.json", "application/json"),
}
// 문자열의 파일
anthropic.FileUploadParams{
File: anthropic.File(strings.NewReader("my file contents"), "custom-name.json", "application/json"),
}
io.Reader의 런타임 타입에 Name() string 또는 ContentType() string을 구현해 파일 이름과 content-type을 커스텀할 수도 있어요. os.File은 Name() string을 구현하므로 os.Open이 반환한 파일은 디스크의 파일 이름으로 보내져요.
페이지네이션 (Pagination)
이 라이브러리는 페이지가 매겨진 목록 엔드포인트를 작업하는 몇 가지 편의 기능을 제공해요.
.ListAutoPaging() 메서드로 모든 페이지의 항목을 순회할 수 있어요:
iter := client.Messages.Batches.ListAutoPaging(context.TODO(), anthropic.MessageBatchListParams{
Limit: anthropic.Int(20),
})
// 필요에 따라 자동으로 더 많은 페이지 가져오기
for iter.Next() {
messageBatch := iter.Current()
fmt.Println(messageBatch.ID)
}
if err := iter.Err(); err != nil {
panic(err.Error())
}
또는 간단한 .List() 메서드로 단일 페이지를 가져오고 .GetNextPage() 같은 추가 헬퍼 메서드가 있는 표준 응답 객체를 받을 수도 있어요:
page, err := client.Messages.Batches.List(context.TODO(), anthropic.MessageBatchListParams{
Limit: anthropic.Int(20),
})
for page != nil {
for _, batch := range page.Data {
fmt.Println(batch.ID)
}
page, err = page.GetNextPage()
}
if err != nil {
panic(err.Error())
}
RequestOptions
이 라이브러리는 함수형 옵션 패턴을 사용해요. option 패키지에 정의된 함수는 RequestConfig를 변경하는 클로저인 RequestOption을 반환해요. 이런 옵션은 클라이언트 또는 개별 요청에 제공할 수 있어요. 예를 들어:
client := anthropic.NewClient(
// 클라이언트가 만든 모든 요청에 헤더 추가
option.WithHeader("X-Some-Header", "custom_header_info"),
)
client.Messages.New(context.TODO(), // ...,
// 헤더 덮어쓰기
option.WithHeader("X-Some-Header", "some_other_custom_header_info"),
// sjson 문법으로 요청 본문에 문서화되지 않은 필드 추가
option.WithJSONSet("some.json.path", map[string]string{"my": "object"}),
)
디버깅할 때 option.WithDebugLog(nil) 요청 옵션이 도움이 될 수 있어요. 전체 요청 옵션 목록을 보세요.
HTTP 클라이언트 커스터마이징 (HTTP client customization)
요청 미들웨어(option.WithMiddleware)와 기본 http.Client 교체(option.WithHTTPClient)는 SDK 미들웨어를 보세요.
플랫폼 통합 (Platform integrations)
참고: 코드 예시가 포함된 상세한 플랫폼 설정 가이드는 다음을 보세요:
Go SDK는 다음 플랫폼을 지원해요:
- Agent Platform:
import "github.com/anthropics/anthropic-sdk-go/vertex".vertex.WithGoogleAuth(ctx, region, projectID)또는vertex.WithCredentials(ctx, region, projectID, creds)를 쓰세요. - Bedrock:
import "github.com/anthropics/anthropic-sdk-go/bedrock". Messages-API Bedrock 엔드포인트에는bedrock.NewMantleClient를(SSE로 스트리밍), (bedrock-runtime경로)에는bedrock.WithLoadDefaultConfig(ctx)/bedrock.WithConfig(cfg)를 쓰세요.bedrock패키지를 전역적으로 import하면 SDK의 스트리밍 레이어에application/vnd.amazon.eventstream용 디코더가 등록돼요(패키지init()을 통해).bedrock-runtimeWithConfig/WithLoadDefaultConfig경로를 쓰든NewMantleClient를 쓰든 적용돼요. - Claude Platform on AWS:
import anthropicaws "github.com/anthropics/anthropic-sdk-go/aws".anthropicaws.ClientConfig값과 함께anthropicaws.NewClient(ctx, cfg)를 써서 클라이언트를 구성하세요. config 또는ANTHROPIC_AWS_WORKSPACE_ID환경 변수에WorkspaceID를 설정하세요.anthropicawsimport 별칭은github.com/aws/aws-sdk-go-v2/aws와 import할 때 이름 충돌을 피해줘요. 베타에서 사용 가능해요. - Foundry: 현재 Go SDK에서 지원되지 않아요. 지원되는 SDK는 Claude in Microsoft Foundry를 보세요.
새 프로젝트에는 bedrock.NewMantleClient를, Bedrock InvokeModel API를 쓰는 기존 애플리케이션에는 bedrock.WithLoadDefaultConfig/WithConfig를 쓰세요.
고급 사용법 (Advanced usage)
원시 응답 데이터 접근(예: 응답 헤더) (Accessing raw response data)
option.WithResponseInto() 요청 옵션으로 원시 HTTP 응답 데이터에 접근할 수 있어요. 응답 헤더, 상태 코드, 기타 세부사항을 검사해야 할 때 유용해요.
// HTTP 응답을 저장할 변수
var response *http.Response
message, err := client.Messages.New(
context.TODO(),
anthropic.MessageNewParams{
MaxTokens: 1024,
Messages: []anthropic.MessageParam{{
Content: []anthropic.ContentBlockParamUnion{{
OfText: &anthropic.TextBlockParam{
Text: "What is a quaternion?",
},
}},
Role: anthropic.MessageParamRoleUser,
}},
Model: anthropic.ModelClaudeOpus5_5,
},
option.WithResponseInto(&response),
)
if err != nil {
// handle error
}
fmt.Printf("%+v\n", message.Content)
fmt.Printf("Status Code: %d\n", response.StatusCode)
fmt.Printf("Headers: %+#v\n", response.Header)
커스텀/문서화되지 않은 요청 만들기 (Making custom/undocumented requests)
이 라이브러리는 문서화된 API에 편리하게 접근하도록 타입화되어 있어요. 문서화되지 않은 엔드포인트, params, 응답 프로퍼티에 접근해야 한다면 여전히 라이브러리를 사용할 수 있어요.
문서화되지 않은 엔드포인트 (Undocumented endpoints)
문서화되지 않은 엔드포인트에 요청하려면 client.Get, client.Post 및 기타 HTTP 동사를 쓸 수 있어요. 재시도 같은 클라이언트의 RequestOptions는 이런 요청을 만들 때 존중돼요.
var (
// params는 io.Reader, []byte, encoding/json 직렬화 가능한 객체,
// 또는 이 라이브러리에 정의된 "...Params" struct일 수 있어요.
params map[string]any
// result는 []byte, *http.Response, encoding/json 역직렬화 가능한 객체,
// 또는 이 라이브러리에 정의된 model일 수 있어요.
result *http.Response
)
err := client.Post(context.Background(), "/unspecified", params, &result)
if err != nil {
// ...
}
문서화되지 않은 요청 params (Undocumented request params)
문서화되지 않은 파라미터로 요청하려면 option.WithQuerySet() 또는 option.WithJSONSet() 메서드를 쓸 수 있어요.
params := FooNewParams{
ID: "id_xxxx",
Data: FooNewParamsData{
FirstName: anthropic.String("John"),
},
}
client.Foo.New(context.Background(), params, option.WithJSONSet("data.last_name", "Doe"))
문서화되지 않은 응답 프로퍼티 (Undocumented response properties)
문서화되지 않은 응답 프로퍼티에 접근하려면 result.JSON.RawJSON()로 응답의 원시 JSON을 문자열로 접근하거나, result.JSON.Foo.Raw()로 결과의 특정 필드의 원시 JSON을 가져올 수 있어요.
응답 struct에 없는 필드는 저장되어 result.JSON.ExtraFields(즉 map[string]respjson.Field)로 접근할 수 있어요.
시맨틱 버저닝 (Semantic versioning)
이 패키지는 일반적으로 SemVer 규칙을 따르지만, 일부 하위 호환성이 깨지는 변경은 마이너 버전으로 릴리스될 수 있어요:
- 기술적으로 공개되어 있지만 외부 사용을 의도하거나 문서화하지 않은 라이브러리 내부의 변경.
- 실제로 대다수 사용자에게 영향을 주지 않을 것으로 예상되는 변경.
원활한 업그레이드 경험을 믿고 맡길 수 있도록 하위 호환성을 진지하게 여겨요. 질문, 버그, 제안은 이슈를 열어 환영해요.