How to make api calls in Golang

Last updated on Mar 4, 2023 by Suraj Sharma



In this tutorial, you will how you can make GET and POST methods requests to external APIs in Golang.


To make API calls in Go, we use the built-in net/http package.

Here's an example to make an HTTP GET request in Go:


  package main

  import (
    "fmt"
    "net/http"
  )

  func main() {
    url := "https://jsonplaceholder.typicode.com/posts/1"
    resp, err := http.Get(url)
    if err != nil {
      panic(err)
    }
    // close the request once it is done
    defer resp.Body.Close()
    fmt.Println(resp.Status)
  }


We can also make more complex API calls, such as HTTP POST requests, by using the http.NewRequest function and the http.Client type.

Here's an example to make POST request in Go:


package main

  import (
      "bytes"
      "encoding/json"
      "fmt"
      "net/http"
  )

  type Post struct {
    UserID int    `json:"userId"`
    ID     int    `json:"id"`
    Title  string `json:"title"`
    Body   string `json:"body"`
  }

  func main() {
    post := Post{UserID: 1, ID: 1, Title: "My Post", Body: "Hello, world!"}
    url := "https://jsonplaceholder.typicode.com/posts"
    jsonStr, err := json.Marshal(post)
    if err != nil {
        panic(err)
    }
    req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
    if err != nil {
        panic(err)
    }
    req.Header.Set("Content-Type", "application/json")
    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    fmt.Println(resp.Status)
  }


Related Solutions


Rate this post


Suraj Sharma is a Full Stack Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.