DEV Community

Steve Omollo
Steve Omollo

Posted on AI-assisted

Adding PostgreSQL to our Go API

Introduction

In the previous article, Structuring Go Projects for Growth with Packages, we organized our Task API by separating our models and handlers into different packages.

Our API can now handle basic CRUD operations; creating, reading, updating and deleting tasks. However, there's still one limitation we haven't addressed: where are we storing our tasks?

If you look at our handler, you'll find that we are currently using an in-memory slice:

var tasks []models.Task
Enter fullscreen mode Exit fullscreen mode

This works for learning and testing, but it comes with a problem. Every time we stop and restart our application, all the tasks we've created disappear.

That's because the data only exists in the application's memory. We need a way to store it permanently, even when our application stops running.

This is where databases come in.

In this article, we'll introduce PostgreSQL and connect it to our existing Go API. We'll gradually replace our in-memory storage with a database while keeping the CRUD functionality we've already built.

By the end, our tasks will persist between application restarts.

What We'll Build

We'll continue working with the Task API from our previous articles rather than creating a new project.

Our goal is to replace the in-memory slice with PostgreSQL while keeping the existing CRUD functionality.

We'll use the following tools:

  • Go: Our backend programming language.
  • PostgreSQL: The relational database where we'll store our tasks.
  • Docker: To run PostgreSQL in a container without having to install it directly on our machine.
  • database/sql: Go's standard library package for working with SQL databases.
  • pgx: The PostgreSQL driver that will allow database/sql to communicate with PostgreSQL.

We'll also use SQL queries to create, retrieve, update, and delete records in our database.

Our project structure

We'll start with the structure we created in the previous article:

go-crud-api/
├─ go.mod
├─ main.go
├─ handlers/
│ └─ tasks.go
└─ models/
  └─ task.go
Enter fullscreen mode Exit fullscreen mode

As we introduce database connectivity, we'll make a few additions to this structure. We'll explain each one as it becomes necessary.

By the end, our application will still expose the same task endpoints, but instead of keeping tasks in memory, it will retrieve and store them in PostgreSQL.

Let's get started!

Setting Up PostgreSQL with Docker

Before connecting our Go application to PostgreSQL, we need to have a running database.

One way to do this is to install PostgreSQL directly on our machine. However, we'll use Docker instead.

Docker allows us to run applications in isolated environments called containers. This means we can run PostgreSQL without having to install and configure it directly on our operating system.

If you already have Docker installed, you're ready to proceed.

1. Create a Docker Compose file

Navigate to the root directory of our go-crud-api project and create a file named docker-compose.yml.

services:
    db:
        image: postgres:17
        container_name: go-crud-db
        restart: always
        environment:
            POSTGRES_USER: postgres
            POSTGRES_PASSWORD: postgres
            POSTGRES_DB: tasks_db
        ports:
            - "5432:5432"
        volumes:
            - postgres_data:/var/lib/postgresql/data
volumes:
    postgres_data:
Enter fullscreen mode Exit fullscreen mode

Let's understand what we are configuring:

  • image: Specifies the PostgreSQL version Docker should download and run.
  • container_name: Gives our container a recognized name.
  • restart: Tells Docker to restart the container automatically if it stops.
  • environment: Defines the initial database credentials and database name.
  • ports: Maps PostgreSQL's default port, 5432, inside the container to port 5432 of our machine.
  • volumes: Provides persistent storage for our database files.

Notice we've configured three environment variables:

  • POSTGRES_USER: The database user.
  • POSTGRES_PASSWORD: The user's password.
  • POSTGRES_DB: The database Docker will create when initializing the container.

For this tutorial, we'll use tasks_db as our database name.

The credentials are kept simple for learning purposes. In a real application, you should use stronger credentials and avoid committing passwords to version control.

2. Start the PostgreSQL container

With our configuration in place, run:

docker compose up -d
Enter fullscreen mode Exit fullscreen mode

