SlideShare a Scribd company logo
Structs to JSON: How Go Powers
REST APIs
A comprehensive exploration of Go's powerful struct-to-JSON
capabilities for building robust RESTful services
by Emily Achieng
DevOps & Software Engineer
Agenda
Foundations
Go structs fundamentals, JSON as API language
Implementation
Struct tags for JSON, Encoding/Decoding, Data validation
Real-world Application
Database integration, API endpoints, Service flow
Go Structs: Building Blocks of Data
Go structs are collections of fields with typed data that:
Custom types
Grouping data
Object-oriented patterns
Type safety
Think of structs as blueprints for your data.
Example: Go Struct Definition
Here’s a typical Go struct used for user data in REST APIs:
type User struct {
ID int `json:"id"`
Username string `json:"username"`
Email string `json:"email"`
Active bool `json:"active"`
CreatedAt time.Time `json:"created_at"`
}
Structs to JSON: The Transformation
JSON is the standard for data exchange in web APIs.
Go's encoding/json package makes it simple to convert between Go
structs and JSON.
The main function for this is json.Marshal, which turns a Go struct
into its JSON text representation.
Example: Struct to JSON Conversion
Here’s how you convert a Go struct to JSON using json.Marshal :
import "encoding/json"
type Product struct {
Name string
Price float64
}
p := Product{Name: "Laptop", Price: 1200.50}
jsonData, _ := json.Marshal(p)
// Output: {"Name":"Laptop","Price":1200.5}
Structs to JSON: The Transformation
1. Go Structs
Strongly typed data structures with fields and methods
2. Struct Tags
Metadata for controlling serialization behavior
3. Encoding/Decoding
json.Marshal() and json.Unmarshal() functions
4. JSON Response
Client-consumable data format
Struct Tags: The Secret Sauce
Struct tags are string literals that attach metadata to fields:
type User struct {
ID int `db:"id" json:"id"`
Username string `db:"username" json:"username"`
Email string `db:"email" json:"email"`
Active bool `db:"active" json:"active"`
CreatedAt time.Time `db:"created_at" json:"created_at"`
}
Common JSON Tag Options
1. json:"name"
Rename field (change the JSON key name for this field)
2. json:"name,omitempty"
Skip empty values (omit the field from JSON if it is empty)
These options help you control how your struct fields are
represented in JSON, making your API responses cleaner and more
flexible.
Common JSON Tag Options (cont.)
3. json:"-"
Exclude from JSON (do not include this field in the output)
4. json:",string"
Force string encoding (convert the field to a JSON string)
The json:"fieldname" tag controls how the field appears in JSON
output.
Request, Process, Decode, Encode
Request
HTTP request arrives with JSON payload
{ "username": "gopher", "email": "go@example.com", "active":
true }
Process Data
Perform operations, such as validation and database storage, using
the typed Go struct
if err := user.Validate(); err != nil { // Handle validation
error }
createdUser, err := store.CreateUser(user)
Request, Process, Decode, Encode (cont.)
Decode
Parse JSON into struct
var user model.User
json.NewDecoder(r.Body).Decode(&user)
Encode
Convert struct back to JSON
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(createdUser)
Validation: Ensuring Data Integrity
What is Validation?
Ensures user data follows business rules before processing.
Why is Validation Important?
Catches bad data early and keeps the application reliable.
How Does Validation Work?
Define rules (e.g., username length, email format)
Return clear error messages if validation fails
Database Integration: Struct to Row and
Back
1. Define Model
2. Execute Query
3. Return JSON
Database Integration: Example Code
type User struct { ID int; Name string }
user := User{}
db.QueryRow("SELECT * FROM users WHERE id = ?", id).Scan(&user.ID, &user.Name)
json, _ := json.Marshal(user)
w.Write(json)
Use struct tags to map fields to database columns.
Putting It All Together
Define Data Models
Create structs with appropriate JSON and DB tags
Implement Storage Layer
Database operations that convert between structs and DB rows
Putting It All Together (cont.)
Build HTTP Handlers
Process requests and encode/decode JSON
Register Routes
Connect HTTP endpoints to handlers
Go's struct system provides a seamless pipeline from HTTP request
to database and back, with type safety at every step.
Error Handling: Consistent API Responses
Robust APIs
Provide clear, consistent error messages to clients. Go allows
defining custom error structs that can be marshaled directly into
JSON.
Standardize Errors
Return predictable JSON formats for all error types.
type ErrorResponse struct {
Code int `json:"code"`
Message string `json:"message"`
}
Key Takeaways
Go structs are your data foundation
Model complex, reliable API data.
Struct tags give you control
Customize JSON serialization easily.
Clean architecture matters
Separate layers for maintainable, scalable APIs.
Validation & error handling ensure reliability
Catch bad data and provide clear feedback.
Thank You!
Questions?
Feel free to connect:
linkedin.com/in/emmilliarchi/
github.com/EmAchieng
Structs to JSON: How Go Powers REST APIs

More Related Content

