# Building a REST API with GORM, Echo Framework, and PostgreSQL in Go

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.

## **Prerequisites**

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
    

## **Setting Up the Project**

### **Initializing the Project**

Start by initializing a new Go module:

```go
go mod init your_project_name
```

Install the required dependencies:

```go
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
```

### **Creating Database**

Create a PostgreSQL database and define a `users` table with columns `id`, `name`, and `email`.

## **Building the REST API**

### **Setting Up Echo Server**

Create a new Go file, e.g., `main.go`, and set up the Echo server:

```go
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"))
}
```

### **Implementing API Endpoints**

#### GET Users

The GET `/users` endpoint retrieves all users from the database:

```go
func getUsers(c echo.Context) error {
	var users []User
	db.Find(&users)
	return c.JSON(200, users)
}
```

#### POST User

The POST `/users` endpoint creates a new user:

```go
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)
}
```

#### GET User by ID

The GET `/users/:id` endpoint fetches a user by ID:

```go
func getUserByID(c echo.Context) error {
	id := c.Param("id")
	var user User
	db.First(&user, id)
	return c.JSON(200, user)
}
```

#### DELETE User by ID

The DELETE `/users/:id` endpoint deletes a user by ID:

```go
func deleteUserByID(c echo.Context) error {
	id := c.Param("id")
	var user User
	db.Delete(&user, id)
	return c.NoContent(204)
}
```

### **Registering API Endpoints**

Add the new API endpoints to the Echo server in the `main` function:

```go
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"))
}
```

## **Testing the API**

Build and run the application:

```go
go run main.go
```

### **Testing Endpoints**

* To retrieve all users: `GET` [`http://localhost:8080/users`](http://localhost:8080/users)
    
* To create a user: `POST` [`http://localhost:8080/users`](http://localhost:8080/users) with JSON payload
    
* To retrieve a user by ID: `GET` [`http://localhost:8080/users/:id`](http://localhost:8080/users/:id)
    
* To delete a user by ID: `DELETE` [`http://localhost:8080/users/:id`](http://localhost:8080/users/:id)
    

## **Conclusion**

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://medium.com/techwasti](Link)

[https://www.youtube.com/@maheshwarligade](https://www.youtube.com/@maheshwarligade)

[https://techwasti.com/series/spring-boot-tutorials](https://techwasti.com/series/spring-boot-tutorials)

[https://techwasti.com/series/go-language](https://techwasti.com/series/go-language)
