Tillitsdone
down Scroll to discover

Setting Up Your First API with Gin in Golang

Learn how to build your first web API using Gin framework in Go.

This guide covers project setup, basic CRUD operations, middleware implementation, and testing - perfect for Go beginners.
thumbnail

A minimalist abstract representation of interconnected geometric shapes floating in space featuring sharp lines and nodes in sunshine yellow and sapphire blue gradients ultra-realistic cinematic lighting 8K UHD high resolution sharp and detailed captured from a low angle perspective looking upward

Getting started with web development in Go can be an exciting journey, especially when you have powerful frameworks like Gin at your disposal. Today, I’ll walk you through creating your first API using Gin, one of the most popular web frameworks in the Go ecosystem. What makes Gin special? It’s lightning-fast, minimalistic, and comes with everything you need to build robust web applications.

Why Choose Gin?

Before diving into the code, let’s understand why Gin might be your best choice for building APIs in Go. In my experience, Gin strikes the perfect balance between performance and developer-friendly features. It’s significantly faster than many other Go web frameworks, thanks to its smart use of radix trees for routing and minimal memory allocations.

An abstract fluid dynamics visualization with swirling patterns in sage green and white resembling flowing data streams high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail captured from a top-down aerial view

Setting Up Your Project

Let’s roll up our sleeves and create our first API. First, you’ll need to set up a new Go project and install Gin. Here’s how I typically structure a new project:

go mod init myapi
go get -u github.com/gin-gonic/gin

Now, let’s create a simple API that handles basic CRUD operations. Here’s a straightforward example that I’ve found works well for beginners:

package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
type Book struct {
ID string `json:"id"`
Title string `json:"title"`
Author string `json:"author"`
}
func main() {
router := gin.Default()
router.GET("/books", getBooks)
router.POST("/books", createBook)
router.Run(":8080")
}
func getBooks(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "Books retrieved successfully",
})
}
func createBook(c *gin.Context) {
var newBook Book
if err := c.BindJSON(&newBook); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": "Invalid input",
})
return
}
c.JSON(http.StatusCreated, newBook)
}

A close-up macro shot of crystalline structures forming intricate patterns in fluorescent green and sapphire blue tones high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail captured from a macro close-up perspective

Adding Middleware and Error Handling

One of my favorite features in Gin is how easy it is to add middleware. Here’s a simple logging middleware I always include in my projects:

router.Use(gin.Logger())
router.Use(gin.Recovery())

The Recovery middleware is particularly helpful as it automatically recovers from any panics and sends a 500 response. Trust me, this will save you lots of debugging time in production!

Testing Your API

Before deploying, it’s crucial to test your endpoints. Gin makes this incredibly straightforward with its built-in testing utilities. Here’s a simple test example:

func TestGetBooks(t *testing.T) {
router := setupRouter()
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/books", nil)
router.ServeHTTP(w, req)
assert.Equal(t, 200, w.Code)
}

An abstract aerial view of a snowy mountain range with geometric patterns cast by shadows in white and sage green colors high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail captured from a bird's eye view angle

Remember, this is just the beginning of what you can do with Gin. As you get more comfortable with these basics, you can explore more advanced features like custom middleware, route groups, and authentication. Happy coding!

