This project is a RESTful API to learn Golang, using the Gin framework and MySQL for data persistence.
It allows users to manage a music album database, with functionality to add, retrieve, and filter albums, inspired by ideas from Go tutorials pages:
- Retrieve all albums or filter by artist.
- Retrieve a single album by its ID.
- Add new albums to the database.
- Go 1.16+
- MySQL
- Gin Web Framework
- go-sql-driver/mysql
- godotenv for managing environment variables
-
Clone the repository:
git clone https://github.com/ZnarKhalil/albums-api.git cd albums-api
-
Copy the example environment file:
cp .env.example .env
-
Update the .env file with your MySQL database credentials
-
Download dependencies:
go mod tidy
-
Set up the database: by creating a MySQL database named recordings and a table album
CREATE DATABASE recordings; USE recordings; CREATE TABLE album ( id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(255) NOT NULL, artist VARCHAR(255) NOT NULL, price DECIMAL(10, 2) NOT NULL );
To start the server, run:
go run main.go
The server will run on localhost:8080 by default.
- Retrieve All Albums:
-
URL: /albums
-
Method: GET
-
Query Parameter (optional): artist
-
Description: Retrieves all albums, or filters albums by the specified artist.
curl http://localhost:8080/albums?artist=John%20Coltrane
- Add a New Album:
-
URL: /albums
-
Method: POST
-
Description: Adds a new album to the database.
-
Request Body:
{ "title": "The Modern Sound of Betty Carter", "artist": "Betty Carter", "price": 49.99 }
curl -X POST http://localhost:8080/albums -H "Content-Type: application/json" -d '{ "title": "The Modern Sound of Betty Carter", "artist": "Betty Carter", "price": 49.99 }'
- Retrieve a Single Album by ID:
-
URL: /albums/:id
-
Method: GET
-
Description: Retrieves the album with the specified ID.
curl http://localhost:8080/albums/2
The project follows a standard Go project structure:
library/
├── main.go # Entry point of the application
├── db/
│ └── db.go # Database connection setup
├── handlers/
│ └── album.go # Handler functions for album-related endpoints
├── models/
│ └── album.go # Album struct and database functions
├── .env.example # Environment variables file
├── go.mod # Go module file
└── README.md # Project documentation