Go Example API Call (Get)

An API, or Application Programming Interface, is a library of related programme code available for programmers to use. People and organisations can provide a service, which is available to use via an API. In the case of the example below, weather data is made available via an HTTP Get request, which returns the data in JSON format. This API returns a five-day forecast, for a specific area, at three hourly intervals. Full details of this API can be found on the Rapid API website here, as well as the API's own website here.

A sample of the weather data returned can be seen below, which covers two time periods on a particular day. It should be noted that the data is returned in one long JSON string, rather than nicely formatted, as shown here.

{
  "timezone": "Europe/London",
  "city_name": "Bath",
  "lon": -2.362,
  "state_code": "ENG",
  "lat": 51.3849,
  "data": [
    {
      "wind_cdir": "SW",
      "wind_gust_spd": 8.52,
      "pod": "d",
      "pres": 995,
      "clouds_hi": 0,
      "clouds_low": 100,
      "clouds_mid": 85,
      "vis": 24,
      "wind_spd": 4.22,
      "wind_cdir_full": "southwest",
      "slp": 1006,
      "datetime": "2025-06-07:09",
      "ts": 1749286800,
      "dewpt": 8.7,
      "uv": 2,
      "snow": 0,
      "ghi": 688,
      "dhi": 107,
      "precip": 0.00048828125,
      "dni": 846,
      "temp": 12.6,
      "app_temp": 12.6,
      "pop": 15,
      "timestamp_utc": "2025-06-07T09:00:00",
      "weather": {
        "icon": "c04d",
        "description": "Overcast clouds",
        "code": 804
      },
      "solar_rad": 196.20615,
      "clouds": 99,
      "timestamp_local": "2025-06-07T10:00:00",
      "snow_depth": 0,
      "ozone": 394,
      "rh": 77,
      "wind_dir": 236
    },
    {
      "wind_cdir": "WSW",
      "wind_gust_spd": 10.74,
      "pod": "d",
      "pres": 995,
      "clouds_hi": 100,
      "clouds_low": 70,
      "clouds_mid": 100,
      "vis": 7.4,
      "wind_spd": 4.88,
      "wind_cdir_full": "west-southwest",
      "slp": 1006,
      "datetime": "2025-06-07:12",
      "ts": 1749297600,
      "dewpt": 11,
      "uv": 3,
      "snow": 0,
      "ghi": 905,
      "dhi": 119,
      "precip": 0.4321289,
      "dni": 905,
      "temp": 14,
      "app_temp": 14,
      "pop": 30,
      "timestamp_utc": "2025-06-07T12:00:00",
      "weather": {
        "icon": "r01d",
        "description": "Light rain",
        "code": 500
      },
      "solar_rad": 179.14203,
      "clouds": 100,
      "timestamp_local": "2025-06-07T13:00:00",
      "snow_depth": 0,
      "ozone": 391,
      "rh": 82,
      "wind_dir": 240
    }
  ],
  "country_code": "GB"
}

Firstly, a 'struct' is defined to handle the response data. The API request is then constructed, and the weather data is retrieved. The name of the city is displayed and the struct is used in the processing of the weather data. The data is formatted where necessary and output as part of a formatted string.

package main

import (
    "encoding/json"
    "fmt"
    "io"
    "math"
    "net/http"
    "time"
)

// Struct to handle the response data.
type WeatherResponse struct {
    StateCode string `json:"state_code"`
    Data      []struct {
        CloudsLow      int     `json:"clouds_low"`
        CloudsMid      int     `json:"clouds_mid"`
        Snow           int     `json:"snow"`
        SolarRad       float64 `json:"solar_rad"`
        WindGustSpd    float64 `json:"wind_gust_spd"`
        TimestampUtc   string  `json:"timestamp_utc"`
        TimestampLocal string  `json:"timestamp_local"`
        Dni            int     `json:"dni"`
        Clouds         int     `json:"clouds"`
        Vis            float64 `json:"vis"`
        Pres           int     `json:"pres"`
        WindSpd        float64 `json:"wind_spd"`
        Slp            int     `json:"slp"`
        WindCdirFull   string  `json:"wind_cdir_full"`
        SnowDepth      int     `json:"snow_depth"`
        Datetime       string  `json:"datetime"`
        Ts             int     `json:"ts"`
        Temp           float64 `json:"temp"`
        Weather        struct {
            Icon        string `json:"icon"`
            Code        int    `json:"code"`
            Description string `json:"description"`
        } `json:"weather"`
        Dewpt    float64 `json:"dewpt"`
        Uv       int     `json:"uv"`
        Ozone    int     `json:"ozone"`
        WindDir  int     `json:"wind_dir"`
        Ghi      int     `json:"ghi"`
        Dhi      int     `json:"dhi"`
        Precip   float64 `json:"precip"`
        Pop      int     `json:"pop"`
        WindCdir string  `json:"wind_cdir"`
        Rh       int     `json:"rh"`
        Pod      string  `json:"pod"`
        CloudsHi int     `json:"clouds_hi"`
        AppTemp  float64 `json:"app_temp"`
    } `json:"data"`
    CountryCode string  `json:"country_code"`
    Lat         float64 `json:"lat"`
    Timezone    string  `json:"timezone"`
    Lon         float64 `json:"lon"`
    CityName    string  `json:"city_name"`
}