icons/logo-tid.svg Latest Blogs
Discover our top articles, selected to support the growth of your business.
https://imgproxy-landing-page.tillitsdone.com/sig/rs:fit:1200:630/plain/https%3A%2F%2Fcms-r2.tillitsdone.com%2Fwp-content-prod%2Fuploads%2F2025%2F09%2FTill-its-done_SEO_R36_Sep_1440x697.jpg@webp Material-UI (MUI) คืออะไร อยากสร้าง UI สวยงามและเป็นมืออาชีพในเวลาอันรวดเร็วใช่ไหม มาทำความรู้จักกับ Material-UI (MUI) ที่ช่วยให้คุณพัฒนาแอปพลิเคชันบน React ได้ง่ายและดูดีในทุกอุปกรณ์ https://imgproxy-landing-page.tillitsdone.com/sig/rs:fit:1200:630/plain/https%3A%2F%2Fcms-r2.tillitsdone.com%2Fwp-content-prod%2Fuploads%2F2025%2F09%2FTill-its-done_SEO_R35_Sep_1440x697.jpg@webp มือใหม่อยากเริ่มเขียนแอป ต้องใช้โปรแกรมและภาษาอะไรบ้าง? อยากเป็นนักพัฒนาแอปแต่ไม่รู้จะเริ่มยังไง พบกับแนวทางการเลือกเครื่องมือและภาษาเบื้องต้นพร้อมคำแนะ เพื่อก้าวสู่เส้นทางการเขียนแอปอย่างมั่นใจในบทความนี้ https://imgproxy-landing-page.tillitsdone.com/sig/rs:fit:1200:630/plain/https%3A%2F%2Fcms-r2.tillitsdone.com%2Fwp-content-prod%2Fuploads%2F2025%2F09%2FTill-its-done_SEO_R34_Sep_1440x697.jpg@webp Website Development Process: เว็บไซต์เปิดตัวแล้ว! แล้วต้องทำอะไรต่อ? พร้อมหรือยังที่จะก้าวสู่ความสำเร็จในโลกออนไลน์ มาเรียนรู้ขั้นตอนและเคล็ดลับดูแลเว็บไซต์หลังเปิดตัว เพื่อสร้างความมั่นคงและเติบโตอย่างยั่งยืนแก่ธุรกิจกันเถอะ พร้อมหรือยังที่จะก้าวสู่ความสำเร็จในโลกออนไลน์ มาเรียนรู้ขั้นตอนและเคล็ดลับดูแลเว็บไซต์หลังเปิดตัว เพื่อสร้างความมั่นคงและเติบโตอย่างยั่งยืนแก่ธุรกิจกันเถอะ https://imgproxy-landing-page.tillitsdone.com/sig/rs:fit:1200:630/plain/https%3A%2F%2Fcms-r2.tillitsdone.com%2Fwp-content-prod%2Fuploads%2F2025%2F09%2FTill-its-done_SEO_R27_Sep_1440x697.jpg@webp เปรียบเทียบ 3 วิธีติดตั้ง install node js บน Ubuntu: NVM vs NodeSource vs Official Repo แบบไหนดีที่สุด? เรียนรู้วิธีติดตั้ง Node.js บน Ubuntu ด้วย NVM, NodeSource หรือ Official Repo เลือกวิธีที่เหมาะกับความต้องการของคุณ พร้อมเปรียบเทียบ เพื่อการพัฒนาที่มีประสิทธิภาพ! https://imgproxy-landing-page.tillitsdone.com/sig/rs:fit:1200:630/plain/https%3A%2F%2Fcms-r2.tillitsdone.com%2Fwp-content-prod%2Fuploads%2F2025%2F09%2FTill-its-done_SEO_R26_Sep_1440x697.jpg@webp Next js image การ Optimization รูปภาพแบบ Native ที่มีประสิทธิภาพสูง เรียนรู้วิธีใช้ Next.js Image เพื่อ Optimization การแสดงภาพบนเว็บไซต์ ด้วยเทคนิคบีบอัด ปรับขนาด Lazy Load และรองรับ Responsive ช่วยให้เว็บคุณโหลดเร็วขึ้นแน่นอน! https://imgproxy-landing-page.tillitsdone.com/sig/rs:fit:1200:630/plain/https%3A%2F%2Fcms-r2.tillitsdone.com%2Fwp-content-prod%2Fuploads%2F2025%2F08%2FTill-its-done_SEO_R22_June_1440x697.jpg@webp Flutter Developer คืออะไร? สำคัญแค่ไหน Flutter Developer คือผู้เชี่ยวชาญด้านการพัฒนาแอปมือถือด้วย Flutter ที่ช่วยสนับสนุนธุรกิจให้เติบโตอย่างรวดเร็วและคุ้มค่า ด้วยเทคโนโลยีที่ยืดหยุ่นและประหยัดต้นทุน
icons/logo-tid.svg

พูดคุยกับซีอีโอ

พร้อมที่จะสร้างเว็บ/แอปของคุณให้มีชีวิตชีวาหรือเสริมทีมของคุณด้วยนักพัฒนาชาวไทยผู้เชี่ยวชาญหรือไม่?
ติดต่อเราวันนี้เพื่อหารือเกี่ยวกับความต้องการของคุณ แล้วมาสร้างโซลูชันที่ปรับแต่งเพื่อบรรลุเป้าหมายของคุณกัน เรายินดีช่วยเหลือทุกขั้นตอน!
🖐️ Contact us
down Explore our best articles, cover a wide variety of technologies
Our knowledge base
Let's keep in Touch
Thank you for your interest in Tillitsdone! Whether you have a question about our services, want to discuss a potential project, or simply want to say hello, we're here and ready to assist you.
We'll be right here with you every step of the way.
Contact Information
rick@tillitsdone.com+66824564755
Find All the Ways to Get in Touch with Tillitsdone - We're Just a Click, Call, or Message Away. We'll Be Right Here, Ready to Respond and Start a Conversation About Your Needs.
Address
9 Phahonyothin Rd, Khlong Nueng, Khlong Luang District, Pathum Thani, Bangkok Thailand
Visit Tillitsdone at Our Physical Location - We'd Love to Welcome You to Our Creative Space. We'll Be Right Here, Ready to Show You Around and Discuss Your Ideas in Person.
Social media
FacebookInstagramLinkedIn
Connect with Tillitsdone on Various Social Platforms - Stay Updated and Engage with Our Latest Projects and Insights. We'll Be Right Here, Sharing Our Journey and Ready to Interact with You.
We anticipate your communication and look forward to discussing how we can contribute to your business's success.
We'll be here, prepared to commence this promising collaboration.
Frequently Asked Questions
Explore frequently asked questions about our products and services.
Whether you're curious about features, warranties, or shopping policies, we provide comprehensive answers to assist you.