A RESTful API built with Go and Gin framework for managing a library's book inventory. This API provides endpoints for CRUD operations on books and handles book checkout/return functionality.
- Get all books
- Get a specific book by ID
- Create a new book
- Update an existing book
- Delete a book
- Checkout a book
- Return a book
- Automatic inventory management
- Duplicate book prevention
- Go 1.16 or higher
- Git
go-api/
├── main.go
└── README.md
- Clone the repository:
git clone <your-repository-url>
cd go-api
- Install dependencies:
go mod tidy
- Run the application:
go run main.go
The server will start on http://localhost:8080
The application is available as a Docker image on Docker Hub. You can run it using:
docker run -it -p 8080:8080 shivang21007/book-api:v1.0
This command will:
- Pull the image from Docker Hub
- Run it in interactive mode (-it)
- Map port 8080 from the container to port 8080 on your host machine (-p 8080:8080)
The API will be accessible at http://localhost:8080
GET http://localhost:8080/books
GET http://localhost:8080/books/:id
POST http://localhost:8080/books
Sample request body:
{
"id": "5",
"title": "The Hobbit",
"author": "J.R.R. Tolkien",
"quantity": 3
}
PUT http://localhost:8080/books/:id
Sample request body:
{
"id": "5",
"title": "The Hobbit",
"author": "J.R.R. Tolkien",
"quantity": 4
}
DELETE http://localhost:8080/books/:id
PATCH http://localhost:8080/checkout?id=:id
PATCH http://localhost:8080/return?id=:id
Here are some example cURL commands to test the API:
- Get all books:
curl http://localhost:8080/books
- Get a specific book:
curl http://localhost:8080/books/1
- Create a new book:
curl -X POST http://localhost:8080/books \
-H "Content-Type: application/json" \
-d '{
"id": "5",
"title": "The Hobbit",
"author": "J.R.R. Tolkien",
"quantity": 3
}'
- Update a book:
curl -X PUT http://localhost:8080/books/1 \
-H "Content-Type: application/json" \
-d '{
"id": "1",
"title": "Updated Title",
"author": "Updated Author",
"quantity": 5
}'
- Delete a book:
curl -X DELETE http://localhost:8080/books/1
- Checkout a book:
curl -X PATCH "http://localhost:8080/checkout?id=1"
- Return a book:
curl -X PATCH "http://localhost:8080/return?id=1"
The API includes proper error handling for various scenarios:
- Invalid request body (400 Bad Request)
- Book not found (404 Not Found)
- Duplicate book ID (409 Conflict)
- Duplicate book title (409 Conflict)
- Book not available for checkout (400 Bad Request)
- Cannot return more books than original quantity (400 Bad Request)
Feel free to submit issues and enhancement requests!