How to write a RESTful API client in Golang

published on 21 December 2022

RESTful API clients allow developers to interact with RESTful APIs to perform various operations, such as sending requests and receiving responses. This tutorial will teach us how to write a simple RESTful API client in Golang using the popular net/http package.

To start, we will need to import the net/http package and create a new client using the http.NewClient function. This function takes a timeout duration as an argument and returns a new client instance:

import "net/http"

client := http.NewClient(10 * time.Second)

Next, we will use the client to send a request to the API by calling the client's Do method. This method takes an HTTP request as an argument and returns an HTTP response and an error.

Here is an example of sending a GET request to an API:

req, err := http.NewRequest("GET", "https://api.example.com/users", nil)
if err != nil {
    // handle error
}

resp, err := client.Do(req)
if err != nil {
    // handle error
}
defer resp.Body.Close()

The Do method sends the request and returns the response from the API. If there was an error sending the request or receiving the response, it will be returned in the error variable.

We can also add headers to the request by using the Header field of the request object:

req.Header.Add("Authorization", "Bearer YOUR_API_TOKEN")
req.Header.Add("Content-Type", "application/json")

If the API requires us to send data in the request body, we can use the io.Reader interface to pass the data to the request. For example, to send a POST request with a JSON payload, we can use the json package to encode the data and pass it to the request body:

data := map[string]string{
    "name": "John",
    "email": "[email protected]",
}

payload, err := json.Marshal(data)
if err != nil {
    // handle error
}

req, err := http.NewRequest("POST", "https://api.example.com/users", bytes.NewBuffer(payload))
if err != nil {
    // handle error
}

req.Header.Add("Content-Type", "application/json")

resp, err := client.Do(req)
if err != nil {
    // handle error
}
defer resp.Body.Close()

Once we have received the response from the API, we can read the response body using the io.Reader interface. For example, to read the response body as a string, we can use the ioutil.ReadAll function:

body, err := ioutil.ReadAll(resp.Body)
if err != nil {
    // handle error
}

fmt.Println(string(body))

That's it! You now know how to write a simple RESTful API client in Go using the net/http package. With these basic building blocks, you can interact with any RESTful API and perform a variety of operations.

Read more