Golang Development, CODEX

Make an HTTP GET/POST Request in Golang

Making REST API requests and handling responses

Sukhpal Saini
CodeX

--

Photo by James Harrison on Unsplash

HTTP Requests are the bread and butter of any application. In this example, I will show you how you can make a GET/POST request using Golang.

We will use the jsonplaceholder.typicode.com API to make sample requests to.

Making a GET Request

package mainimport (
"io/ioutil"
"log"
"net/http"
)
func main() {
resp, err := http.Get("https://jsonplaceholder.typicode.com/todos/1")

if err != nil {
log.Printf("Request Failed: %s", err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Printf("Reading body failed: %s", err)
return
}
// Log the request body
bodyString := string(body)
log.Print(bodyString)
}

Making a GET Request with Params

Let’s look at how we can add URL params to our previous GET request. We can pass a userId to get the posts by that user.

package mainimport (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
)
type Posts []struct {
Userid int `json:"userId"`
ID int `json:"id"`
Title string `json:"title"`
Body string `json:"body"`
}
func main() {
params := url.Values{}
params.Add("userId", "1")
resp, err := http.Get("https://jsonplaceholder.typicode.com/posts?" +params.Encode()) if err != nil {
log.Printf("Request Failed: %s", err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
// Log the request body
bodyString := string(body)
log.Print(bodyString)
// Unmarshal result
posts := Posts{}
err = json.Unmarshal(body, &posts)
if err != nil {
log.Printf("Reading body failed: %s", err)
return
}
log.Printf("The title of the first post is %s", posts[0].Title)
}

We can also marshal the JSON response into a collection of post structs. For reference, the JSON response from the API looks like this:

[
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit suscipit recusandae consequuntur expedita et cum reprehenderit molestiae ut ut quas totam nostrum rerum est autem sunt rem eveniet architecto"
}
]

Making a POST Request

Similarly, we can also make a POST request with body params to create a post using the API.

package mainimport (
"encoding/json"
"io/ioutil"
"log"
"net/http"
"net/url"
)
type Post struct {
Userid string `json:"userId"`
ID int `json:"id"`
Title string `json:"title"`
Body string `json:"body"`
}
func main() {
params := url.Values{}
params.Add("title", "foo")
params.Add("body", "bar")
params.Add("userId", "1")
resp, err := http.PostForm("https://jsonplaceholder.typicode.com/posts",
params)
if err != nil {
log.Printf("Request Failed: %s", err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
// Log the request body
bodyString := string(body)
log.Print(bodyString)
// Unmarshal result
post := Post{}
err = json.Unmarshal(body, &post)
if err != nil {
log.Printf("Reading body failed: %s", err)
return
}

log.Printf("Post added with ID %d", post.ID)
}

The response from the API POST request looks like this:

{
id: 101,
title: 'foo',
body: 'bar',
userId: 1
}

There you have it. Now you can access data all across the web using GET/POST requests with Golang.

Find me on Twitter and let’s have a chat :)

--

--

Sukhpal Saini
CodeX
Writer for

Full Stack Engineer. Prev at IBM, Apple, Saks. Now building https://engyne.ai to help B2B SaaS get customers with content marketing using AI.