PDF
JSON Support in DB2 for z/OS
Jane Man
 
PDF
Json at work overview and ecosystem-v2.0
Boulder Java User's Group
 
PPTX
MongoDB.local Sydney: Evolving your Data Access with MongoDB Stitch
MongoDB
 
PPT
Java Script Based Client Server Webapps 2
kriszyp
 
PDF
Going Native: Leveraging the New JSON Native Datatype in Oracle 21c
Jim Czuprynski
 
PDF
Spray Json and MongoDB Queries: Insights and Simple Tricks.
Andrii Lashchenko
 
PPTX
LU 1.3. JSON & XML.pptx about how they work and introduction
niyigenagilbert6
 
JSON Support in DB2 for z/OS
Jane Man
 
Json at work overview and ecosystem-v2.0
Boulder Java User's Group
 
MongoDB.local Sydney: Evolving your Data Access with MongoDB Stitch
MongoDB
 
Java Script Based Client Server Webapps 2
kriszyp
 
Going Native: Leveraging the New JSON Native Datatype in Oracle 21c
Jim Czuprynski
 
Spray Json and MongoDB Queries: Insights and Simple Tricks.
Andrii Lashchenko
 
LU 1.3. JSON & XML.pptx about how they work and introduction
niyigenagilbert6
 

Similar to Structs to JSON: How Go Powers REST APIs (20)

PDF
Data Types/Structures in DivConq
eTimeline, LLC
 
PDF
07 objective-c session 7
Amr Elghadban (AmrAngry)
 
PDF
Q-JSON - Reduced JSON schema with high Data Representation Efficiency
iosrjce
 
PDF
A017650104
IOSR Journals
 
PDF
OrientDB - The 2nd generation of (multi-model) NoSQL
Roberto Franchini
 
PDF
Http4s, Doobie and Circe: The Functional Web Stack
GaryCoady
 
PPTX
Working with XML and JSON Serializing
ssusere19c741
 
PPTX
MongoDB Knowledge share
Mr Kyaing
 
PPTX
Evolving your Data Access with MongoDB Stitch - Drew Di Palma
MongoDB
 
PPTX
Json
Uma mohan
 
PDF
Implementing Schema Validation in MongoDB with Pydantic
techprane
 
PPTX
Mule: JSON to Object
Sulthony Hartanto
 
PPTX
Working with JSON
Lovely Professional University
 
PPTX
Mongoose and MongoDB 101
Will Button
 
PPTX
SQL for Web APIs - Simplifying Data Access for API Consumers
Jerod Johnson
 
PDF
Scalable web application architecture
postrational
 
PDF
Superficial mongo db
DaeMyung Kang
 
PDF
JSON Processing in the Database using PostgreSQL 9.4 :: Data Wranglers DC :: ...
Ryan B Harvey, CSDP, CSM
 
PDF
JSON Application
Lin Tzu Cheng
 
PPT
MongoDB at the Silicon Valley iPhone and iPad Developers' Meetup
MongoDB
 
Data Types/Structures in DivConq
eTimeline, LLC
 
07 objective-c session 7
Amr Elghadban (AmrAngry)
 
Q-JSON - Reduced JSON schema with high Data Representation Efficiency
iosrjce
 
A017650104
IOSR Journals
 
OrientDB - The 2nd generation of (multi-model) NoSQL
Roberto Franchini
 
Http4s, Doobie and Circe: The Functional Web Stack
GaryCoady
 
Working with XML and JSON Serializing
ssusere19c741
 
MongoDB Knowledge share
Mr Kyaing
 
Evolving your Data Access with MongoDB Stitch - Drew Di Palma
MongoDB
 
Json
Uma mohan
 
Implementing Schema Validation in MongoDB with Pydantic
techprane
 
Mule: JSON to Object
Sulthony Hartanto
 
Mongoose and MongoDB 101
Will Button
 
SQL for Web APIs - Simplifying Data Access for API Consumers
Jerod Johnson
 
Scalable web application architecture
postrational
 
Superficial mongo db
DaeMyung Kang
 
JSON Processing in the Database using PostgreSQL 9.4 :: Data Wranglers DC :: ...
Ryan B Harvey, CSDP, CSM
 
JSON Application
Lin Tzu Cheng
 
MongoDB at the Silicon Valley iPhone and iPad Developers' Meetup
MongoDB
 
Ad

Recently uploaded (20)

PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PDF
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PDF
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
PDF
Software Development Methodologies in 2025
KodekX
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PDF
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
PPTX
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
PDF
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
PPT
Coupa-Kickoff-Meeting-Template presentai
annapureddyn
 
PDF
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
PDF
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
PDF
This slide provides an overview Technology
mineshkharadi333
 
PDF
Software Development Company | KodekX
KodekX
 
PDF
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
PPTX
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
 
PPTX
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
Software Development Methodologies in 2025
KodekX
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
Coupa-Kickoff-Meeting-Template presentai
annapureddyn
 
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
This slide provides an overview Technology
mineshkharadi333
 
