Stage 3 · Build
HTTP & REST APIs
JSON APIs
Decode request bodies, validate payloads, encode responses, and handle encoding/json error paths.
Decoding Requests
Use json.NewDecoder to decode request bodies. It streams from the body directly, avoiding the need to read the entire body into memory first. Always close the body after decoding.
Validation
Always validate request payloads. Check required fields, ranges, string formats, and business rules. Return specific error messages so clients know what to fix.
For applications with many endpoints, the go-playground/validator package provides struct tag validation. Add validate:"required,min=1,max=100" to struct fields and call validator.New().Struct(req).
Encoding Responses
Use json.NewEncoder to write JSON responses. It handles escaping, streaming, and error handling. Set Content-Type before writing.
Error Paths
Your API needs consistent error handling for decode failures, validation errors, not-found errors, and internal errors. Each should return the correct status code and a structured error body.
Struct Tags
Struct tags control how fields serialize to JSON. The json tag defines the field name in JSON. Use omitempty to skip zero-value fields. Use the dash to exclude fields entirely.
Streaming JSON
For large responses like paginated lists, stream JSON with json.Encoder instead of building the entire response in memory. This keeps memory usage constant regardless of list size.
Never ignore json.Decode errors. Malformed JSON is the most common API error. Return 400 with a clear message like 'invalid JSON in request body' so clients can fix their requests.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.