This repository demonstrates how to set up a Go REST API using the sqlc
tool for generating type-safe SQL queries from PostgreSQL database schemas.
- RESTful API structure
- Type-safe SQL queries using
sqlc
- PostgreSQL database integration
- CRUD operations
- Installing recent versions of sqlc requires Go 1.21+.
- PostgreSQL
- sqlc (installation instructions below)
-
Clone the repository:
git clone git clone https://github.com/muthukumar89uk/go-restapi-with-sqlc.git
Click here to directly download it.
-
Install sqlc:
go install github.com/sqlc-dev/sqlc/cmd/sqlc@latest
-
Install dependencies:
go mod tidy
-
Define SQL Queries:
Create a
sqlc.yaml
file in your project root with the following content:version: "1" packages: - name: "db" path: "internal/db" queries: "./sql/" schema: "./schema/" engine: "postgresql"
-
Create SQL Files:
Create a directory structure for your SQL files:
. ├── sql │ ├── queries.sql | └── schema.sql
-
sql/queries.sql:
-- name: CreateCareer :one INSERT INTO career (Company,Position,Jobtype,Description,StartDate,EndDate) VALUES ($1, $2,$3,$4,$5,$6) RETURNING *; -- name: GetCareerByJobId :one SELECT * FROM career WHERE jobid = $1 LIMIT 1; -- name: GetAllCareerDetails :many SELECT * FROM career; -- name: UpdateCareerByJobId :one UPDATE career SET company=$1,position=$2,jobtype=$3,description=$4 WHERE jobid = $5 RETURNING *; -- name: DeleteCareerByJobId :one DELETE FROM career WHERE jobid = $1 RETURNING *;
-
sql/schema.sql:
CREATE TABLE IF NOT EXISTS Career ( JobID BIGSERIAL PRIMARY KEY, Company VARCHAR(255) NOT NULL, Position VARCHAR(255) NOT NULL, Jobtype VARCHAR(255) NOT NULL, Description VARCHAR(255) NOT NULL, StartDate DATE NOT NULL , EndDate DATE NOT NULL );
-
-
Generate Code:
Run the
sqlc
command to generate Go code from the SQL queries:sqlc generate
-
Run the application:
go run .
-
Access the API:
The API will be available at
http://localhost:8080
.Example Endpoints:
GET /get-all-career-details
- Retrieve all career-detailsGET /getcareerdetail/:id
- Retrieve an career details by IDPOST /create-career
- Create a new careerPUT /updatecareer/:id
- Update an existing careerDELETE /deletecareer/:id
- Delete a career