May is Coding
December 9th, 0202

Consume API using GO

GO

A few days ago I have to look at consuming API with GO from Ghost so here is what I learnt.  

A very simple example of how to consume API and print it as text to console. It's not much but it's good to start. 

package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "os"
)

func main() {
    var endpoint = "http://your-addres.domain/api/endpoint"

    response, err := http.Get(endpoint)

    if err != nil {
        fmt.Print(err.Error())
        os.Exit(1)
    }

    responseData, err := ioutil.ReadAll(response.Body)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(string(responseData))
}

Next, it will be good if I can return objects to use in my app instead of text. And go has to function for it called unmarshall. Unmarshalling JSON response need JSON module so I have to import "encoding/json".

Another thing I need was struct in which will be my json respone parsed. Following syntax is example for Ghost API for posts.

type Response struct {
    Posts []Post    `json: "posts"`
}

type Post struct {
    Id string       `json: "id"`
    Title string    `json: "title"`
    Slug string     `json: "slug"`
    Excerpt string  `json: "excerpt"`
    Html string     `json: "html"`
}

and define new variable in main function var responseObject Response

next i add unmarshall after response which will parse json string to my object syntax for it is as follows:

json.Unmarshal(responseData, &responseObject)

Now you can go trough array of object.

for _, post := range responseObject.Posts {
  fmt.Println("Id:", post.Id, "with title:", post.Title, "slug:", post.Slug)
}

Complete example is here:

package main

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

type Response struct {
    Posts []Post    `json: "posts"`
}

type Post struct {
    Id string       `json: "id"`
    Title string    `json: "title"`
    Slug string     `json: "slug"`
    Excerpt string  `json: "id"`0
    Html string     `json: "id"`1
}

func main() {
    var endpoint = "http://your-addres.domain/api/endpoint"
    var responseObject Response

    response, err := http.Get(endpoint)

    if err != nil {
        fmt.Print(err.Error())
        os.Exit(1)
    }

    responseData, err := ioutil.ReadAll(response.Body)
    if err != nil {
        log.Fatal(err)
    }
    // fmt.Println(string(responseData))

    json.Unmarshal(responseData, &responseObject)

    for _, post := range responseObject.Posts {
        fmt.Println("Id:", post.Id, "with title:", post.Title, "slug:", post.Slug)
    }
}

Thank You for reading.