# Build a REST API with Go and Postgres

Source: https://bogie-go.com/guides/go-rest-api-postgres.html

In this guide you build a JSON REST API in Go, backed by Postgres, with create, list, update and delete, and tests that pass. Bogie writes the starting code, so it is fast to build, but everything it writes is plain Go you can read and change: Gin for HTTP, pgx for Postgres, sqlc for typed queries and goose for migrations. Those are the skills you keep.

## What you'll build

A small shop API with one resource, `products`, each with a `name` and a `price_cents`. By the end it answers these routes, with JSON in and out:

```
GET    /products
POST   /products
GET    /products/:id
PATCH  /products/:id
DELETE /products/:id
```

You need Go 1.26 or newer and Docker with Compose v2, which runs Postgres for you. Every command and every output on this page was captured from a real run with Bogie v1.0.1 and Go 1.27; your ids, timestamps and migration names will differ.

## Create the app with bogie new

Install the Bogie command-line tool, then check it:

```
go install github.com/bogie-go/bogie@latest
bogie version
```

```
v1.0.1
```

If your shell says **command not found: bogie**, add Go's bin folder to your `PATH`: `export PATH="$PATH:$(go env GOPATH)/bin"`.

Now create the app. `bogie new` writes a Go service, runs `go mod tidy` and prints the next steps (the long list of `create` lines is trimmed):

```
bogie new shop
```

```
      create  shop/AGENTS.md
      create  shop/CLAUDE.md
      create  shop/Dockerfile
      create  shop/Makefile
...
      create  shop/config/master.key
      create  shop/config/credentials.yml.enc
         run  go mod tidy

Next:
  cd shop
  make up             # postgres on :5440, via docker compose
  bogie db:prepare    # create, migrate, seed
  bogie server
  curl localhost:8080/healthz
```

Start Postgres and prepare the database. `make up` runs Postgres in Docker on port 5440, so it does not clash with a Postgres you may already run on 5432:

```
cd shop
make up
bogie db:prepare
```

```
docker compose up -d --wait
...
 Container shop-db  Healthy
ready: postgres on :5440
time=2026-11-27T17:46:22.722+07:00 level=INFO msg="database already exists" service=shop database=shop_development
time=2026-11-27T17:46:22.722+07:00 level=INFO msg="schema: nothing to apply" service=shop dir=migrate
```

"database already exists" is fine: the Docker container creates `shop_development` when it starts. There are no tables yet, so there is nothing to apply.

## Scaffold a resource

One command writes the whole `products` resource and wires it in:

```
bogie g scaffold product name:string price_cents:integer
```

```
      create  db/migrate/20261127104622_create_products.sql
      create  db/queries/products.sql
      create  app/models/product.go
      create  app/models/product_test.go
      create  db/adapter/products.go
      create  db/adapter/products_test.go
      create  test/factories/products.go
      create  app/views/products.go
      create  app/controllers/products_controller.go
      create  app/controllers/products_controller_test.go
      insert  app/controllers/application.go: Products *ProductsController
      insert  app/application.go: server.Products = controllers.NewProductsController(store, log)
      insert  app/controllers/routes.go: s.Products.SetupRoutes(&r.RouterGroup)
         run  sqlc generate
```

Apply the migration to create the table:

```
bogie db:migrate
```

```
time=2026-11-27T17:46:42.941+07:00 level=INFO msg="schema applied" service=shop from=0 to=20261127104622
```

The scaffold accepts any product until you add rules. Open `app/models/product.go` and make the name required (add `"fmt"` to the imports). This is the only Go you write by hand in this guide:

```
func (p Product) Validate() error {
	if p.Name == "" {
		return fmt.Errorf("%w: name is required", ErrInvalid)
	}
	return nil
}
```

Start the server. It runs on port 8080 and reloads when you save a file:

```
bogie server
```

