Sobes.tech
Junior — Middle

How do you organize work with external API in your project?

sobes.tech AI

Answer from AI

When working with external APIs in a Go project, it is common to organize a separate layer or package responsible for interacting with that API. Key points:

  • Encapsulation of request logic — creating a client with methods for each API endpoint.
  • Error handling and timeouts — using contexts (context.Context) to control execution time.
  • Serialization and deserialization of data — working with JSON or other formats.
  • Retry and fallback mechanisms — implementing retries and fallbacks if necessary.

Example of a simple client for a GET request:

package api

import (
    "context"
    "encoding/json"
    "net/http"
    "time"
)

type APIClient struct {
    baseURL    string
    httpClient *http.Client
}

func NewAPIClient(baseURL string) *APIClient {
    return &APIClient{
        baseURL: baseURL,
        httpClient: &http.Client{
            Timeout: 10 * time.Second,
        },
    }
}

type DataResponse struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
}

func (c *APIClient) GetData(ctx context.Context, endpoint string) (*DataResponse, error) {
    req, err := http.NewRequestWithContext(ctx, "GET", c.baseURL+endpoint, nil)
    if err != nil {
        return nil, err
    }

    resp, err := c.httpClient.Do(req)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()

    if resp.StatusCode != http.StatusOK {
        return nil, fmt.Errorf("unexpected status: %s", resp.Status)
    }

    var data DataResponse
    if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
        return nil, err
    }

    return &data, nil
}

Thus, the project has a centralized client that can be used in services or handlers, ensuring clean architecture and ease of testing.

How do you organize work with external API in your… - sobes.tech