Design request and response contracts
Design request and response contracts
A data transfer object (DTO) describes the external fields accepted or returned by an API. Keep input, domain state and output types separate so a client cannot set server-owned fields and private data is not accidentally serialized. Document types, required fields, nullability, media type and status codes. This example uses a synthetic record.
package main
import ( "encoding/json" "fmt")
type Create struct { Name string `json:"name"`}type Book struct { ID int Name string InternalNote string}type View struct { ID int `json:"id"` Name string `json:"name"`}
func main() { var in Create if e := json.Unmarshal([]byte(`{"name":"Go"}`), &in); e != nil { panic(e) } b := Book{7, in.Name, "private"} out, e := json.Marshal(View{b.ID, b.Name}) if e != nil { panic(e) } fmt.Println(string(out))}Explicit projection prevents the internal note from appearing in the response. Unmarshal by itself ignores unknown keys; the next lesson adds strict decoding. Never bind a request directly to a persistence model containing roles, owner IDs or internal flags.
Expected output:
{"id":7,"name":"Go"}Check zero values and field presence
package main
import ( "encoding/json" "fmt")
type Patch struct { Count *int `json:"count"`}
func main() { for _, s := range []string{`{}`, `{"count":0}`, `{"count":null}`} { var p Patch if e := json.Unmarshal([]byte(s), &p); e != nil { panic(e) } if p.Count == nil { fmt.Println("absent or null") } else { fmt.Println(*p.Count) } }}A pointer distinguishes zero from absent or null, but does not distinguish absent from explicit null on a fresh struct. If that distinction matters, use an explicit presence type or inspect raw fields. Define the update media type and rules before implementing partial updates; do not treat all PATCH requests as JSON object merges.
Expected output:
absent or null0absent or nullTry it locally
Project a synthetic customer with ID 2, label Mina and an internal flag into a response containing only id and label. Marshal it and print the JSON.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
REST API 02: Design request and response contracts
Check the lesson objective before moving on.
Why separate input and output types?
What does a nil *int on a fresh DTO mean after JSON decoding?