Building a REST API with GORM, Echo 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...
Combining GORM, the powerful ORM library for Go, with Echo, a fast and minimalist web framework, along with PostgreSQL, offers a robust foundation for developing efficient and scalable RESTful APIs. In this comprehensive tutorial, we'll create a practical example demonstrating the integration of GORM, Echo, and PostgreSQL to build a fully functional REST API in Go.
To follow along, ensure you have the following:
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/labstack/echo/v4
go get -u github.com/labstack/echo/v4/middleware
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 Echo server:
package main
import (
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
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.Open(dsn), &gorm.Config{})
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 echo.Context) error {
var users []User
db.Find(&users)
return c.JSON(200, users)
}
func main() {
e := echo.New()
// Middleware
e.Use(middleware.Logger())
e.Use(middleware.Recover())
// Routes
e.GET("/users", getUsers)
// Start server
e.Logger.Fatal(e.Start(":8080"))
}
The GET /users endpoint retrieves all users from the database:
func getUsers(c echo.Context) error {
var users []User
db.Find(&users)
return c.JSON(200, users)
}
The POST /users endpoint creates a new user:
func createUser(c echo.Context) error {
user := new(User)
if err := c.Bind(user); err != nil {
return err
}
db.Create(&user)
return c.JSON(201, user)
}
The GET /users/:id endpoint fetches a user by ID:
func getUserByID(c echo.Context) error {
id := c.Param("id")
var user User
db.First(&user, id)
return c.JSON(200, user)
}
The DELETE /users/:id endpoint deletes a user by ID:
func deleteUserByID(c echo.Context) error {
id := c.Param("id")
var user User
db.Delete(&user, id)
return c.NoContent(204)
}
Add the new API endpoints to the Echo server in the main function:
func main() {
e := echo.New()
// Middleware
e.Use(middleware.Logger())
e.Use(middleware.Recover())
// Routes
e.GET("/users", getUsers)
e.POST("/users", createUser)
e.GET("/users/:id", getUserByID)
e.DELETE("/users/:id", deleteUserByID)
// Start server
e.Logger.Fatal(e.Start(":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, Echo, and PostgreSQL provides a robust foundation for developing RESTful APIs in Go. This example demonstrates the integration of GORM with Echo and PostgreSQL to create a fully functional API with endpoints for user management.
Building upon this example, developers can extend functionality, and implement authentication, validation, and further endpoints, leveraging the capabilities of GORM and Echo to build scalable and efficient APIs in Go.
I hope this helps, you!!
More such articles:
https://www.youtube.com/@maheshwarligade