Exercise 7: Introduction to APIs with Go

Learn how to send and receive data via APIs using Go.

What is an API?

An API (Application Programming Interface) allows different applications to communicate via HTTP.

APIs are commonly used to fetch data from external servers, such as weather forecasts, financial information, or social media data.

Why Use APIs in Go?

Making an HTTP GET Request in Go

We use the `net/http` package to perform a GET request and retrieve data.

package main

import (
    "fmt"
    "io"
    "net/http"
)

func main() {
    response, err := http.Get("https://jsonplaceholder.typicode.com/todos/1")
    if err != nil {
        fmt.Println("Error making request:", err)
        return
    }
    defer response.Body.Close()

    body, _ := io.ReadAll(response.Body)
    fmt.Println(string(body))
}

In this example, we send a GET request to a public API and display the JSON response.

Creating a Simple API with Go

Go allows you to build HTTP servers easily using the `net/http` package.

package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, API!")
}

func main() {
    http.HandleFunc("/", handler)
    fmt.Println("Server started at http://localhost:8080")
    if err := http.ListenAndServe(":8080", nil); err != nil {
        fmt.Println("Server error:", err)
    }
}

This program starts a simple HTTP server that responds "Hello, API!" to every request and handles errors.

Best Practices for APIs in Go

Exercise Instructions

Expected Output

{ "userId": 1, "id": 1, "title": "delectus aut autem", "completed": false }

📚 Learn more about using APIs in Go:

Official Go Documentation
← Previous Exercise Back to Home

🚀 Enjoying these exercises? If you find them useful and want to support my work, buying me a coffee would be greatly appreciated! ☕😊


☕ Buy me a coffee