Response Concepts

Understanding how the Go SDK handles API responses is crucial for building robust applications. This section delves into the structure of responses, how to access data, and how the SDK manages different response scenarios.

The Response Object

When you make a request using the Go SDK, you'll typically receive a response object. This object encapsulates all the information returned by the API server, including the status code, headers, and the actual response body.

The SDK aims to provide a convenient and idiomatic Go interface for interacting with these responses. Common response types include:

Accessing Response Data

The SDK deserializes the response body into Go structs, making it easy to work with the data. The specific struct type depends on the API endpoint you are calling.

For example, if an endpoint returns JSON data representing a user, the SDK will attempt to unmarshal it into a predefined User struct:


// Assuming 'resp' is your response object from an SDK call
var userData struct {
    ID   string `json:"id"`
    Name string `json:"name"`
}

err := resp.Unmarshal(&userData)
if err != nil {
    // Handle unmarshalling error
}

fmt.Printf("User ID: %s, Name: %s\n", userData.ID, userData.Name)
                

The SDK provides helper methods like resp.Unmarshal() to simplify this process. Always check for errors during unmarshalling.

HTTP Status Codes

The Go SDK respects standard HTTP status codes. You can access the status code directly from the response object to determine the outcome of your request:


statusCode := resp.StatusCode() // Returns an int (e.g., 200, 404, 500)

if statusCode >= 200 && statusCode < 300 {
    // Success
} else {
    // Handle non-success status codes
}
                

Common success codes include 200 (OK), 201 (Created), and 204 (No Content). Error codes range from 400 (Bad Request) to 500 (Internal Server Error) and beyond.

Response Headers

Response headers provide metadata about the API response. The SDK allows you to access these headers by their key:


contentType := resp.Header("Content-Type")
if contentType != "" {
    fmt.Printf("Content Type: %s\n", contentType)
}
                

This is useful for inspecting things like Content-Type, ETag, or custom headers set by the API.

Important Note: The SDK often abstracts away the direct HTTP response object. You'll usually interact with a higher-level SDK response type that wraps the underlying HTTP details for a more Go-idiomatic experience.

Handling Different Response Structures

APIs can return responses with varying structures. The SDK is designed to be flexible:

Error Responses in Detail

When an API returns an error status code (typically 4xx or 5xx), the response body often contains structured error information. The SDK aims to parse this into a usable error object.

Refer to the Error Handling section for a comprehensive guide on how to effectively catch and interpret API errors.