Building a RESTful API in Go: A Step-by-Step Tutorial for Developers
Go (Golang) has become a top choice for building fast, scalable RESTful APIs thanks to its simplicity and excellent standard library. In this practical tutorial, you’ll create a minimal but functional books API with `net/http` and the popular `gorilla/mux` router. By the end, you’ll have a solid pattern for handling CRUD operations and JSON responses.
First, set up your project and dependencies. Create a new directory, run `go mod init books-api`, and install the router with `go get github.com/gorilla/mux`. This gives you a clean module and URL parameter parsing built in.
Define the Data Model and Mock Storage
Start by defining a Book struct with JSON tags, then create a slice as an in-memory store. For example:
ID string– unique identifierTitle string– book nameAuthor string– writer
type Book struct {
ID string `json:"id"`
Title string `json:"title"`
Author string `json:"author"`
}
Implement CRUD Handlers
GET and POST Endpoints
Write handlers that return all books, return a single book by ID, create a new book, and update or delete existing ones. Use r.Vars() to extract path variables and json.NewEncoder for responses.
Enable Middleware and Logging
Wrap your router with simple logging middleware that records each request method and path. This improves debugging and gives your API production-ready behavior without extra dependencies.
Wire Up Routes and Start the Server
In your main() function, create a new router, register each handler with methods like HandleFunc("/books", getBooks).Methods("GET"), and call http.ListenAndServe(":8080", r). Test with curl or Postman.
Conclusion
You’ve built a working RESTful API in Go using just a few lines of code. This pattern—structs, mux routes, and JSON handlers—forms the foundation for any real-world service. From here, you can add a database, validation, and authentication. Happy coding!