Docker Compose reads our configuration, downloads the PostgreSQL image if necessary, and starts the container.

The -d flag means detached mode, allowing the container to run in the background while we continue working in our terminal.

3. Verify that PostgreSQL is running

To check the container's status, run:

docker compose ps
Enter fullscreen mode Exit fullscreen mode

You should see go-crud-db listed as a running container.

We can also inspect its logs:

docker compose logs db
Enter fullscreen mode Exit fullscreen mode

Look for a message similar to :

database system is ready to accept connections
Enter fullscreen mode Exit fullscreen mode

This indicates that PostgreSQL database is running in Docker, with a database named tasks_db waiting for our application.

Creating the Tasks Table

Now that our PostgreSQL database is running, we need to create a table to store our tasks.

Remember the Task struct we created earlier in models/task.go?

package models

type Task struct {
    ID    int    `json:"id"`
    Title string `json:"title"`
}
Enter fullscreen mode Exit fullscreen mode

This struct defines the structure of a task in our Go application. We need a corresponding structure in our database.

In PostgreSQL, we'll create a table called tasks with two columns: id and title.

1. Access the PostgreSQL container

We can interact with PostgreSQL using a command-line tool called psql.

Since PostgreSQL is running inside Docker, execute:

docker exec -it go-crud-db psql -U postgres -d tasks_db
Enter fullscreen mode Exit fullscreen mode

Here's what the command does:

  • docker exec: Executes a command inside a running container.
  • -it: Allows us to interact with the container through our terminal.
  • go-crud-db: The name of our PostgreSQL container.
  • psql: Opens the PostgreSQL command-line interface.
  • -U postgres: Connects using the postgres user.
  • -d tasks_db: Specifies the database we want to access.

If successful, you'll enter the PostgreSQL interactive terminal, where you can execute SQL commands.

2. Create the tasks table

Inside the PostgreSQL terminal, execute:

CREATE TABLE tasks(
    id SERIAL PRIMARY KEY,
    title TEXT NOT NULL
);
Enter fullscreen mode Exit fullscreen mode

Let's understand the columns:

  • id: Identifies each task.
  • SERIAL: Automatically generates an incrementing integer whenever a new task is inserted.
  • PRIMARY KEY: Ensures each task has a unique identifier.
  • title: Stores the task's title.
  • TEXT: Allows us to store text of varying lengths.
  • NOT NULL: Prevents a task from being created without a title

We've now created a table that can store our tasks.

3. Verify the table

To confirm that our table was created successfully, run:

\dt
Enter fullscreen mode Exit fullscreen mode

This displays the tables in the current database. You should see tasks listed.

To inspect its structure, run:

\d tasks
Enter fullscreen mode Exit fullscreen mode

This displays the columns, data types, and constraints defined for the table.

To leave the PostgreSQL terminal, execute:

\q
Enter fullscreen mode Exit fullscreen mode

We can now have a tasks table ready to store data.

Notice how our database table corresponds to the Task struct in Go. Both define an ID and a title, but they serve different purposes: the struct represents a task in our application, while the table stores the task records in the database.

Connecting Go to PostgreSQL

We have our database and tasks table ready. The next step is to establish a connection between our Go application and PostgreSQL.

Go provides a standard library package called database/sql for working with SQL databases. It provides a common interface for executing queries, inserting records, and managing database connections.

However, database/sql doesn't communicate with PostgreSQL on its own. It needs a database driver to handle the communication with the specific database we're using.

We'll use pgx, a PostgreSQL driver and toolkit for Go.

1. Install the PostgreSQL driver

From the root directory of our project, run:

go get github.com/jackc/pgx/v5/stdlib
Enter fullscreen mode Exit fullscreen mode

This downloads the pgx package and adds it to our project's dependencies.

The /stdlib part is important because it provides the adapter that allows pgx to work with Go's standard database/sql package.

2. Create a database connection

We'll create a new directory called database and add a file named database.go.

Our project structure now looks like this:

