Simple rest api on golang
to manager tasks in postgresql
database.
- Go 1.20 or newer
- Third party chi package router for rest api
- Third party viper package for configuration
- Postman or
curl
to test the Rest API - Docker to run postgresql container for persisting data
NOTE
: Database name, table name, username, password, database host, database port and application port used in the following configuration need to match the config.toml configuration file.
NOTE
: Run the following commands in terminal to run postgresql
as a docker container
, create database and table for the application:
- Build the
docker
image and runpostgresql
:
$ docker run --name api-tasks -p 5432:5432 -e POSTGRES_PASSWORD=secret -d postgres:15.3-alpine
- List all running docker processes:
$ docker container ps
- List all docker processes:
$ docker ps -a
- Logging into
psql
process asinteractive mode
:
$ docker exec -it api-tasks psql postgres -U postgres
- Create the user:
$ create user user_tasks;
- Give user password:
$ alter user user_tasks with encrypted password '5995';
- Create the database:
$ create database api_tasks;
- List all databases:
$ \l
- Connect to database:
$ \c api_tasks postgres
- Grant user to all on schema public:
$ GRANT ALL ON SCHEMA public TO user_tasks;
- Connect the user to the new database:
$ \c api_tasks user_tasks
- Create the
tasks
table:
$ CREATE TABLE tasks (id serial primary key, title varchar, description text, done bool default false);
- List all tables:
$ \d
- Exit the
psql
process:
$ \q
- Stopping
postgresql
docker container:
$ docker stop api-tasks
- Starting
postgresql
docker container:
$ docker start api-tasks
- Logging into
psql
process asinteractive mode
directly into the new database with new user:
$ docker exec -it api-tasks psql api_tasks -U user_tasks
- Int the root directory, run the following command to run the application:
$ go run main.go
POST
: Create a new task:
$ curl --location --request POST 'localhost:8080/tasks' \
--header 'Content-Type: application/json' \
--data '{
"title": "Home work",
"description": "I need to do all school tasks",
"done": false
}'
GET
: List all tasks:
$ curl --location --request GET 'localhost:8080/tasks'
GET
: Retrieve a task byid
:
$ curl --location --request GET 'localhost:8080/tasks/1'
PUT
: Update a task:
$ curl --location --request PUT 'localhost:8080/tasks/1' \
--header 'Content-Type: application/json' \
--data '{
"title": "Home work",
"description": "I need to do all school tasks",
"done": true
}'
DELETE
: Delete a task byid
:
$ curl --location --request DELETE 'localhost:8080/tasks/1'