In this article, we’ll guide you through creating a simple REST API using the Go programming language. REST APIs are essential components for many software applications, enabling different software systems to communicate with each other over the internet. Let’s dive into building a REST API in Go step-by-step.
Prerequisites
Before starting, make sure you have Go installed on your machine. You can download and install it from the official Go website. Additionally, you will need a code editor like Visual Studio Code, and a command line terminal to execute Go commands.
Step 1: Create a New Go Project
First, let's create a new directory for our project and initialize it as a Go module:
$ mkdir restapi
$ cd restapi
$ go mod init example.com/restapiStep 2: Set Up the HTTP Server
Go has excellent built-in support for HTTP. Add the following code to create a simple HTTP server:
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World!")
})
http.ListenAndServe(":8080", nil)
}This code sets up an HTTP server on port 8080 that returns "Hello, World!" when accessed at the root URL.
Step 3: Define API Endpoints
Now, it’s time to define some API endpoints. For this example, we will create endpoints to fetch and create items. Update your main file as follows:
package main
import (
"encoding/json"
"net/http"
)
type Item struct {
ID string `json:"id"`
Name string `json:"name"`
}
var inventory = []Item{
{ID: "1", Name: "Item1"},
{ID: "2", Name: "Item2"},
}
func main() {
http.HandleFunc("/items", getItems)
http.HandleFunc("/items/add", addItem)
http.ListenAndServe(":8080", nil)
}
func getItems(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(inventory)
}
func addItem(w http.ResponseWriter, r *http.Request) {
var newItem Item
json.NewDecoder(r.Body).Decode(&newItem)
inventory = append(inventory, newItem)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(newItem)
}Step 4: Test Your API
Finally, it’s time to test the API. You can use tools like curl or Postman to send requests to your server.
# Test: Get all items
$ curl http://localhost:8080/items
# Test: Add a new item
$ curl -X POST http://localhost:8080/items/add -d '{"id":"3","name":"Item3"}' -H "Content-Type: application/json"After executing the above commands, you should see the list of items including the newly added item when accessing the GET /items endpoint.
Conclusion
Congratulations! You've successfully created a basic REST API using Go. This tutorial covered setting up a project, creating an HTTP server, defining endpoints, and testing your API. With this foundation, you can extend your API further by adding additional functionality, integrating with databases, and incorporating more advanced error handling.