go-crud-api/
├─ go.mod
├─ go.sum
├─ main.go
├─ database/
│ └─ database.go
├─ handlers/
│ └─ tasks.go
└─ models/
  └─ task.go
Enter fullscreen mode Exit fullscreen mode

Inside database/database.go, add:

package database

import (
    "database/sql"
    "log"

    _ "github.com/jackc/pgx/v5/stdlib"
)

func Connect() *sql.DB {
    connStr := "postgres://postgres:postgres@localhost:5432/tasks_db"

    db, err := sql.Open("pgx", connStr)
    if err != nil {
        log.Fatal(err)
    }

    err = db.Ping()
    if err != nil {
        log.Fatal(err)
    }

    log.Println("Connected to PostgreSQL")

    return db
}
Enter fullscreen mode Exit fullscreen mode

Let's break down what's happening.

  • database/sql - Provides Go's standard interface for interacting with SQL databases.
  • log - Allows us to log messages and errors.
  • _ "github.com/jackc/pgx/v5/stdlib" - Registers the pgx driver with database/sql. The underscore means we're importing the package for its initialization side effect rather than using its exported names directly.
  • sql.Open("pgx", connStr) - Creates a database handle using the registered pgx driver.
  • db.Ping() - Checks whether the database is reachable.
  • sql.DB - A database handle that manages connections to the database. It isn't just one physical connection.

Notice the connection string:

postgres://postgres:postgres@localhost:5432/tasks_db
Enter fullscreen mode Exit fullscreen mode

It follows this general format:

postgres://username:password@host:port/database_name
Enter fullscreen mode Exit fullscreen mode

In our case:

  • postgres is our database username.
  • postgres is our password.
  • localhost is where PostgreSQL is running.
  • 5432 is PostgreSQL's default port.
  • tasks_db is the database we created earlier.

For this tutorial, we're keeping credentials simple. In a real application, connection details should be stored in environment variables rather than hardcoded in source files.

3. Initialize the connection in main.go

Now that we've created our connection function, we need to call it when our application starts.

Open main.go and update it:

package main

import (
    "net/http"

    "go-crud-api/database"
    "go-crud-api/handlers"
)

func main() {
    db := database.Connect()
    defer db.Close()

    http.HandleFunc("/tasks", handlers.TaskHandler(db))
}
Enter fullscreen mode Exit fullscreen mode

We've introduced two important things:

  • database.Connect() - Establishes our database connection when the application starts.
  • defer db.Close() - Schedules the database handle to be closed when main exits.

At this point, our application can connect to PostgreSQL, but our handlers are not using the database yet. They're still working with the in-memory slice.

We'll change that next.

Reading Tasks from PostgreSQL

Previously, our GET handler returned the contents of our in-memory slice:

json.NewEncoder(w).Encode(tasks)
Enter fullscreen mode Exit fullscreen mode

Now that we've established a database connection, we can retrieve the tasks directly from PostgreSQL

1. Update the task handler

First, we need to make our database connection available to the handler.

Open handlers/tasks.go and update the handler to accept a database connection:

func TaskHandler(db *sql.DB) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        // handler logic goes here
    }
}
Enter fullscreen mode Exit fullscreen mode

We're changing the TaskHandler from a regular function into one that accepts a database handle and returns an HTTP handler.

This allows our handler to use the database when processing requests.

We'll also need to import database/sql.

2. Retrieve tasks using a SELECT query

Inside the handler's GET case, replace the previous slice-based implementation with:

case http.MethodGet:
    rows, err := db.Query("SELECT id, title FROM tasks")
    if err != nil {
        http.Error(w, "Failed to retrieve tasks", http.StatusInternalServerError)
        return
    }
    defer rows.Close()

    tasks := make([]models.Task, 0)

    for rows.Next() {
        var task models.Task

        err := rows.Scan(&task.ID, &task.Title)
        if err != nil {
            http.Error(w, "Failed to read task", http.StatusInternalServerError)
            return
        }

        tasks = append(tasks, task)
    }

    if err := rows.Err(); err != nil {
            http.Error(w, "Failed to retrieve tasks", http.StatusInternalServerError)
            return
    }

    json.NewEncoder(w).Encode(tasks)
