Building a Basic API in Go: A Beginner’s Guide

Building a Basic API in Go: A Beginner’s Guide

·

3 min read


Go (or Golang) is a statically typed, compiled language designed for simplicity and efficiency. It’s particularly well-suited for building scalable and high-performance applications, including APIs. In this post, we’ll walk through the basics of setting up a simple API in Go, covering essential concepts, file structure, and code.

Why Go for APIs?

Go’s strengths include:
- Performance: Compiled language with efficient concurrency.
- Standard Library: Powerful and minimalistic standard libraries, including net/http for building HTTP servers.

There are some other well known third party libraries that can be used to handle API requests, however, since this is a very beginner friendly guide, we will be using the Go’s own library net/http .

Setting Up Your Go Environment

Before we dive into the code, ensure you have Go installed on your system. You can download it from the official Go website.

Verify your installation by running:

go version

The output should look something like this (on macOS):

go version go1.22.5 darwin/arm64

At the time I wrote this code, I was using version 1.22.5, yours might be different.

File Structure

Here’s a simple file structure for a basic Go API project:

/basic-go-api
    |-- main.go
    |-- go.mod
    |-- go.sum

main.go:
This is where your application code will reside.

go.mod:
This file manages your project’s dependencies. It is created by running go mod init <module-name> .

go.sum:
This file is automatically generated and contains cryptographic hashes of module dependencies.


Creating a Simple API

Let’s start coding a basic API. Our example will create a simple HTTP server that responds with “Hello, World!” when accessed.

Step 1: Initialise Your Go Module
Navigate to your project directory and run:

go mod init github.com/<user-name>/basic-go-api

It’s a good practice to use a module name format like github.com/<your-username>/module-name. This naming convention helps in identifying and managing your module, especially if you plan to publish it or collaborate with others.

This command creates a go.mod file to manage your module.

Step 2: Write Your API Code Create a file named main.go with the following content:

package main

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


func main() {
    http.HandleFunc("/", helloHandler)
    fmt.Println("Server is running on port 8000")
    log.Fatal(http.ListenAndServe(":8000", nil))
}

func helloHandler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusOK)

    json.NewEncoder(w).Encode(map[string]string{"message": "Hello, World!"})
}

Code Explanation:
1. Imports:
- encoding/json for encoding / decoding JSON format.
- fmtfor formatted I/O operations.
- logfor logging errors.
- net/http for HTTP server and client implementations.

2. main:
- http.HandleFunc('/', helloHandler) sets up the route for the root URL.
- fmt.Println("Server is running on port 8000") outputs a message to the console.
- log.Fatal(http.ListenAndServe(":8000", nil)) starts the server on port 8000 and logs any fatal errors.

3. helloHandler:
- w.Header().Set("Content-Type", "application/json") sets the response content type to JSON.
- w.WriteHeader(http.StatusOK) sends a 200 OK HTTP status code.
- json.NewEncoder(w).Encode(map[string]string{"message": "Hello, World!"}) encodes a map into JSON and writes it to the response.

Step 3: Run the Server
In your terminal, navigate to the project directory and execute:

go run main.go

You should see:

Server is running on port 8000

Open a web browser or use curl to test your API:

curl http://localhost:8000

You should get a JSON response:

{"message": "Hello, World!"}

Conclusion

Congratulations! You’ve just built a very basic API in Go that returns a JSON response. Here’s a recap of what we covered:

  • Setting up the Go environment.

  • Structuring a simple Go project.

  • Writing a basic HTTP server that responds with JSON.

Go’s minimalism and powerful standard library make it a great choice for building APIs, even as a beginner. By following the best practice of naming your module with a format like github.com/<your-username>/basic-go-api, you ensure better organisation and ease of future collaboration.

Feel free to experiment with the code, and stay tuned for more in-depth guides on Go!