How to make HTTP POST Request with JSON body in Golang

The Go standard library comes with the “net/http” package, which has excellent support for HTTP Client and Server. Go also has a “json” package that implements the encoding and decoding of JSON.

JSON

JSON is a lightweight, human-readable data exchange format. Below is an example of a simple JSON containing a Course and Path list.
{
"Courses": [
"Java",
"Golang"
],
"Paths": [
"System Design",
"Coding Interview"
]
}

JSON is widely used in web development to define API contracts.

Usage

Using the "net/http" package, we can make a HTTP POST request. During this post request, we can send JSON data in binary format using the "json" package. The following code shows how we can make the create user request on server "reqres.in", by sending the USER JSON object.
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
//If the struct variable names does not match with json attributes
//then you can define the json attributes actual name after json:attname as shown below.
type User struct {
Name string `json:"name"`
Job string `json:"job"`
}
func main(){
//Create user struct which need to post.
user := User{
Name: "Test User",
Job: "Go lang Developer",
}
//Convert User to byte using Json.Marshal
//Ignoring error.
body, _ := json.Marshal(user)
//Pass new buffer for request with URL to post.
//This will make a post request and will share the JSON data
resp, err := http.Post("https://reqres.in/api/users", "application/json", bytes.NewBuffer(body) )
// An error is returned if something goes wrong
if err != nil {
panic(err)
}
//Need to close the response stream, once response is read.
//Hence defer close. It will automatically take care of it.
defer resp.Body.Close()
//Check response code, if New user is created then read response.
if resp.StatusCode == http.StatusCreated {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
//Failed to read response.
panic(err)
}
//Convert bytes to String and print
jsonStr := string(body)
fmt.Println("Response: ", jsonStr)
} else {
//The status is not Created. print the error.
fmt.Println("Get failed with error: ", resp.Status)
}
}

If the request completes successfully, we will get the USER JSON object in response.

body, err := json.Marshal(user)

Marshal will return the JSON encoding of given type. You need to check if there is any error during encoding before sending the data to post request.

Free Resources

Attributions:
  1. undefined by undefined