Enter fullscreen mode Exit fullscreen mode

Let's understand the important parts.

  • db.Query() executes our SQL query and returns the resulting rows.
  • defer rows.Close() ensures that the result set is closed when we're done processing it.
  • rows.Next() moves through the returned rows one at a time.
  • rows.Scan() copies the column values into our Go variables.
  • tasks = append(tasks, task) adds each retrieved task to our slice.
  • json.NewEncoder(w).Encode(tasks) converts the resulting slice into a JSON response.

Notice that we're still using a Go slice, but there's an important difference: we're no longer using it as permanent storage. We're using it temporarily to collect the records retrieved from PostgreSQL before returning them to the client.

3. Register the updated handler

Since TaskHandler now requires a database connection, we need to pass it when registering the route.

Update main.go:

func main() {
    db := database.Connect()
    defer db.Close()

    http.HandleFunc("/tasks", handlers.TaskHandler(db))

    http.ListenAndServe(":8080", nil)
}
Enter fullscreen mode Exit fullscreen mode

We now pass our database handle to TaskHandler(db).

This makes the same database connection available whenever the /tasks endpoint receives a request.

4. Test the GET endpoint

Start your application:

go run .
Enter fullscreen mode Exit fullscreen mode

Then retrieve the tasks:

curl http://localhost:8080/tasks
Enter fullscreen mode Exit fullscreen mode

If your database doesn't contain any tasks yet, you should get:

[]
Enter fullscreen mode Exit fullscreen mode

That's expected. We haven't inserted any records.

If you want to verify the endpoints with existing data, you can temporarily insert a record directly into PostgreSQL:

INSERT INTO tasks (title) VALUES ('Learn PostgreSQL');
Enter fullscreen mode Exit fullscreen mode

Run the GET request again. You should now receive:

[
    {
        "id": 1,
        "title": "Learn PostgreSQL"
    }
]
Enter fullscreen mode Exit fullscreen mode

Our GET endpoint now retrieves tasks from PostgreSQL instead of the in-memory slice.

Take not of the ID returned when you create your task. We'll use that ID when updating and deleting it. In the examples below we'll assume the generated ID is 1. Your ID may be different depending on the records in your database.

Creating Tasks in PostgreSQL

Previously, our POST handler added new tasks to the in-memory slice using:

tasks = append(tasks, task)
Enter fullscreen mode Exit fullscreen mode

We'll replace this with an SQL INSERT statement.

1. Update the POST handler

Inside the switch statement in handlers/tasks.go, replace the existing POST case with:

case http.MethodPost:
    var task models.Task

    err := json.NewDecoder(r.Body).Decode(&task)
    if err != nil {
        http.Error(w, "Invalid JSON", http.StatusBadRequest)
        return
    }

    err = db.QueryRow(
        "INSERT INTO tasks (title) VALUES ($1) RETURNING id", task.Title,
    ).Scan(&task.ID)

    if err != nil {
        http.Error(w, "Failed to create task", http.StatusInternalServerError)
        return
    }

    w.WriteHeader(http.StatusCreated)    
    json.NewEncoder(w).Encode(task)
Enter fullscreen mode Exit fullscreen mode

Let's break down what's happening.

  • json.NewDecoder(r.Body).Decode(&task) reads the incoming JSON request and converts it into a Go Task struct.
  • INSERT INTO tasks tells PostgreSQL to create a new record in the tasks table.
  • $1 is a placeholder for a value that will be supplied separately.
  • task.Title supplies the title we want to insert.
  • RETURNING id tells PostgreSQL to return the ID generated for the newly created task.
  • db.QueryRow() executes the query and returns a single row. We then use Scan() to retrieve the generated ID.
  • Scan(&task.ID) stores the returned ID into our Go struct.

