How to Build a RESTful API in Go with GORM and PostgreSQL
Learn how to build a RESTful API in Go (Golang) using GORM and PostgreSQL. This hands-on Go tutorial guides you through database integration and API design.
- Home
- Development Tutorial
- How to Build a RESTful API in Go with GORM and PostgreSQL
Partner With APPECODE! Let’s Work Together!
Let APPECODE implement your vision and take your project from idea to done.
How to Build a RESTful API in Go with GORM and PostgreSQL
This hands-on development tutorial teaches you how to build a robust RESTful API in Go using the GORM ORM and PostgreSQL. This tutorial guides you through model definitions, migrations, CRUD operations, and best practices for structuring scalable Go backends with real database support.
Let’s begin.
Tutorial Information
This tutorial assumes you already have an applicable development environment set up.
In this tutorial, you will learn to build a robust RESTful API in Go using the GORM ORM and PostgreSQL. This tutorial guides you through model definitions, migrations, CRUD operations, and best practices for structuring scalable Go backends with real database support.
Why Use Go, GORM, and PostgreSQL Together?
Go is known for its performance, simplicity, and excellent support for concurrency, making it ideal for scalable backend APIs. PostgreSQL is a powerful open-source relational database, perfect for real-world data management. GORM is an object-relational mapper (ORM) for Go that simplifies database operations with a high-level API. Together, they offer a clean, efficient, and scalable way to build full-featured RESTful APIs in Go.Prerequisites
- Go installed (https://golang.org/dl/)
- PostgreSQL installed and running locally
- Basic understanding of Go syntax and REST principles
- A tool like Postman or curl to test the API
Step 1: Initialize Your Go Project
In your terminal, run:mkdir go_api_gorm
cd go_api_gorm
go mod init go_api_gorm
This sets up a new Go module named go_api_gorm
.
Step 2: Add Required Packages
Run the following commands to add GORM and PostgreSQL driver:go get -u gorm.io/gorm
go get -u gorm.io/driver/postgres
go get -u github.com/gin-gonic/gin
This installs GORM, the PostgreSQL driver, and Gin — a fast web framework for Go.
Step 3: Create the Main App File
Create a new file namedmain.go
and add:
package main
import (
"gorm.io/gorm"
"gorm.io/driver/postgres"
"github.com/gin-gonic/gin"
"net/http"
"log"
)
type Task struct {
ID uint `gorm:"primaryKey"`
Title string `json:"title"`
Status string `json:"status"`
}
var db *gorm.DB
func main() {
dsn := "host=localhost user=postgres password=yourpassword dbname=taskdb port=5432 sslmode=disable"
database, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatal("Failed to connect to database")
}
db = database
db.AutoMigrate(&Task{})
r := gin.Default()
r.GET("/tasks", getTasks)
r.POST("/tasks", createTask)
r.Run()
}
func getTasks(c *gin.Context) {
var tasks []Task
db.Find(&tasks)
c.JSON(http.StatusOK, tasks)
}
func createTask(c *gin.Context) {
var task Task
if err := c.ShouldBindJSON(&task); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
db.Create(&task)
c.JSON(http.StatusOK, task)
}
This sets up basic routes to create and fetch tasks using GORM with PostgreSQL.
Step 4: Run Your API
Run your project with:go run main.go
Test the endpoints using curl or Postman:
GET /tasks
– Retrieve all tasksPOST /tasks
– Create a new task with a JSON payload
Step 5: Improve the API
- Add routes for update and delete
- Add validation and error responses
- Use environment variables for DB credentials
- Implement pagination and filtering
Conclusion
You’ve now built a foundational RESTful API in Go using GORM and PostgreSQL. You learned how to define models, perform migrations, and expose endpoints with Gin. This is a great starting point for building more advanced backend systems with authentication, advanced querying, and deployment support.Team APPECODE
This concludes this APPECODE development tutorial. Thanks for coding with us today. You now have the tools and techniques to apply the demonstrated skills in real development scenarios. Whether you’re refining a feature or launching something big, APPECODE is here to guide your technical journey every step of the way. Team APPECODE is all about helping devs like you grow with real-world, hands-on examples. Have questions or project ideas? Let’s keep the conversation going—your next big breakthrough could be one line away.