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

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

September 1, 2024 · 3 min read

TL;DR

Go's net/http standard library is all you need to build a working REST API. Define handler functions, register routes with http.HandleFunc, and start a server with http.ListenAndServe. No framework required — Go's built-in tooling handles routing, JSON encoding, and HTTP lifecycle out of the box.

Go consistently ranks among the top 10 most-used programming languages in Stack Overflow's annual Developer Survey.

Stack Overflow Developer Survey 2024

Go's net/http package is part of the standard library and requires no third-party dependencies to build a production HTTP server.

Go Standard Library Documentation

Go compiles to a single static binary, which simplifies deployment and reduces container image sizes compared to interpreted runtimes.

Go Documentation

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!

In Depth Guides

Frequently Asked Questions

How do I build a REST API in Go?

Use the net/http package from Go's standard library. Define handler functions with the signature func(w http.ResponseWriter, r *http.Request), register them with http.HandleFunc, and start the server using http.ListenAndServe. For larger projects, consider a router like chi or gorilla/mux.

Do I need a framework to build an API in Go?

No. Go's standard library net/http is sufficient for building a fully functional HTTP API. Frameworks like Gin or Echo add routing conveniences and middleware, but are optional — many production APIs run on net/http alone.

How do I return JSON from a Go API handler?

Set the Content-Type header to application/json, then use json.NewEncoder(w).Encode(yourStruct) to write a JSON response. The encoding/json package is part of the standard library.

What is go.mod used for?

go.mod defines your module's name and its dependency requirements. Create it by running go mod init <module-name> in your project root. Go uses it to resolve and version external packages.

GitHub
LinkedIn
X