You might be wondering why we're using $1 instead of inserting the task directly into the SQL statement.

These are called parameterized queries. They allow us to pass values separately from SQL statement, helping prevent SQL injection and ensuring that supplied values are handled safely.

Also, notice that we've added:

w.WriteHeader(http.StatusCreated)
Enter fullscreen mode Exit fullscreen mode

This sends HTTP status code 201 Created, indicating that a new resource has been successfully created.

2. Test the POST endpoint

Start your application:

go run .
Enter fullscreen mode Exit fullscreen mode

Now submit a new task:

curl -X POST http://localhost:8080/tasks \
-H "Content-Type: application/json" \
-d '{"title":"Learn PostgreSQL"}'
Enter fullscreen mode Exit fullscreen mode

You should receive a response similar to:

{
    "id": 1,
    "title": "Learn PostgreSQL"
}
Enter fullscreen mode Exit fullscreen mode

The ID is generated automatically by PostgreSQL and returned to our application.

To confirm that the record was actually stored, make another GET request:

curl http://localhost:8080/tasks
Enter fullscreen mode Exit fullscreen mode

You should now see the newly created task in the response.

Unlike our previous implementation, this record will remain in the database even after we stop and restart our Go application.

We've successfully implemented the Create operation using PostgreSQL!

Updating Tasks in PostgreSQL

Previously, our PUT handler searched through the in-memory slice, found the task with matching ID, and changed its title.

Now we'll use an SQL UPDATE statement to modify the record stored in PostgreSQL.

1. Update the PUT handler

Inside the switch statement in handlers/tasks.go, replace the existing PUT case with:

case http.MethodPut:
    var updatedTask models.Task

    err := json.NewDecoder(r.Body).Decode(&updatedTask)
    if err != nil {
        http.Error(w, "Invalid JSON", http.StatusBadRequest)
        return
    }

    result, err := db.Exec(
        "UPDATE tasks SET title = $1 WHERE id = $2",
        updatedTask.Title,
        updatedTask.ID,
    )

    if err != nil {
        http.Error(w, "Failed to update task", http.StatusInternalServerError)
        return
    }

    rowsAffected, err := result.RowsAffected()
    if err != nil {
        http.Error(w, "Failed to check updated task", http.StatusInternalServerError)
        return
    }

    if rowsAffected == 0 {
        http.Error(w, "Task not found", http.StatusNotFound)
        return
    }

    json.NewEncoder(w).Encode(updatedTask)
Enter fullscreen mode Exit fullscreen mode

Let's understand the important parts:

  • db.Exec() executes an SQL statement that doesn't need to return rows, such as an UPDATE or DELETE.
  • UPDATE tasks SET title = $1 tells PostgreSQL to change the title of a task.
  • WHERE id = $2 specifies which task should be updated.
  • result.RowsAffected() tells us how many database rows were affected by the operation.
  • rowsAffected == 0 means no matching task was found, so we return a 404 Not Found response.

2. Test the PUT endpoint

Let's assume we already have a task with ID 1.

We can update it using:

curl -X PUT http://localhost:8080/tasks \
-H "Content-Type: application/json" \
-d '{"id":1,"title":"Learn Go and PostgreSQL"}'
Enter fullscreen mode Exit fullscreen mode

The response should look like:

{
    "id": 1,
    "title": "Learn Go and PostgreSQL"
}
Enter fullscreen mode Exit fullscreen mode

To verify the change, send another GET request:

curl http://localhost:8080/tasks
Enter fullscreen mode Exit fullscreen mode

You should see the updated title.

What if we try to update a task that doesn't exist?

For example:

curl -X PUT http://localhost:8080/tasks \
-H "Content-Type: application/json" \
-d '{"id":99,"title":"Nonexistent task"}'
Enter fullscreen mode Exit fullscreen mode

Our API should respond with:

