A RESTful API built with Express.js that implements CRUD operations for products, with features like authentication, logging, and error handling.
- RESTful API endpoints for product management
- Authentication using API keys
- Request logging
- Error handling
- Product filtering and pagination
- Search functionality
- Product statistics
- Node.js (v18 or higher)
- npm (Node Package Manager)
- Clone the repository:
git clone <repository-url>
cd <repository-name>- Install dependencies:
npm install- Create a
.envfile based on.env.example:
cp .env.example .env- Update the
.envfile with your configuration:
PORT=3000
API_KEY=your_api_key_here
Start the server:
npm startThe server will start on http://localhost:3000 (or the port specified in your .env file)
All product endpoints require an API key to be sent in the request headers:
X-API-Key: your_api_key_here
-
GET /api/products- Get all products- Query parameters:
category: Filter by categorypage: Page number (default: 1)limit: Items per page (default: 10)
- Example:
GET /api/products?category=electronics&page=1&limit=10
- Query parameters:
-
GET /api/products/:id- Get a specific product- Example:
GET /api/products/1
- Example:
-
POST /api/products- Create a new product- Body:
{ "name": "Product Name", "description": "Product Description", "price": 99.99, "category": "category", "inStock": true }
- Body:
-
PUT /api/products/:id- Update a product- Example:
PUT /api/products/1 - Body: Same as POST
- Example:
-
DELETE /api/products/:id- Delete a product- Example:
DELETE /api/products/1
- Example:
-
GET /api/products/search?q=query- Search products by name- Example:
GET /api/products/search?q=laptop
- Example:
-
GET /api/products/stats/categories- Get product count by category
You can test the API using tools like Postman, Insomnia, or curl. Here's an example using curl:
# Get all products
curl -H "X-API-Key: your_api_key_here" http://localhost:3000/api/products
# Create a new product
curl -X POST -H "Content-Type: application/json" -H "X-API-Key: your_api_key_here" \
-d '{"name":"New Product","description":"Description","price":99.99,"category":"electronics","inStock":true}' \
http://localhost:3000/api/productsThe API uses standard HTTP status codes and returns error messages in JSON format:
{
"error": "Error message here"
}Common status codes:
- 200: Success
- 201: Created
- 400: Bad Request
- 401: Unauthorized
- 403: Forbidden
- 404: Not Found
- 500: Internal Server Error
Week2-Assignment.md: Detailed assignment instructionsserver.js: Starter Express.js server file.env.example: Example environment variables file
Your work will be automatically submitted when you push to your GitHub Classroom repository. Make sure to:
- Complete all the required API endpoints
- Implement the middleware and error handling
- Document your API in the README.md
- Include examples of requests and responses