Building a REST API with GORM, Gin Framework, and PostgreSQL in Go.

Learner, Love to make things simple, Full Stack Developer, StackOverflower, Passionate about using machine learning, deep learning and AI
Search for a command to run...

Learner, Love to make things simple, Full Stack Developer, StackOverflower, Passionate about using machine learning, deep learning and AI
No comments yet. Be the first to comment.
Move beyond traditional RESTful thinking. Learn how to design APIs specifically for MCP (Model Context Protocol) servers. This guide covers the shift in mindset, a practical OpenAPI 3.1 example, and a Spring Boot implementation to make your services ...

Extending Kestra to Every Corner of Your Data Stack. Introduction: The Power of Plugins Imagine you're a master chef. You don't just have one knife - you have specialized tools for every task: a paring knife for delicate work, a chef's knife for chop...
Mastering Complex Orchestration Scenarios. Introduction: The Orchestrator's Toolkit Imagine you're conducting a symphony. You don't just wave your baton - you cue sections, adjust tempo, handle surprises, and ensure harmony. That's what advanced work...
From Data Extraction to Loading - A Practical Guide Introduction: Why ETL Still Matters in the Modern Data Stack Remember when data engineering was "extract, transform, load"? Some say ETL is dead, replaced by ELT, reverse ETL, and data mesh. But her...
Building Blocks of Declarative Orchestration. Introduction: The Power of Simplicity Imagine trying to build a house without understanding bricks, beams, and blueprints. That's what using an orchestration tool without understanding its core concepts f...
The combination of GORM, a powerful ORM library for Go, along with Gin, a high-performance web framework, and PostgreSQL, a robust relational database, forms a solid foundation for developing RESTful APIs in Go. In this detailed tutorial, we'll create a practical example showcasing the integration of GORM, Gin, and PostgreSQL to build a fully functional REST API in Go.
Ensure you have the following prerequisites:
Go installed on your machine
PostgreSQL installed and running
Basic knowledge of Go, SQL, and RESTful APIs
Start by initializing a new Go module:
go mod init your_project_name
Install the required dependencies:
go get -u github.com/gin-gonic/gin
go get -u github.com/jinzhu/gorm
go get -u github.com/jinzhu/gorm/dialects/postgres
Create a PostgreSQL database and define a users table with columns id, name, and email.
Create a new Go file, e.g., main.go, and set up the Gin server:
package main
import (
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
)
var (
db *gorm.DB
)
func init() {
var err error
dsn := "postgresql://user:password@localhost/database_name?sslmode=disable" // Update with your database credentials
db, err = gorm.Open("postgres", dsn)
if err != nil {
panic("failed to connect to database")
}
// Auto migrate the User model
db.AutoMigrate(&User{})
}
type User struct {
gorm.Model
Name string `json:"name"`
Email string `json:"email"`
}
func getUsers(c *gin.Context) {
var users []User
db.Find(&users)
c.JSON(200, users)
}
func main() {
r := gin.Default()
// Routes
r.GET("/users", getUsers)
// Start server
r.Run(":8080")
}
The GET /users endpoint retrieves all users from the database:
func getUsers(c *gin.Context) {
var users []User
db.Find(&users)
c.JSON(200, users)
}
The POST /users endpoint creates a new user:
func createUser(c *gin.Context) {
var user User
if err := c.BindJSON(&user); err != nil {
c.AbortWithStatus(400)
return
}
db.Create(&user)
c.JSON(201, user)
}
The GET /users/:id endpoint fetches a user by ID:
func getUserByID(c *gin.Context) {
id := c.Param("id")
var user User
db.First(&user, id)
c.JSON(200, user)
}
The DELETE /users/:id endpoint deletes a user by ID:
func deleteUserByID(c *gin.Context) {
id := c.Param("id")
var user User
db.Delete(&user, id)
c.Status(204)
}
Add the new API endpoints to the Gin server:
func main() {
r := gin.Default()
// Routes
r.GET("/users", getUsers)
r.POST("/users", createUser)
r.GET("/users/:id", getUserByID)
r.DELETE("/users/:id", deleteUserByID)
// Start server
r.Run(":8080")
}
Build and run the application:
go run main.go
To retrieve all users: GET http://localhost:8080/users
To create a user: POST http://localhost:8080/users with JSON payload
To retrieve a user by ID: GET http://localhost:8080/users/:id
To delete a user by ID: DELETE http://localhost:8080/users/:id
Combining GORM, Gin, and PostgreSQL enables the creation of efficient and scalable RESTful APIs in Go. This example demonstrates the integration of GORM with Gin and PostgreSQL to create a fully functional API with endpoints for user management.
Leveraging this example, developers can expand functionality, and implement authentication, validation, and additional endpoints, harnessing the capabilities of GORM and Gin to build robust and efficient APIs in Go.
I hope this helps, you!!
More such articles:
https://www.youtube.com/@maheshwarligade