A RESTful API built with Go that performs standard CRUD operations on a products resource, backed by a MongoDB database. This API includes the ability to create, read, update, and delete products, with built-in validation for required fields and timestamp management.
- Create, read, update, and delete operations on
products
. - Uses MongoDB for persistent storage.
- Dynamic field handling: Only non-empty fields are inserted or updated in MongoDB.
- Meta timestamps: Automatically handles
createdAt
andupdatedAt
fields. - Field validation: Only allowed fields are accepted, with checks for required fields like
title
andprice
.
To run this project locally, ensure that you have the following prerequisites installed:
- Clone the Repository:
git clone https://github.com/kyratzakos/simple-api-app.git
cd simple-api-app
-
Install Dependencies:
Run the following command in the project root directory to install the required Go dependencies:
go mod tidy
-
Set Up MongoDB:
Ensure MongoDB is running on your machine. You can start MongoDB using:
- Linux/Mac:
sudo service mongod start
- Windows:
net start MongoDB
- Set Environment Variables:
Create a copy of .env.example file in the root directory with name .env
:
- Create Product
- Endpoint: POST /products
- Description: Creates a new product.
- Body Parameters:
{
"title": "Product A",
"description": "A high-quality product",
"price": 199.99,
"category": "Optional",
"meta": {
"createdAt": "optional_timestamp",
"updatedAt": "optional_timestamp"
}
}
- Required Fields:
title
,price
- Response: 201 Created, with the inserted product
id
.
- Get Products (Paginated)
- Endpoint:
GET /products?page=1&limit=10
- Description: Retrieves all products with pagination.
- Query Parameters: page, limit
- Response: 200 OK with paginated product list.
- Endpoint:
- Get Single Product
- Endpoint:
GET /products/{id}
- Description: Retrieves a single product by its MongoDB ObjectId.
- Response: 200 OK with the product data.
- Endpoint:
- Update Product
- Endpoint: PUT /products/{id}
- Description: Updates an existing product's fields dynamically (only non-empty fields are updated).
- Body Parameters:
{
"titel": "Updated Product title",
"price": 299.99,
"meta": {
"updatedAt": "2024-09-17T12:34:56Z"
}
}
- Response: 200 OK with a success message.
- Delete Product
- Endpoint:
DELETE /products/{id}
- Description: Deletes a product by its MongoDB ObjectId.
- Response: 200 OK with a success message.
- Endpoint:
Once you have set up the environment variables and MongoDB is running, you can start the server with:
go run main.go
The API will be available at http://localhost:3000.
- Add unit tests for the CRUD functionality.
- Implement authentication and authorization.
- Add more comprehensive validation for request payloads.