DEV Community

Prashant Kumar
Prashant Kumar

Posted on

Consuming REST API in GO

Consuming REST API GO

Consuming REST API is really simple in GO. The net/http comes with GO standard modules, which we are going to use in this article.

package main

import (

func getMovieDetails(movieName string) map[string]interface{} {

    // response is going to be stored in this variable
    var movieDetailResponse map[string]interface{}

    // url to be fetched, replace the apiikey with your own
    url := "" + movieName + "&apikey=your_key"

    // create a new http request
    res, err := http.Get(url)

    // check for errors
    if err != nil {

    // close the response body when function returns
    defer res.Body.Close()

    // read the response body
    body, err := ioutil.ReadAll(res.Body)

    if err != nil {

    // unmarshal the json response
    // the body is in []byte format, so we need to convert it to json
    // we can use json.Unmarshal(body, &movieDetailResponse) to unmarshal byte array to json
    if err := json.Unmarshal(body, &movieDetailResponse); err != nil {

    // return the movie details
    return movieDetailResponse


func main() {
    movieName := "k.g.f chapter 2"
    movieDetail := getMovieDetails(movieName)
    // print the movie details
    fmt.Println("Title", movieDetail["Title"])
    fmt.Println("Genre", movieDetail["Genre"])
    fmt.Println("Plot", movieDetail["Plot"])

Enter fullscreen mode Exit fullscreen mode

Hope this was insightful.

For more instant updates follow me on twitter

Discussion (0)