Test API contracts and compatibility
Test API contracts and compatibility
An API contract test asserts observable behavior: method, path, status, content type, field types, required values and error shape. It should not depend on internal function names or incidental JSON key ordering. Run tests for allowed and denied behavior and compare old consumer expectations with changed responses.
package main
import ( "encoding/json" "fmt" "net/http" "net/http/httptest" "strings")
func probe(h http.Handler, method, path, body string) *httptest.ResponseRecorder { w := httptest.NewRecorder() h.ServeHTTP(w, httptest.NewRequest(method, path, strings.NewReader(body))) return w}
type Old struct { ID int `json:"id"` Name string `json:"name"`}
func oldClient(body string) bool { var b Old e := json.Unmarshal([]byte(body), &b) return e == nil && b.ID == 7 && b.Name == "Go"}func main() { m := http.NewServeMux() m.HandleFunc("GET /books/7", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") fmt.Fprint(w, `{"name":"Go","id":7,"edition":2}`) }) w := probe(m, "GET", "/books/7", "") fmt.Println(w.Code == 200 && w.Result().Header.Get("Content-Type") == "application/json" && oldClient(w.Body.String())) fmt.Println(probe(m, "POST", "/books/7", "").Code)}The old client parses JSON and checks required fields. Adding edition is tolerated by this particular decoder, not guaranteed for every consumer. A strict consumer can reject additions. Check real consumer contracts, not only your own server tests. The recorder does not exercise transport; a local httptest server adds that boundary.
Expected output:
true405Recognize breaking changes
package main
import ( "encoding/json" "fmt")
type Old struct { ID int `json:"id"` Name string `json:"name"`}
func oldClient(body string) bool { var b Old e := json.Unmarshal([]byte(body), &b) return e == nil && b.ID == 7 && b.Name == "Go"}func main() { for _, s := range []string{`{"id":7,"name":"Go","edition":2}`, `{"id":"7","name":"Go"}`, `{"id":7,"title":"Go"}`} { fmt.Println(oldClient(s)) }}Changing an integer to a string or renaming a required field breaks this consumer. Status codes, error codes, authorization rules, pagination semantics and accepted inputs can also break compatibility. Introduce a versioned contract or migration period for breaking changes; test both old and new consumers, and communicate deprecation before removing fields. A test passing does not prove all consumers are compatible.
Expected output:
truefalsefalseTry it locally
With oldClient, verify that reordered keys pass, a missing ID fails, and a null name fails. Print three booleans.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
REST API 08: Test API contracts and compatibility
Check the lesson objective before moving on.
Why parse JSON before checking fields?
Which change breaks the illustrated old consumer?