Go REST API Tutorial for Beginners

Updated 5 min read
Go REST API featured image: cards showing GET, POST and DELETE endpoints

A Go REST API lets other apps create, read and delete your data over HTTP using JSON. In this post, you will build a small book API with only the standard library. Then you will test every endpoint with curl. Each step comes with code that you can run yourself.

This project brings several lessons together. You will need the server basics from building your first web server in Go and the encoding rules from JSON encoding and decoding in Go. We also protect shared data with a mutex, as shown in the sync package, WaitGroup and Mutex.

What Is a Go REST API?

To begin with, REST is a simple style for web APIs. Then each URL names a thing, like /books, and the HTTP method says what to do with it. For example, GET reads data, POST creates it and DELETE removes it.

For example, think of a library desk. You can ask for the list of books, borrow one by its number, donate a new one or return one. A Go REST API offers the same actions, only through URLs instead of a librarian.

Planning the Go REST API Endpoints

Method and pathWhat it doesSuccess code
GET /booksList all books200 OK
GET /books/{id}Get one book200 OK
POST /booksCreate a book201 Created
DELETE /books/{id}Delete a book204 No Content

Therefore, planning first keeps the design clean. The diagram below shows how one request flows through these pieces.

Go REST API diagram showing a client request flowing through the router, handler and store

The client sends JSON, the router picks a handler, the handler uses the store, and a JSON response goes back.

The Book Model and Store

type Book struct {
	ID     int    `json:"id"`
	Title  string `json:"title"`
	Author string `json:"author"`
}

type Store struct {
	mu     sync.Mutex
	books  map[int]Book
	nextID int
}

func NewStore() *Store {
	return &Store{books: map[int]Book{}, nextID: 1}
}

For the moment, books live in a map in memory, so they disappear when the server stops. Later, however, you can swap the map for a real database. The mutex matters, because every request runs in its own goroutine.

A Helper for JSON Responses

func writeJSON(w http.ResponseWriter, status int, v any) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	json.NewEncoder(w).Encode(v)
}

In short, this small helper sets the header, the status and the body in the right order. As a result, every handler stays short.

Building the Go REST API Handlers

List All Books

func (s *Store) list(w http.ResponseWriter, r *http.Request) {
	s.mu.Lock()
	defer s.mu.Unlock()
	books := make([]Book, 0, len(s.books))
	for i := 1; i < s.nextID; i++ {
		if b, ok := s.books[i]; ok {
			books = append(books, b)
		}
	}
	writeJSON(w, http.StatusOK, books)
}

We loop by ID so the list always comes back in order, since map order is random. Also, make ensures an empty list prints as [], not null.

Get One Book

func (s *Store) get(w http.ResponseWriter, r *http.Request) {
	id, err := strconv.Atoi(r.PathValue("id"))
	if err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid id"})
		return
	}
	s.mu.Lock()
	b, ok := s.books[id]
	s.mu.Unlock()
	if !ok {
		writeJSON(w, http.StatusNotFound, map[string]string{"error": "book not found"})
		return
	}
	writeJSON(w, http.StatusOK, b)
}

Create a Book

func (s *Store) create(w http.ResponseWriter, r *http.Request) {
	var b Book
	if err := json.NewDecoder(r.Body).Decode(&b); err != nil || b.Title == "" {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": "title is required"})
		return
	}
	s.mu.Lock()
	b.ID = s.nextID
	s.books[b.ID] = b
	s.nextID++
	s.mu.Unlock()
	writeJSON(w, http.StatusCreated, b)
}

Most importantly, always validate input before saving it. For example, an empty title gets a clear 400 Bad Request instead of bad data.

Delete a Book

func (s *Store) remove(w http.ResponseWriter, r *http.Request) {
	id, _ := strconv.Atoi(r.PathValue("id"))
	s.mu.Lock()
	_, ok := s.books[id]
	delete(s.books, id)
	s.mu.Unlock()
	if !ok {
		writeJSON(w, http.StatusNotFound, map[string]string{"error": "book not found"})
		return
	}
	w.WriteHeader(http.StatusNoContent)
}

Wiring Up the Go REST API Routes

func main() {
	store := NewStore()
	mux := http.NewServeMux()
	mux.HandleFunc("GET /books", store.list)
	mux.HandleFunc("GET /books/{id}", store.get)
	mux.HandleFunc("POST /books", store.create)
	mux.HandleFunc("DELETE /books/{id}", store.remove)

	log.Println("API running on :8081")
	log.Fatal(http.ListenAndServe(":8081", mux))
}

In fact, each route in the Go REST API pairs a method and a path with a handler. So the code reads almost exactly like the plan table above.

Testing the Go REST API with curl

curl -X POST localhost:8081/books -d '{"title":"Go Basics","author":"Asha"}'
# {"id":1,"title":"Go Basics","author":"Asha"}

curl -X POST localhost:8081/books -d '{"title":"Web APIs","author":"Ravi"}'
# {"id":2,"title":"Web APIs","author":"Ravi"}

curl localhost:8081/books/1
# {"id":1,"title":"Go Basics","author":"Asha"}

curl localhost:8081/books/9
# {"error":"book not found"}

curl -X POST localhost:8081/books -d '{}'
# {"error":"title is required"}

curl -i -X DELETE localhost:8081/books/1
# HTTP/1.1 204 No Content

As a result, every endpoint returns the right status and a clear JSON message. Next, try curl localhost:8081/books to confirm only book 2 remains.

Common Mistakes in a Go REST API

Problem you seeWhy it happensHow to fix it
Empty list shows nullThe slice was nil.Create it with make or [ ]Book{}.
Client cannot read the responseThe Content-Type header is missing.Set application/json first.
Random crashes under loadThe map has no lock.Guard it with a mutex.

However, the missing lock may pass every test and still fail in production. REST API design is a favourite interview topic too, so practise with my Go interview questions and answers.

Official Resources

These pages come straight from the Go team, so they are always accurate and up to date.

Quick Recap

  • A Go REST API maps HTTP methods and paths to actions on data.
  • Plan endpoints and status codes before writing code.
  • A writeJSON helper keeps headers, status and body in order.
  • Validate input and return clear error messages.
  • Protect shared data with a mutex, since requests run concurrently.

What’s Next?

Your API stores books in memory for now. Next, we will connect it to a real database so the data survives a restart.

Next lesson: Go Database Tutorial with database/sql