Model resources and method semantics
Model resources and method semantics
A resource is something the API identifies, such as a book at /books/7. Its JSON representation is not the resource itself. GET retrieves information; POST can create an item under a collection; PUT replaces the state at a known URI; DELETE removes the association with that URI. These are HTTP semantics, not automatic guarantees supplied by Go. Design the requested effect before choosing a method.
package main
import ( "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}func main() { m := http.NewServeMux() m.HandleFunc("GET /books/{id}", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, r.PathValue("id")) }) m.HandleFunc("POST /books", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Location", "/books/8") w.WriteHeader(201) }) a := probe(m, "GET", "/books/7", "") b := probe(m, "POST", "/books", "") fmt.Println(a.Code, a.Body.String()) fmt.Println(b.Code, b.Header().Get("Location"))}This routing sketch returns a fixed synthetic ID rather than persisting a book. A real creation handler must commit the new record before reporting 201. Use collection and item paths consistently. GET must not be designed to delete or purchase anything merely by visiting a link.
Expected output:
200 7201 /books/8Idempotency concerns state, not identical status codes
package main
import ( "fmt")
func main() { books := map[int]string{7: "Go"} remove := func(id int) int { if _, ok := books[id]; !ok { return 404 } delete(books, id) return 204 } fmt.Println(remove(7), remove(7), len(books))}Both deletes leave the same intended final state. A safe method is also idempotent, but PUT and DELETE are not safe: they intentionally change state. Concurrent storage requires synchronization; this isolated map is sequential.
Expected output:
204 404 0Try it locally
Create a mux that accepts GET /items/{id} and DELETE /items/{id}; return 204 for the latter (routing sketch only). Probe DELETE /items/3 and POST /items/3; print their statuses.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
REST API 01: Model resources and method semantics
Check the lesson objective before moving on.
A repeated DELETE returns 404 after 204. Is that inconsistent with idempotency?
What should a GET link do?