```
shop: env=development settings="config/credentials.yml.enc" key="config/master.key"
shop: addr=:8080 log_level=debug shutdown_grace=10s database=postgres://postgres:xxxxx@localhost:5440/shop_development?sslmode=disable migrate_at_boot=true
time=2026-11-27T17:46:54.988+07:00 level=INFO msg="schema up to date" service=shop version=20261127104622
...
[GIN-debug] GET    /products                 --> shop/app/controllers.(*ProductsController).Index-fm (4 handlers)
[GIN-debug] POST   /products                 --> shop/app/controllers.(*ProductsController).Create-fm (4 handlers)
[GIN-debug] GET    /products/:id             --> shop/app/controllers.(*ProductsController).Show-fm (4 handlers)
[GIN-debug] PATCH  /products/:id             --> shop/app/controllers.(*ProductsController).Update-fm (4 handlers)
[GIN-debug] DELETE /products/:id             --> shop/app/controllers.(*ProductsController).Destroy-fm (4 handlers)
time=2026-11-27T17:46:54.992+07:00 level=INFO msg="http listening" service=shop addr=:8080 env=development
```

## Create, list, update and delete with curl

In a second terminal, call the API. Each response below is real; the headers are trimmed to the status line.

### Create

A blank name is refused with a 422, from the rule you just wrote. A good product is created with a 201:

```
$ curl -i -X POST localhost:8080/products \
    -H "Content-Type: application/json" -d '{"name":""}'
HTTP/1.1 422 Unprocessable Entity

{"status":"error","error":"invalid: name is required"}

$ curl -i -X POST localhost:8080/products \
    -H "Content-Type: application/json" -d '{"name":"Blue mug","price_cents":1250}'
HTTP/1.1 201 Created

{"id":1,"name":"Blue mug","price_cents":1250,"created_at":"2026-11-27T17:48:55.75735+07:00","updated_at":"2026-11-27T17:48:55.75735+07:00"}
```

### List

```
$ curl localhost:8080/products
{"products":[{"id":1,"name":"Blue mug","price_cents":1250,"created_at":"2026-11-27T17:48:55.75735+07:00","updated_at":"2026-11-27T17:48:55.75735+07:00"}]}
```

### Update

`PATCH` changes only the fields you send. The name stays, the price changes, and `updated_at` moves:

```
$ curl -i -X PATCH localhost:8080/products/1 \
    -H "Content-Type: application/json" -d '{"price_cents":990}'
HTTP/1.1 200 OK

{"id":1,"name":"Blue mug","price_cents":990,"created_at":"2026-11-27T17:48:55.75735+07:00","updated_at":"2026-11-27T17:48:55.827179+07:00"}
```

### Delete

A delete answers 204 with no body. After it, the list is empty and the product is a 404:

```
$ curl -i -X DELETE localhost:8080/products/1
HTTP/1.1 204 No Content

$ curl localhost:8080/products
{"products":[]}

$ curl -i localhost:8080/products/1
HTTP/1.1 404 Not Found

{"status":"error","error":"no such product"}
```

### Run the tests

The scaffold wrote tests for the model, the store and the controller. They run against their own database, `shop_test`, so your development data is safe. Create it once, then run the suite:

```
SHOP_ENV=test bogie db:prepare
bogie test
```

Every package passed on this run (trimmed to the packages with tests):

```
ok  	shop/app/controllers	3.146s	coverage: 76.7% of statements
ok  	shop/app/middlewares	1.029s	coverage: 0.0% of statements
ok  	shop/app/models	1.038s	coverage: 66.7% of statements
ok  	shop/app/services/database	1.025s	coverage: 43.4% of statements
ok  	shop/app/services/migrate	1.025s	coverage: 2.9% of statements
ok  	shop/config	1.038s	coverage: 73.1% of statements
ok  	shop/db/adapter	1.612s	coverage: 63.3% of statements
ok  	shop/test/requests	1.284s	coverage: [no statements]
```

## What got generated: Gin, pgx, sqlc and goose

Nothing here is magic, and the app never imports Bogie. Each piece is a standard Go tool you can use in any Go service:

**goose** runs the migration in `db/migrate/`, plain SQL with an up and a down:

```
-- +goose Up
CREATE TABLE products (
    id         bigserial   PRIMARY KEY,
    name       varchar     NOT NULL DEFAULT '',
    price_cents integer     NOT NULL DEFAULT 0,
    created_at timestamptz NOT NULL DEFAULT now(),
    updated_at timestamptz NOT NULL DEFAULT now()
);

-- +goose Down
DROP TABLE products;
```

