How I Built a REST API from Scratch in Go: A Beginner’s Guide
So, here’s the deal: I wanted to try my hand at Go (aka Golang) and figured, what better way to learn than to build something useful? A REST API seemed like a great starting point. It’s practical, it’s scalable, and let’s be honest—it looks cool when you tell people, “Yeah, I built an API in Go.”
This guide walks you through how I created a basic API that manages a list of books. If you’re new to Go or APIs, don’t worry—I’ll keep things simple but useful. Let’s dive in!
Why Go?
Good question! Go is like that friend who’s always punctual, gets straight to the point, and doesn’t overcomplicate things. It’s fast, lightweight, and perfect for building APIs that can handle a lot of traffic without breaking a sweat. Plus, learning Go adds some serious swagger to your developer resume.
What Are We Building?
We’re making a simple REST API for a book collection. Think of it as a library, but without the late fees. Here’s what it’ll do:
GET /books:
Get a list of all books.GET /books/{id}:
Get details about a specific book.POST /books:
Add a new book to the collection.PUT /books/{id}:
Update an existing book.DELETE /books/{id}:
Remove a book (goodbye, bad reads).
Step 1: Setting Up the Project
First, create a new directory for the project:
mkdir go-rest-api
cd go-rest-api
Now, initialize the Go module:
go mod init github.com/yourusername/go-rest-api
Boom! You’ve just created the skeleton of your project. 🎉
Step 2: Installing the Gorilla Mux Package
For routing (aka figuring out where to send requests), we’ll use a popular package called gorilla/mux
. Think of it as the GPS for your API. Install it with:
go get -u github.com/gorilla/mux
Step 3: Writing the Code
Let’s jump into main.go
and start coding. This file will be the brains of the operation. Here’s what it’ll look like:
package main
import (
"encoding/json"
"net/http"
"github.com/gorilla/mux"
)
type Book struct {
ID string `json:"id"`
Title string `json:"title"`
Author string `json:"author"`
}
var books []Book
func main() {
router := mux.NewRouter()
// Define the API endpoints
router.HandleFunc("/books", getBooks).Methods("GET")
router.HandleFunc("/books/{id}", getBook).Methods("GET")
router.HandleFunc("/books", createBook).Methods("POST")
router.HandleFunc("/books/{id}", updateBook).Methods("PUT")
router.HandleFunc("/books/{id}", deleteBook).Methods("DELETE")
// Start the server
http.ListenAndServe(":8000", router)
}
Step 4: Adding the Endpoints
Here’s where the magic happens. We’ll create the functions that handle each API request.
Get All Books
func getBooks(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(books)
}
Get a single Book
func getBook(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
for _, book := range books {
if book.ID == params["id"] {
json.NewEncoder(w).Encode(book)
return
}
}
http.NotFound(w, r)
}
Add a New Book
func createBook(w http.ResponseWriter, r *http.Request) {
var book Book
json.NewDecoder(r.Body).Decode(&book)
books = append(books, book)
json.NewEncoder(w).Encode(book)
}
Update a Book
func updateBook(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
for i, book := range books {
if book.ID == params["id"] {
books = append(books[:i], books[i+1:]...)
var updatedBook Book
json.NewDecoder(r.Body).Decode(&updatedBook)
updatedBook.ID = params["id"]
books = append(books, updatedBook)
json.NewEncoder(w).Encode(updatedBook)
return
}
}
http.NotFound(w, r)
}
Delete a Book
func deleteBook(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
for i, book := range books {
if book.ID == params["id"] {
books = append(books[:i], books[i+1:]...)
w.WriteHeader(http.StatusNoContent)
return
}
}
http.NotFound(w, r)
}
Step 5: Testing the API
Fire up the server with:
go run main.go
Now test your endpoints using Postman, cURL, or any other tool. For example, to add a book:
curl -X POST -H "Content-Type: application/json" -d '{"id":"1","title":"The Go Gopher","author":"John Doe"}' http://localhost:8000/books
Step 6: What’s Next?
Congrats! You’ve built a REST API in Go. From here, you can:
- Hook it up to a real database like PostgreSQL.
- Add authentication to secure your endpoints.
- Make it fancier with middleware for logging or error handling.
Final Thoughts
Building this API was a cool way for me to get my hands dirty with Go and figure out some of the basics of backend development. Honestly, I’m still learning, and there’s a lot I don’t know yet, but this project helped me take a step forward. 🚀
If you’re just getting started too, don’t stress about getting everything right—just try things out and learn as you go. 💡
You can check out the full project on GitHub here. Feel free to fork it, try it out, or even suggest improvements—I’d love to hear what you think!