Task not found
Enter fullscreen mode Exit fullscreen mode

Along with an HTTP 404 Not Found status code.

We've now successfully moved the Update operation from in-memory storage to PostgreSQL.

Deleting Tasks in PostgreSQL

Our final operation is Delete. Previously, we removed tasks from our in-memory slice using Go's append() function.

Now we'll use an SQL DELETE statement to remove records directly from PostgreSQL.

1. Update the DELETE handler

Inside the switch statement in handlers/tasks.go, replace the existing DELETE case with:

case http.MethodDelete:
    var taskToDelete models.Task

    err := json.NewDecoder(r.Body).Decode(&taskToDelete)
    if err != nil {
        http.Error(w, "Invalid JSON", http.StatusBadRequest)
        return
    }

    result, err := db.Exec(
        "DELETE FROM tasks WHERE id = $1",
        taskToDelete.ID,
    )

    if err != nil {
        http.Error(w, "Failed to delete task", http.StatusInternalServerError)
        return
    }

    rowsAffected, err := result.RowsAffected()
    if err != nil {
        http.Error(w, "Failed to check deleted task", http.StatusInternalServerError)
        return
    }

    if rowsAffected == 0 {
        http.Error(w, "Task not found", http.StatusNotFound)
        return
    }

    w.Write([]byte("Task deleted"))
Enter fullscreen mode Exit fullscreen mode

Let's look at the important parts:

  • db.Exec() executes our SQL DELETE statement.
  • DELETE FROM tasks tells PostgreSQL which table we want to delete from.
  • WHERE id = $1 identifies the specific task we want to remove.
  • result.RowsAffected() tells us how many records were deleted.
  • rowsAffected == 0 means no task matched the supplied ID, so we return a 404 Not Found response.

The WHERE clause is particularly important here. Without it, the DELETE statement would remove every record in the tasks table.

2. Test the DELETE endpoint

Let's assume we have a task with ID 1.

We can delete it by sending:

curl -X DELETE http://localhost:8080/tasks \
-H "Content-Type: application/json" \
-d '{"id":1}'
Enter fullscreen mode Exit fullscreen mode

If successful, our API responds:

Task deleted
Enter fullscreen mode Exit fullscreen mode

To confirm that the task has been removed, send another GET request:

curl http://localhost:8080/tasks
Enter fullscreen mode Exit fullscreen mode

The deleted task should no longer appear in the response.

We can also try deleting a task that doesn't exist:

curl -X DELETE http://localhost:8080/tasks \
-H "Content-Type: application/json" \
-d '{"id":99}'
Enter fullscreen mode Exit fullscreen mode

Our API should respond with Task not found and an HTTP 404 Not Found status.

Where we are now

Operation SQL statement
Create INSERT
Read SELECT
Update UPDATE
Delete DELETE

Bringing the Handler Together

We've now replaced our in-memory CRUD operation with SQL queries. Let's look at the complete handlers/tasks.go file to see how everything fits together.

Your file should now look like this:

package handlers

import (
    "database/sql"
    "encoding/json"
    "net/http"

    "go-crud-api/models"
)