func main() {

    // Construct the API request.
    url := "https://weatherbit-v1-mashape.p.rapidapi.com/forecast/3hourly" +
        "?lat=51.38488&lon=-2.36197"
    req, _ := http.NewRequest("GET", url, nil)
    req.Header.Add("x-rapidapi-key", "api-key-goes-here")
    req.Header.Add("x-rapidapi-host", "weatherbit-v1-mashape.p.rapidapi.com")

    // Get the API response using the request information.
    res, err := http.DefaultClient.Do(req)
    if err != nil {
        fmt.Println("Error making request:", err)
        return
    }
    defer res.Body.Close()
    body, _ := io.ReadAll(res.Body)

    // Use the struct to handle the response data.
    var weather WeatherResponse
    if err := json.Unmarshal(body, &weather); err != nil {
        fmt.Println("Can not unmarshal JSON")
    }

    // Display the city name.
    fmt.Println(weather.CityName)

    // Process and display the forecast data.
    for _, dayTime := range weather.Data {

        // Parse and format the timestamp.
        dateTime, err := time.Parse("2006-01-02T15:04:05", dayTime.TimestampLocal)
        if err != nil {
            fmt.Println("Error parsing timestamp:", err)
            continue
        }
        fDateTime := dateTime.Format("02/01/2006 15:04:05")

        // Round the temperature and format the output.
        temperature := fmt.Sprintf("%.0f°C", math.Round(dayTime.Temp))

        // Extract the description.
        weatherDescription := dayTime.Weather.Description

        // Display as: 'Date Time - Temperature - Weather Description'
        fmt.Printf("%s - %s - %s\n", fDateTime, temperature, weatherDescription)

    }

}

Sample output to the terminal can be seen below.

Bath
07/06/2025 10:00:00 - 13°C - Overcast clouds
07/06/2025 13:00:00 - 14°C - Light rain
07/06/2025 16:00:00 - 14°C - Light rain
07/06/2025 19:00:00 - 14°C - Light shower rain
07/06/2025 22:00:00 - 12°C - Clear Sky
08/06/2025 01:00:00 - 10°C - Clear Sky
08/06/2025 04:00:00 - 9°C - Clear Sky
08/06/2025 07:00:00 - 10°C - Clear Sky
08/06/2025 10:00:00 - 13°C - Clear Sky
08/06/2025 13:00:00 - 16°C - Clear Sky
08/06/2025 16:00:00 - 16°C - Few clouds
08/06/2025 19:00:00 - 15°C - Clear Sky
08/06/2025 22:00:00 - 12°C - Clear Sky
09/06/2025 01:00:00 - 11°C - Clear Sky
09/06/2025 04:00:00 - 10°C - Clear Sky
09/06/2025 07:00:00 - 11°C - Scattered clouds
09/06/2025 10:00:00 - 15°C - Clear Sky
09/06/2025 13:00:00 - 17°C - Overcast clouds
09/06/2025 16:00:00 - 17°C - Scattered clouds
09/06/2025 19:00:00 - 16°C - Overcast clouds
09/06/2025 22:00:00 - 13°C - Overcast clouds
10/06/2025 01:00:00 - 13°C - Overcast clouds
10/06/2025 04:00:00 - 13°C - Clear Sky
10/06/2025 07:00:00 - 13°C - Overcast clouds
10/06/2025 10:00:00 - 17°C - Overcast clouds
10/06/2025 13:00:00 - 18°C - Overcast clouds
10/06/2025 16:00:00 - 19°C - Scattered clouds
10/06/2025 19:00:00 - 17°C - Scattered clouds
10/06/2025 22:00:00 - 15°C - Clear Sky
11/06/2025 01:00:00 - 13°C - Clear Sky
11/06/2025 04:00:00 - 11°C - Scattered clouds
11/06/2025 07:00:00 - 12°C - Overcast clouds
11/06/2025 10:00:00 - 17°C - Few clouds
11/06/2025 13:00:00 - 22°C - Clear Sky
11/06/2025 16:00:00 - 24°C - Clear Sky
11/06/2025 19:00:00 - 22°C - Scattered clouds
11/06/2025 22:00:00 - 19°C - Few clouds
12/06/2025 01:00:00 - 19°C - Few clouds
12/06/2025 04:00:00 - 16°C - Overcast clouds
12/06/2025 07:00:00 - 16°C - Overcast clouds