DEV Community

Prashant Kumar
Prashant Kumar

Posted on

3 3

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 (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
)

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 := "http://www.omdbapi.com/?t=" + movieName + "&apikey=your_key"

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

    // check for errors
    if err != nil {
        log.Fatal(err)
    }

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

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

    if err != nil {
        log.Fatal(err)
    }

    // 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 {
        log.Fatal(err)
    }

    // 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

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay