~/Making API Requests in Go
Feb 14, 2019
To make API requests in Go, use the net/http
package. This package provides the tools for HTTP requests including GET, POST, and others. Here is a straightforward example for a GET request:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
package main
import (
"io/ioutil"
"log"
"net/http"
)
func main() {
resp, err := http.Get("https://jsonplaceholder.typicode.com/posts/1")
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
log.Println(string(body))
}
|
For a POST request, use http.Post
or http.NewRequest
:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
package main
import (
"bytes"
"io/ioutil"
"log"
"net/http"
)
func main() {
jsonStr := []byte(`{"title":"foo","body":"bar","userId":1}`)
resp, err := http.Post("https://jsonplaceholder.typicode.com/posts",
"application/json", bytes.NewBuffer(jsonStr))
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
log.Println(string(body))
}
|
Always handle errors and close response bodies to avoid leaking resources. See official net/http documentation for more methods and details.