Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Structs as API Models | Structs as Behavioral Units
Struct-Based Design in Go

bookStructs as API Models

Swipe to show menu

When building backend APIs in Go, you often need to model the data that flows through your endpoints. Structs are the primary way to define the shape of both requests and responses. By using structs, you can clearly describe the expected fields, their types, and how they map to JSON, which is the most common data format for APIs. This is achieved by attaching field tags to struct fields, allowing Go's standard library to automatically serialize and deserialize data between Go structs and JSON objects.

main.go

main.go

copy
12345678910111213141516171819202122232425262728293031323334353637383940414243
package main import ( "encoding/json" "fmt" ) // Order models an API request/response for an e-commerce order. type Order struct { ID int `json:"id"` Customer string `json:"customer"` Items []string `json:"items"` UnitPrices []float64 `json:"unit_prices"` Quantities []int `json:"quantities"` } // TotalPrice calculates the total price for the order. func (o *Order) TotalPrice() float64 { total := 0.0 for i := range o.Items { if i < len(o.UnitPrices) && i < len(o.Quantities) { total += o.UnitPrices[i] * float64(o.Quantities[i]) } } return total } func main() { order := Order{ ID: 101, Customer: "Alice", Items: []string{"Book", "Pen"}, UnitPrices: []float64{12.5, 1.5}, Quantities: []int{2, 5}, } // Serialize to JSON data, _ := json.Marshal(order) fmt.Println("Serialized JSON:", string(data)) // Calculate total price fmt.Printf("Total price: %.2f\n", order.TotalPrice()) }

Struct tags in Go are string annotations that appear after field declarations, enclosed in backticks. For API models, the most common use is to control how fields are mapped to JSON keys using the json tag. When you marshal or unmarshal JSON, the encoding/json package reads these tags to match struct fields with JSON object properties.

Best practices for API model design include:

  • Use exported field names (capitalized) so that encoding/json can access them;
  • Keep struct definitions focused on the data actually needed by the API;
  • Use clear, consistent JSON tag names that match your API specification;
  • Avoid including business logic in API model structs, except for utility methods like total calculations;
  • Document any non-obvious field mappings or required fields.
question mark

Which of the following best describes the role of struct tags in Go API model design?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Sectionย 1. Chapterย 4

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Sectionย 1. Chapterย 4
some-alt