Recap - REST API Models
Part of the Object Oriented Programming section of Coddy's GO journey — lesson 78 of 107.
Challenge
EasyLet's build a REST API model system for a blog platform! You'll create well-structured types that serialize to JSON and provide readable string representations—exactly what you'd need when building real API responses.
You'll organize your code across two files:
models.go: Define your API data models with proper JSON tags and string representations.Create an
Authorstruct withID(int),Name(string), andEmail(string) fields. Map these to JSON keys"id","name", and"email". ImplementString()to return the format[Name] <[Email]>.Create a
Poststruct withID(int),Title(string),Content(string),Author(nested Author struct), andPublished(bool). Map these to"id","title","content","author", and"published". TheContentfield should useomitemptyso empty content doesn't appear in JSON. ImplementString()to return"[Title]" by [Author's String representation].Create an
APIResponsestruct withSuccess(bool),Message(string), andData(Post). Map to"success","message", and"data". TheMessagefield should useomitempty.main.go: Build API responses and demonstrate both JSON output and string representations.Read an operation type (
jsonordisplay), then read post details: post ID, title, content, author ID, author name, author email, and published status (trueorfalse).For
json: Create an APIResponse withSuccess: trueand the Post as data (leave Message empty). Convert to JSON and print it.For
display: Create the Post and print it using its String method, then print the Author separately on a new line.
The following inputs will be provided:
- Line 1: Operation type (
jsonordisplay) - Line 2: Post ID
- Line 3: Title
- Line 4: Content (may be empty)
- Line 5: Author ID
- Line 6: Author name
- Line 7: Author email
- Line 8: Published status (
trueorfalse)
For example, given:
json
1
Getting Started with Go
Learn the basics of Go programming
101
Jane Smith
jane@example.com
trueYour output should be:
{"success":true,"data":{"id":1,"title":"Getting Started with Go","content":"Learn the basics of Go programming","author":{"id":101,"name":"Jane Smith","email":"jane@example.com"},"published":true}}And given:
json
2
Draft Post
102
John Doe
john@example.com
falseYour output should be:
{"success":true,"data":{"id":2,"title":"Draft Post","author":{"id":102,"name":"John Doe","email":"john@example.com"},"published":false}}Notice how the empty content field is omitted from the JSON output.
And given:
display
3
Advanced Interfaces
Deep dive into Go interfaces
103
Alice Chen
alice@example.com
trueYour output should be:
"Advanced Interfaces" by Alice Chen <alice@example.com>
Alice Chen <alice@example.com>Try it yourself
package main
import (
"bufio"
"encoding/json"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
reader := bufio.NewReader(os.Stdin)
// Read operation type
operation, _ := reader.ReadString('\n')
operation = strings.TrimSpace(operation)
// Read post ID
postIDStr, _ := reader.ReadString('\n')
postID, _ := strconv.Atoi(strings.TrimSpace(postIDStr))
// Read title
title, _ := reader.ReadString('\n')
title = strings.TrimSpace(title)
// Read content
content, _ := reader.ReadString('\n')
content = strings.TrimSpace(content)
// Read author ID
authorIDStr, _ := reader.ReadString('\n')
authorID, _ := strconv.Atoi(strings.TrimSpace(authorIDStr))
// Read author name
authorName, _ := reader.ReadString('\n')
authorName = strings.TrimSpace(authorName)
// Read author email
authorEmail, _ := reader.ReadString('\n')
authorEmail = strings.TrimSpace(authorEmail)
// Read published status
publishedStr, _ := reader.ReadString('\n')
published := strings.TrimSpace(publishedStr) == "true"
// TODO: Create an Author struct with the read values
// TODO: Create a Post struct with the read values and the Author
// TODO: Handle the operation type
// If operation is "json":
// - Create an APIResponse with Success: true and the Post as Data
// - Convert to JSON using json.Marshal
// - Print the JSON string
// If operation is "display":
// - Print the Post using its String method
// - Print the Author on a new line
// Placeholder to use variables (remove when implementing)
_ = postID
_ = title
_ = content
_ = authorID
_ = authorName
_ = authorEmail
_ = published
_ = operation
_ = json.Marshal
fmt.Println("TODO: Implement the solution")
}
All lessons in Object Oriented Programming
1Fundamentals of Go OOP
External FilesGo Workspace & ModulesPackages & ImportsExported vs Unexported NamesIntroduction to OOP in GoStructs as ClassesDefining Methods on StructsPointer vs Value ReceiversStruct InitializationConstructor FunctionsRecap - Simple Calculator4Interfaces
Introduction to InterfacesImplicit ImplementationInterface as ContractEmpty Interface (any)Type AssertionType SwitchInterface CompositionStringer & Error InterfacesRecap - Shape Calculator7Encapsulation
Exported vs Unexported FieldsPackage-Level EncapsulationGetter & Setter MethodsInformation Hiding in GoRecap - Student Records10Generics (Go 1.18+)
Introduction to GenericsType ParametersType ConstraintsGeneric StructsGeneric Methods WorkaroundRecap - Generic Collection2Types & Structs Deep Dive
Basic & Composite TypesCustom Type DefinitionsStruct TagsAnonymous StructsNested StructsZero Values & DefaultsRecap - Contact Book5Composition Over Inheritance
Why Go Has No InheritanceStruct Embedding BasicsMethod PromotionEmbedding Multiple StructsEmbedding vs AggregationShadowing Embedded MethodsRecap - Employee Hierarchy8Error Handling & OOP
The error InterfaceCustom Error TypesError Wrapping (fmt.Errorf)Sentinel Errorserrors.Is() and errors.As()Panic, Defer, and RecoverRecap - File Parser11Standard Library & OOP
io.Reader & io.Writersort.Interfacefmt.Stringer Interfaceencoding/json with Structshttp.Handler InterfaceRecap - REST API Models3Pointers & Memory
Pointer Basics in GoPointers to StructsPass by Value vs ReferenceThe new() FunctionGarbage Collection in GoRecap - Linked List Builder6Polymorphism in Go
Polymorphism via InterfacesDuck Typing in GoInterface Satisfaction RulesPolymorphic CollectionsDependency InjectionRecap - Payment Processor9Concurrency & OOP
Goroutines BasicsChannels & CommunicationBuffered vs Unbuffered ChanSelect Statementsync.Mutex & sync.RWMutexsync.WaitGroupThread-Safe Struct DesignRecap - Worker Pool