REST API Response JSON to Go Structs
Convert typical REST API response JSON into well-structured Go types. Covers pagination, error envelopes, and nested resource patterns.
Detailed Explanation
Modeling REST API Responses in Go
Most REST APIs wrap their data in a standard envelope with metadata like pagination, status, and error details. Converting these patterns to Go structs requires careful type modeling.
Typical API Response
{
"status": "ok",
"data": {
"users": [
{ "id": 1, "name": "Alice", "email": "alice@example.com" },
{ "id": 2, "name": "Bob", "email": "bob@example.com" }
]
},
"pagination": {
"page": 1,
"per_page": 20,
"total": 152,
"total_pages": 8
}
}
Generated Go Structs
type APIResponse struct {
Status string `json:"status"`
Data Data `json:"data"`
Pagination Pagination `json:"pagination"`
}
type Data struct {
Users []User `json:"users"`
}
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
}
type Pagination struct {
Page int `json:"page"`
PerPage int `json:"per_page"`
Total int `json:"total"`
TotalPages int `json:"total_pages"`
}
Generic Response Wrapper
In practice, you often create a generic wrapper to reuse across endpoints:
type APIResponse[T any] struct {
Status string `json:"status"`
Data T `json:"data"`
Pagination *Pagination `json:"pagination,omitempty"`
Error *APIError `json:"error,omitempty"`
}
type APIError struct {
Code string `json:"code"`
Message string `json:"message"`
}
Usage: APIResponse[UserListData] for user lists, APIResponse[OrderData] for orders.
Error Handling
APIs often return a different structure on error. Using pointer fields with omitempty or a separate error struct handles both cases cleanly.
Use Case
Building API client libraries in Go requires modeling both success and error responses. A well-designed struct hierarchy lets you unmarshal any endpoint's response into the same wrapper type.