Sling Academy
Home/Golang/Creating REST APIs with Go: Step-by-Step

Creating REST APIs with Go: Step-by-Step

Last updated: November 27, 2024

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/restapi

Step 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.

Next Article: Building gRPC Servers in Go

Previous Article: Using `http2` for Faster Networking in Go

Series: Networking and Server

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant