How to Write a REST API in Go in 30 Minutes: A Step-by-Step Guide

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction: Why Go is Ideal for REST APIs



Go (or Golang) is a modern compiled programming language created at Google. It combines the performance of C++ with the simplicity of Python, making it an ideal choice for building high-load web services and REST APIs. Unlike many other languages, Go has built-in support for HTTP servers, multithreading, and fast compilation.



In this guide, we will step by step create a full-fledged REST API for managing a Todo List. You will learn:

  • How to set up an HTTP server in Go
  • How to work with JSON requests and responses
  • How to implement CRUD operations (Create, Read, Update, Delete)
  • How to test the API using curl or Postman


The entire process will take you no more than 30 minutes. Let's go!



1. Installation and Project Setup



Before writing code, make sure you have Go installed. You can check this with the command:

go version


If Go is not installed, download the latest version from the official website.



Create a new directory for the project and initialize the module:

mkdir go-rest-apicd go-rest-apigo mod init go-rest-api


Now create a file main.go — all our code will be in it. For convenient route handling, we will use the standard net/http library, which is already built into Go. No third-party dependencies are required — this is one of the main advantages of the language.



2. Defining the Data Structure and Storage



Let's start by describing the data model. For simplicity, we will store tasks in memory (in a slice) rather than in a database. Let's create a Task structure and a global ID counter:



package main

import ( "encoding/json" "log" "net/http" "strconv" "strings" "sync")

// Task represents a tasktype Task struct { ID int `json:"id"` Title string `json:"title"` Done bool `json:"done"`}

// Task storage (in memory)var ( tasks []Task nextID int = 1 mu sync.Mutex)


Note the sync.Mutex — it is needed for thread-safe access to data, since a Go server can process requests concurrently.



3. Implementing CRUD Operations



Now let's write the main handlers for each HTTP method. We will use the URL routing pattern:

  • GET /tasks — get all tasks
  • POST /tasks — create a new task
  • GET /tasks/{id} — get a task by ID
  • PUT /tasks/{id} — update a task
  • DELETE /tasks/{id} — delete a task


3.1. Getting All Tasks (GET /tasks)

func getTasks(w http.ResponseWriter, r *http.Request) {    mu.Lock()    defer mu.Unlock()

w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(tasks)}


3.2. Creating a Task (POST /tasks)

func createTask(w http.ResponseWriter, r *http.Request) {    var newTask Task    if err := json.NewDecoder(r.Body).Decode(&newTask); err != nil {        http.Error(w, "Invalid JSON", http.StatusBadRequest)        return    }

mu.Lock() newTask.ID = nextID nextID++ tasks = append(tasks, newTask) mu.Unlock()

w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusCreated) json.NewEncoder(w).Encode(newTask)}


3.3. Getting, Updating, and Deleting by ID

For these operations, we need to extract the ID from the URL. The standard Go library does not have a built-in path parser, so we will write a simple utility:



                

Blogs

Book Recommendations