DEV Community

Ramu Mangalarapu
Ramu Mangalarapu

Posted on • Edited on

Consuming 3rd Party REST APIs Golang {GET method}

Hello World!,

This is my first internet post. So there may be mistakes, please ignore it, thank you.

Today, I am going to write small and simple tutorial about consuming 3rd party API in Golang.

package main

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

func main() {
    // To consume 3rd party API, we need to build request object.
    // This can be anything you want to consume, just paste the URL,
    // usually, we test the URL in API clients such as Postman or through cURL, then
    // we can proceed for consumption.
    req, err := http.NewRequest(http.MethodGet, "https://jsonplaceholder.typicode.com/todos/2", nil)
    if err != nil {
        log.Fatalf("Failed to create request object for /GET endpoint: %v", err)
    }

    // Now add all the required request headers, mostly APIs secured with access tokens
    // req.Header.Add("Authorization", "Bearer "+token)
    // And today's application development, most of wire format is JSON.
    // if the wire format we wanted to be different, we could request but server has to support it.
    req.Header.Add("Content-type", "application/json; charset=utf-8")

    // we can build our custom http clients but here we are using deafult http client
    // when we use custom http client, we can send context object, timeouts etc..
    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        log.Fatalf("Failed to send HTTP request: %v", err)
    }

    // here we are reading the response body from the server
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        log.Fatalf("Failed to read response body: %v", err)
    }

    // Always close the response body
    defer resp.Body.Close()

    // now we need to read this to our native Golang type
    // as the map data structure is close to JSON, we could use it
    // in fact we could this for most of the wire formats.
    data := make(map[string]interface{})

    // this step de-serializes JSON data to our native Golang data
    json.Unmarshal(body, &data)

    // let's print the map data by iterating over it
    for key, value := range data {
        fmt.Printf("%s: %v\n", key, value)
    }
}

Enter fullscreen mode Exit fullscreen mode

Thank you.

Top comments (1)

Collapse
 
b0r profile image
b0r

Hi Ramu, welcome!

Thank you for this nice tutorial in Go!

May I just ask you to use this syntax for code blocks that adds code highlighting, so it's easier to read. Please?

Image description

Source:
support.codebasehq.com/articles/ti...