**sqlc** reads the named queries in `db/queries/products.sql` and generates typed Go for them in `db/sqlc/products.sql.go`. You edit the SQL, never the generated file:

```
-- name: ListProducts :many
SELECT * FROM products ORDER BY created_at DESC, id DESC LIMIT $1;

-- name: CreateProduct :one
INSERT INTO products (name, price_cents) VALUES ($1, $2) RETURNING *;
```

**pgx** is the Postgres driver those generated functions call. `db/adapter/products.go` is the store between them and your model.

**Gin** handles HTTP. `app/controllers/products_controller.go` mounts the five routes and turns requests into model calls:

```
func (ctl *ProductsController) SetupRoutes(router *gin.RouterGroup) {
	products := router.Group("/products")
	products.GET("", ctl.Index)
	products.POST("", ctl.Create)
	products.GET("/:id", ctl.Show)
	products.PATCH("/:id", ctl.Update)
	products.DELETE("/:id", ctl.Destroy)
}
```

The model in `app/models/product.go` is a plain struct with your `Validate` rule, and `app/views/products.go` holds the JSON request and response shapes. The tests use Ginkgo and Gomega. The [controllers](https://bogie-go.com/docs/controllers.html) and [models](https://bogie-go.com/docs/models.html) docs go through each file.

## How the project is laid out

A Go REST API project needs a structure you can find your way around. Bogie lays the app out by role, so each file sits where its job says it should. This is the real tree from this guide's app, trimmed to the main folders:

```
app/
  controllers/   HTTP: routes and handlers, with Gin
  models/        your types and their Validate rules; imports nothing third-party
  views/         the JSON request and response shapes
  services/      logic with no HTTP in it (database and migrate ship built in)
  middlewares/   request id, logging, recover
config/          settings: encrypted credentials plus env, and Kamal's deploy.yml
db/
  migrate/       goose SQL migrations, one file per change
  queries/       named SQL that sqlc compiles
  sqlc/          Go generated by sqlc
  adapter/       the store between your models and sqlc
  seeds/         plain Go seed functions
test/            what tests share: test database, factories, the whole app
```

Tests sit beside the code they test, such as `app/models/product_test.go`. Most of this is yours to edit: models, controllers, views, tests and factories. Three things belong to the generators: never edit `db/sqlc/` (change the SQL in `db/queries/`, then run `make sqlc`); don't edit a file whose header says "overwritten whole on the next run", such as `db/queries/products.sql` and `db/adapter/products.go`, but put your own code in a `products_extra` file beside it; and never edit a migration that has already run, but add a new one with `bogie g migration`. The [Conventions and agents](https://bogie-go.com/docs/conventions.html) doc explains why the layout is this way.

## FAQ

### Is Go good for web development?

Yes, for APIs and backends. The standard library ships an HTTP server (net/http) and JSON encoding, the compiler catches type mistakes before you run anything, and a Go program builds to a single binary you can copy to a server. Go is a common choice for JSON APIs like the one in this guide.

### Do I need a framework?

No. Go's standard library net/http is enough to build a JSON API, and the free [Go with AI](https://bogie-go.com/go-with-ai/go-web-api-net-http/) book builds one that way. A generator like Bogie saves the setup: it writes the routes, migrations, queries, validation hook and tests for you. What it writes is plain Go using Gin, pgx, sqlc and goose, and the app never imports Bogie, so you can change or drop any of it.

### Which Postgres driver should I use?

pgx (github.com/jackc/pgx/v5) is the usual choice for Postgres in Go, and it is what this app uses. sqlc sits on top: you write plain SQL queries, and sqlc generates typed Go functions that call them through pgx.

## What you built

A JSON REST API on Postgres with create, list, update and delete, a validation rule, a migration, typed queries and passing tests, all in plain Go you own.

Full walkthrough in Chapter 1 and Chapter 3 of the [Bogie book](https://bogie-go.com/book.html). For every command and flag, see [Getting started](https://bogie-go.com/docs/getting-started.html).

New to Go? [Read the free Go with AI book first](https://bogie-go.com/go-with-ai/).