Software Development Company | KodekX
KodekX
 
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
 
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
Ad

Structs to JSON: How Go Powers REST APIs

  • 1. Structs to JSON: How Go Powers REST APIs A comprehensive exploration of Go's powerful struct-to-JSON capabilities for building robust RESTful services by Emily Achieng DevOps & Software Engineer
  • 2. Agenda Foundations Go structs fundamentals, JSON as API language Implementation Struct tags for JSON, Encoding/Decoding, Data validation Real-world Application Database integration, API endpoints, Service flow
  • 3. Go Structs: Building Blocks of Data Go structs are collections of fields with typed data that: Custom types Grouping data Object-oriented patterns Type safety Think of structs as blueprints for your data.
  • 4. Example: Go Struct Definition Here’s a typical Go struct used for user data in REST APIs: type User struct { ID int `json:"id"` Username string `json:"username"` Email string `json:"email"` Active bool `json:"active"` CreatedAt time.Time `json:"created_at"` }
  • 5. Structs to JSON: The Transformation JSON is the standard for data exchange in web APIs. Go's encoding/json package makes it simple to convert between Go structs and JSON. The main function for this is json.Marshal, which turns a Go struct into its JSON text representation.
  • 6. Example: Struct to JSON Conversion Here’s how you convert a Go struct to JSON using json.Marshal : import "encoding/json" type Product struct { Name string Price float64 } p := Product{Name: "Laptop", Price: 1200.50} jsonData, _ := json.Marshal(p) // Output: {"Name":"Laptop","Price":1200.5}
  • 7. Structs to JSON: The Transformation 1. Go Structs Strongly typed data structures with fields and methods 2. Struct Tags Metadata for controlling serialization behavior 3. Encoding/Decoding json.Marshal() and json.Unmarshal() functions 4. JSON Response Client-consumable data format
  • 8. Struct Tags: The Secret Sauce Struct tags are string literals that attach metadata to fields: type User struct { ID int `db:"id" json:"id"` Username string `db:"username" json:"username"` Email string `db:"email" json:"email"` Active bool `db:"active" json:"active"` CreatedAt time.Time `db:"created_at" json:"created_at"` }
  • 9. Common JSON Tag Options 1. json:"name" Rename field (change the JSON key name for this field) 2. json:"name,omitempty" Skip empty values (omit the field from JSON if it is empty) These options help you control how your struct fields are represented in JSON, making your API responses cleaner and more flexible.
  • 10. Common JSON Tag Options (cont.) 3. json:"-" Exclude from JSON (do not include this field in the output) 4. json:",string" Force string encoding (convert the field to a JSON string) The json:"fieldname" tag controls how the field appears in JSON output.
  • 11. Request, Process, Decode, Encode Request HTTP request arrives with JSON payload { "username": "gopher", "email": "[email protected]", "active": true } Process Data Perform operations, such as validation and database storage, using the typed Go struct if err := user.Validate(); err != nil { // Handle validation error } createdUser, err := store.CreateUser(user)
  • 12. Request, Process, Decode, Encode (cont.) Decode Parse JSON into struct var user model.User json.NewDecoder(r.Body).Decode(&user) Encode Convert struct back to JSON w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(createdUser)
  • 13. Validation: Ensuring Data Integrity What is Validation? Ensures user data follows business rules before processing. Why is Validation Important? Catches bad data early and keeps the application reliable. How Does Validation Work? Define rules (e.g., username length, email format) Return clear error messages if validation fails
  • 14. Database Integration: Struct to Row and Back 1. Define Model 2. Execute Query 3. Return JSON
  • 15. Database Integration: Example Code type User struct { ID int; Name string } user := User{} db.QueryRow("SELECT * FROM users WHERE id = ?", id).Scan(&user.ID, &user.Name) json, _ := json.Marshal(user) w.Write(json) Use struct tags to map fields to database columns.
  • 16. Putting It All Together Define Data Models Create structs with appropriate JSON and DB tags Implement Storage Layer Database operations that convert between structs and DB rows
  • 17. Putting It All Together (cont.) Build HTTP Handlers Process requests and encode/decode JSON Register Routes Connect HTTP endpoints to handlers Go's struct system provides a seamless pipeline from HTTP request to database and back, with type safety at every step.
  • 18. Error Handling: Consistent API Responses Robust APIs Provide clear, consistent error messages to clients. Go allows defining custom error structs that can be marshaled directly into JSON. Standardize Errors Return predictable JSON formats for all error types. type ErrorResponse struct { Code int `json:"code"` Message string `json:"message"` }
  • 19. Key Takeaways Go structs are your data foundation Model complex, reliable API data. Struct tags give you control Customize JSON serialization easily. Clean architecture matters Separate layers for maintainable, scalable APIs. Validation & error handling ensure reliability Catch bad data and provide clear feedback.
  • 20. Thank You! Questions? Feel free to connect: linkedin.com/in/emmilliarchi/ github.com/EmAchieng