Making Http Call and Fetching Data Into Map Golang

fetching data from api in golang#

golang have great support for web and cloud and its http package will handle all of the work we need to do for web

So in this post we will create simple http client which call external api and we get json response from api which we will further decode into maps

for making default http client we can use http.DefaultClient and then on that client we can call http methods like Get Post PUT and so on.

we will json.Unmarshal() function from encoding/json package which can decode json data into maps or struct

look at the example below it’s quite simple to implement

package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {

	client, err := http.DefaultClient.Get("https://jsonplaceholder.typicode.com/posts")

	if err != nil {
		fmt.Println(err)
	}
	data, err := ioutil.ReadAll(client.Body)
	if err != nil {
		fmt.Println(err)
	}
	
	var jsonData []map[string]interface{}

	err = json.Unmarshal(data, &jsonData)
	if err != nil {
		fmt.Println(err)
	}
	for _, v := range jsonData {
		fmt.Println(v["title"])
	}
	
}


it will print all the title from the response post array

comments powered by Disqus