By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
Penny can already store expenses in penny.json and total them, and you have tests for the important rules. Part 3 makes the same data reachable over HTTP: any program that speaks HTTP can list Penny's expenses, add one, or fetch a single entry by ID. The data layer does not change; you wrap it in handlers.
The API you build in this project has four endpoints:
| Request | What it does | Success status |
|---|---|---|
GET /health | Reports that the server is awake | 200 |
GET /expenses | Returns every expense as a JSON array | 200 |
GET /expenses/{id} | Returns one expense, or an error if the ID is unknown | 200 / 404 |
POST /expenses | Validates one JSON expense, assigns its ID, saves it | 201 / 400 |
Work in the same penny folder from steps 35 and 36. Move the Expense type, loadExpenses and saveExpenses out of the old main.go into a new file called store.go, and add nextID there too. The old main.go is replaced completely: the command-line menu from part 2 is not part of the API.
# From inside the penny folder.
ls
# go.mod the module created in step 2
# main.go HTTP handlers, routes and main
# store.go Expense, loadExpenses, saveExpenses, nextID
# penny.json created by the API on the first POST
# Run the test suite before and after the change.
go test ./...Read main.go first: it holds the routes and the handlers. Then read store.go: it holds the data layer. The two files share the Expense type and the store functions, exactly as the earlier lessons defined them.
// ==== file: main.go ====
package main
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"sync"
)
const dataFile = "penny.json"
// api holds everything the handlers need: the list, the file path and a lock.
type api struct {
mu sync.Mutex
expenses []Expense
path string
}
func newAPI(path string) (*api, error) {
expenses, err := loadExpenses(path)
if err != nil {
return nil, err
}
return &api{expenses: expenses, path: path}, nil
}
// writeJSON sends one JSON value with the given status code.
func writeJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(value)
}
func (a *api) health(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
}
func (a *api) handleExpenses(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
a.mu.Lock()
list := append([]Expense{}, a.expenses...)
a.mu.Unlock()
writeJSON(w, http.StatusOK, list)
case http.MethodPost:
var input Expense
if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON body"})
return
}
if strings.TrimSpace(input.Description) == "" {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "description is required"})
return
}
if input.Cents < 0 {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "cents must be zero or more"})
return
}
a.mu.Lock()
input.ID = nextID(a.expenses)
a.expenses = append(a.expenses, input)
err := saveExpenses(a.path, a.expenses)
a.mu.Unlock()
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not save expenses"})
return
}
writeJSON(w, http.StatusCreated, input)
default:
w.Header().Set("Allow", "GET, POST")
writeJSON(w, http.StatusMethodNotAllowed, map[string]string{"error": "method not allowed"})
}
}
func (a *api) handleExpenseByID(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.Header().Set("Allow", "GET")
writeJSON(w, http.StatusMethodNotAllowed, map[string]string{"error": "method not allowed"})
return
}
raw := strings.TrimPrefix(r.URL.Path, "/expenses/")
id, err := strconv.Atoi(raw)
if err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "id must be a number"})
return
}
a.mu.Lock()
defer a.mu.Unlock()
for _, expense := range a.expenses {
if expense.ID == id {
writeJSON(w, http.StatusOK, expense)
return
}
}
writeJSON(w, http.StatusNotFound, map[string]string{"error": "expense not found"})
}
func main() {
store, err := newAPI(dataFile)
if err != nil {
fmt.Println("could not load penny.json:", err)
return
}
mux := http.NewServeMux()
mux.HandleFunc("/health", store.health)
mux.HandleFunc("/expenses", store.handleExpenses)
mux.HandleFunc("/expenses/", store.handleExpenseByID)
fmt.Println("Penny API listening on http://localhost:8080")
if err := http.ListenAndServe(":8080", mux); err != nil {
fmt.Println("server error:", err)
}
}
// ==== file: store.go ====
package main
import (
"encoding/json"
"errors"
"os"
)
// Expense is one row in Penny's list. Money is stored in integer cents.
type Expense struct {
ID int `json:"id"`
Description string `json:"description"`
Cents int `json:"cents"`
Category string `json:"category"`
}
// loadExpenses reads the list from the JSON file at path. A missing file is
// not an error: it means Penny has no expenses yet.
func loadExpenses(path string) ([]Expense, error) {
data, err := os.ReadFile(path)
if errors.Is(err, os.ErrNotExist) {
return []Expense{}, nil
}
if err != nil {
return nil, err
}
var expenses []Expense
if err := json.Unmarshal(data, &expenses); err != nil {
return nil, err
}
return expenses, nil
}
// saveExpenses writes the whole list to path as JSON.
func saveExpenses(path string, expenses []Expense) error {
data, err := json.MarshalIndent(expenses, "", " ")
if err != nil {
return err
}
return os.WriteFile(path, data, 0o644)
}
// nextID returns the largest existing ID plus one, so IDs are never reused.
func nextID(expenses []Expense) int {
maxID := 0
for _, expense := range expenses {
if expense.ID > maxID {
maxID = expense.ID
}
}
return maxID + 1
}Three details make the handlers safe. The api struct holds a mutex, so a read and a write cannot touch the slice at the same time. GET /expenses copies the slice before unlocking, so encoding the response does not run while another request mutates it. POST calls saveExpenses while the lock is still held, so two adds cannot write the file in the wrong order.
The route mux.HandleFunc("/expenses/", ...) ends in a slash deliberately. It matches every path that starts with /expenses/, and the handler trims that prefix and parses the rest as an ID. Atoi from the strconv package turns the text into an int and returns an error for anything that is not a number.
Start the server with go run . in the penny folder, then use a second terminal for these requests. The first POST creates an expense and returns it with the ID the server assigned:
# The server must be running in another terminal.
curl -s -X POST http://localhost:8080/expenses \
-H "Content-Type: application/json" \
-d '{"description":"coffee","cents":450,"category":"food"}'
{"id":1,"description":"coffee","cents":450,"category":"food"}
curl -s -X POST http://localhost:8080/expenses \
-H "Content-Type: application/json" \
-d '{"description":"bus ticket","cents":275,"category":"travel"}'
{"id":2,"description":"bus ticket","cents":275,"category":"travel"}Now read the data back. The list endpoint returns both expenses in the order they were added, and the ID endpoint returns one of them:
curl -s http://localhost:8080/expenses
[{"id":1,"description":"coffee","cents":450,"category":"food"},{"id":2,"description":"bus ticket","cents":275,"category":"travel"}]
curl -s http://localhost:8080/expenses/2
{"id":2,"description":"bus ticket","cents":275,"category":"travel"}
curl -s http://localhost:8080/health
{"status":"ok"}Every error is JSON too, with an error key and a status code that tells the client what kind of problem it was. A client can then handle failures without reading English text.
| Situation | Status | Body |
|---|---|---|
| POST with no description | 400 | {"error":"description is required"} |
| POST with negative cents | 400 | {"error":"cents must be zero or more"} |
| POST with broken JSON | 400 | {"error":"invalid JSON body"} |
GET /expenses/abc | 400 | {"error":"id must be a number"} |
GET /expenses/99 | 404 | {"error":"expense not found"} |
DELETE /expenses | 405 | {"error":"method not allowed"} |
# Missing description: the server refuses to create an unusable expense.
curl -s -X POST http://localhost:8080/expenses \
-H "Content-Type: application/json" \
-d '{"cents":450}'
{"error":"description is required"}
# Unknown ID: a correct request for something that is not there.
curl -s http://localhost:8080/expenses/99
{"error":"expense not found"}The store functions are ordinary Go functions, so they can be tested without HTTP at all. This listing is store.go with a test file for two rules: a missing file loads as an empty list, and a new ID is always larger than every existing ID.
// ==== file: store.go ====
package main
import (
"encoding/json"
"errors"
"os"
)
// Expense is one row in Penny's list. Money is stored in integer cents.
type Expense struct {
ID int `json:"id"`
Description string `json:"description"`
Cents int `json:"cents"`
Category string `json:"category"`
}
// loadExpenses reads the list from the JSON file at path. A missing file is
// not an error: it means Penny has no expenses yet.
func loadExpenses(path string) ([]Expense, error) {
data, err := os.ReadFile(path)
if errors.Is(err, os.ErrNotExist) {
return []Expense{}, nil
}
if err != nil {
return nil, err
}
var expenses []Expense
if err := json.Unmarshal(data, &expenses); err != nil {
return nil, err
}
return expenses, nil
}
// saveExpenses writes the whole list to path as JSON.
func saveExpenses(path string, expenses []Expense) error {
data, err := json.MarshalIndent(expenses, "", " ")
if err != nil {
return err
}
return os.WriteFile(path, data, 0o644)
}
// nextID returns the largest existing ID plus one, so IDs are never reused.
func nextID(expenses []Expense) int {
maxID := 0
for _, expense := range expenses {
if expense.ID > maxID {
maxID = expense.ID
}
}
return maxID + 1
}
// ==== file: store_test.go ====
package main
import "testing"
func TestLoadExpensesMissingFile(t *testing.T) {
expenses, err := loadExpenses("does-not-exist.json")
if err != nil {
t.Fatalf("loadExpenses returned error: %v", err)
}
if len(expenses) != 0 {
t.Errorf("loadExpenses returned %d expenses; want 0", len(expenses))
}
}
func TestNextID(t *testing.T) {
tests := []struct {
name string
expenses []Expense
want int
}{
{name: "empty list", expenses: nil, want: 1},
{name: "one expense", expenses: []Expense{{ID: 4}}, want: 5},
{name: "gaps do not matter", expenses: []Expense{{ID: 2}, {ID: 9}, {ID: 5}}, want: 10},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
if got := nextID(tc.expenses); got != tc.want {
t.Errorf("nextID(%v) = %d; want %d", tc.expenses, got, tc.want)
}
})
}
}Before you call part 3 finished, check every line on this list in a terminal. Each one tests a rule from the earlier lessons.
curl each one and read the body and the status code.GET /expenses still returns the same list.error key.id, description, cents and category, and money stays in integer cents.go vet ./... prints nothing and go test ./... passes.Key takeaways
Part 3 wraps the existing Penny store in HTTP handlers; the data model and JSON tags do not change.
Routes go on a http.ServeMux; each handler takes w http.ResponseWriter and r *http.Request.
A shared mutex protects the expense slice because several requests can arrive at the same time.
POST validates, assigns nextID, saves to penny.json and returns 201; errors return JSON with 400, 404 or 405.
Test the store directly with go test ./..., and test handlers with httptest when you add them.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.