func TaskHandler(db *sql.DB) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "application/json")

        switch r.Method {

        case http.MethodGet:
            rows, err := db.Query("SELECT id, title FROM tasks")
            if err != nil {
                http.Error(w, "Failed to retrieve tasks", http.StatusInternalServerError)
                return
            }
            defer rows.Close()

            tasks := make([]models.Task, 0)

            for rows.Next() {
                var task models.Task

                err := rows.Scan(&task.ID, &task.Title)
                if err != nil {
                    http.Error(w, "Failed to read task", http.StatusInternalServerError)
                    return
                }

                tasks = append(tasks, task)
            }

            if err := rows.Err(); err != nil {
                http.Error(w, "Failed to retrieve tasks", http.StatusInternalServerError)
                return
            }

            json.NewEncoder(w).Encode(tasks)

        case http.MethodPost:
            var task models.Task

            err := json.NewDecoder(r.Body).Decode(&task)
            if err != nil {
                http.Error(w, "Invalid JSON", http.StatusBadRequest)
                return
            }

            err = db.QueryRow(
                "INSERT INTO tasks (title) VALUES ($1) RETURNING id",
                task.Title,
            ).Scan(&task.ID)

            if err != nil {
                http.Error(w, "Failed to create task", http.StatusInternalServerError)
                return
            }

            w.WriteHeader(http.StatusCreated)
            json.NewEncoder(w).Encode(task)

        case http.MethodPut:
            var updatedTask models.Task

            err := json.NewDecoder(r.Body).Decode(&updatedTask)
            if err != nil {
                http.Error(w, "Invalid JSON", http.StatusBadRequest)
                return
            }

            result, err := db.Exec(
                "UPDATE tasks SET title = $1 WHERE id = $2",
                updatedTask.Title,
                updatedTask.ID,
            )

            if err != nil {
                http.Error(w, "Failed to update task", http.StatusInternalServerError)
                return
            }

            rowsAffected, err := result.RowsAffected()
            if err != nil {
                http.Error(w, "Failed to check updated task", http.StatusInternalServerError)
                return
            }

            if rowsAffected == 0 {
                http.Error(w, "Task not found", http.StatusNotFound)
                return
            }

            json.NewEncoder(w).Encode(updatedTask)

        case http.MethodDelete:
            var taskToDelete models.Task

            err := json.NewDecoder(r.Body).Decode(&taskToDelete)
            if err != nil {
                http.Error(w, "Invalid JSON", http.StatusBadRequest)
                return
            }

            result, err := db.Exec(
                "DELETE FROM tasks WHERE id = $1",
                taskToDelete.ID,
            )

            if err != nil {
                http.Error(w, "Failed to delete task", http.StatusInternalServerError)
                return
            }

            rowsAffected, err := result.RowsAffected()
            if err != nil {
                http.Error(w, "Failed to check deleted task", http.StatusInternalServerError)
                return
            }

            if rowsAffected == 0 {
                http.Error(w, "Task not found", http.StatusNotFound)
                return
            }

            w.Write([]byte("Task deleted"))

        default:
            http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Notice a few things in this implementation:

  • We no longer have a global tasks slice. PostgreSQL is now responsible for storing our task records.
  • Our handler receives a database connection through TaskHandler(db).
  • Each CRUD operation executes an SQL statement against the tasks table.
  • We still use our existing models.Task struct to represent tasks in Go.

One additional detail in our GET implementation is rows.Err(). This checks whether an error occurred while iterating through the database results.

We also initialize the slice using make([]models.Task, 0). This ensures that when there are no records, our API returns an empty JSON array instead of null.

Our handler is now using PostgreSQL for all four CRUD operations.

Testing the Complete API

We've connected our Go application to PostgreSQL and replaced our in-memory storage with database queries.

Now let's test everything to make sure our API works as expected.

1. Start the application

From the root directory of the project, run:

go run .
Enter fullscreen mode Exit fullscreen mode

If everything is configured correctly, you should see:

Connected to PostgreSQL
Enter fullscreen mode Exit fullscreen mode

Our API should now be listening on port 8080.

2. Create a task

Let's start by creating a new task:

curl -X POST http://localhost:8080/tasks \
-H "Content-Type: application/json" \
-d '{"title":"Learn PostgreSQL"}'
Enter fullscreen mode Exit fullscreen mode

Expected response:

{
    "id": 1,
    "title": "Learn PostgreSQL"
}
Enter fullscreen mode Exit fullscreen mode

The database automatically generates the task ID and returns it to our application.

3. Retrieve tasks

Next, let's retrieve all our tasks:

curl http://localhost:8080/tasks
Enter fullscreen mode Exit fullscreen mode

Expected response:

[
    {
        "id": 1,
        "title": "Learn PostgreSQL"
    }
]
Enter fullscreen mode Exit fullscreen mode

4. Update a task

Let's update the task we just created:

curl -X PUT http://localhost:8080/tasks \
-H "Content-Type: application/json" \
-d '{"id":1,"title":"Build a Go API with PostgreSQL"}'
Enter fullscreen mode Exit fullscreen mode

Expected response:

{
    "id": 1,
    "title": "Build a Go API with PostgreSQL"
}
Enter fullscreen mode Exit fullscreen mode

5. Delete a task

Finally, let's delete the task:

curl -X DELETE http://localhost:8080/tasks \
-H "Content-Type: application/json" \
-d '{"id":1}'
Enter fullscreen mode Exit fullscreen mode

Expected response:

Task deleted
Enter fullscreen mode Exit fullscreen mode

We can verify that the task is gone by retrieving all tasks again:

curl http://localhost:8080/tasks
Enter fullscreen mode Exit fullscreen mode

Expected response:

[]
Enter fullscreen mode Exit fullscreen mode

6. Verify data persistence

Now let's test something that wasn't possible with our previous in-memory implementation.

Create another task:

curl -X POST http://localhost:8080/tasks \
-H "Content-Type: application/json" \
-d '{"title":"Test data persistence"}'
Enter fullscreen mode Exit fullscreen mode

Stop the Go application using Ctrl + C, then start it again:

go run .
Enter fullscreen mode Exit fullscreen mode

Retrieve the tasks:

curl http://localhost:8080/tasks
Enter fullscreen mode Exit fullscreen mode

You should still see the task we created:

[
    {
        "id": 2,
        "title": "Test data persistence"
    }
]
Enter fullscreen mode Exit fullscreen mode

The ID may differ depending on how many records you've previously inserted. PostgreSQL's SERIAL sequence continues generating IDs even when records are deleted.

This confirms that our data is stored in PostgreSQL rather than the application's memory. Restarting the Go application does not erase our records.

We've successfully built a database-backed CRUD API!

Updated Project Structure

Our project has now grown from a simple Go application into an API connected to a PostgreSQL database.

The updated structure looks like this:

go-crud-api/
├── go.mod
├── go.sum
├── docker-compose.yml
├── main.go
├── database/
│   └── database.go
├── handlers/
│   └── tasks.go
└── models/
    └── task.go
Enter fullscreen mode Exit fullscreen mode

Each part now has a specific responsibility:

  • main.go starts the application, establishes the database connection, and registers the API route.
  • database/ contains the code responsible for connecting to PostgreSQL.
  • handlers/ contains the HTTP handlers that process API requests and execute database operations.
  • models/ defines the data structures used by the application.
  • docker-compose.yml defines the PostgreSQL container and its configuration.
  • go.mod and go.sum manage the Go module and its dependencies.

Notice that we have kept the separation introduced in the previous article. Instead of putting everything into main.go, each package handles a particular responsibility.

What We've Learned

In this article, we took our existing CRUD API and replaced its in-memory storage with PostgreSQL.

Along the way, we learned how to:

  • Run PostgreSQL using Docker Compose.
  • Create a database and a table.
  • Connect a Go application to PostgreSQL using database/sql.
  • Use the pgx driver to communicate with PostgreSQL.
  • Retrieve records using SELECT.
  • Insert records using INSERT.
  • Update records using UPDATE.
  • Delete records using DELETE.
  • Use parameterized queries to pass values safely into SQL statements.

Most importantly, our API can now retain data even after the Go application is stopped and restarted.

This is a significant step forward. We are no longer working with an API that only remembers data while it is running. We now have an application backed by persistent storage.

What's Next?

We have a working Go API connected to PostgreSQL, but there is still room to improve how we manage and organize our application.

In the next article, we'll explore database migrations and why they matter as applications grow.

Rather than manually creating database tables, we'll learn how to manage changes to our database structure in a controlled and repeatable way.

Thanks for reading!

Happy coding!

Top comments (0)