Build a Product API
Scenario
You are a backend developer for “Zenith,” a rapidly growing e-commerce company. The company needs a robust and scalable API to manage its product inventory. This API will be the backbone of their new online store, used by internal tools for inventory management and by the public-facing website to display products to customers.
Your task is to design and build this RESTful API from the ground up using Node.js, Express, and Mongoose. The API must handle all fundamental CRUD operations and include advanced features like filtering, sorting, and pagination to manage a large and complex product catalog.
Instructions
Task 1: Project Setup
- Initialize Project: Create a new project directory, initialize it with
npm
, and installexpress
,mongoose
, anddotenv
. - Environment: Create a
.env
file to store yourMONGO_URI
connection string and aPORT
for the server. - Security: Create a
.gitignore
file and ensurenode_modules/
and.env
are listed. - Project Structure: Your application must be well-structured with separate directories for your database connection logic, Mongoose models, and Express routes.
server.js
(main entry point)config/
(ordb/
) forconnection.js
models/
forProduct.js
routes/
forproductRoutes.js
Task 2: Schema and Model
- In
models/Product.js
, define aproductSchema
with the following fields and validation rules:name
:String
, required.description
:String
, required.price
:Number
, required, must be greater than 0.category
:String
, required.inStock
:Boolean
, defaults totrue
.tags
: AnArray
ofString
s.createdAt
:Date
, defaults to the current date and time.
- Compile this schema into a model named
Product
and export it.
Task 3: Database Connection
- In your
config/connection.js
file, establish a connection to your MongoDB Atlas database using Mongoose. - Handle both successful connections and connection errors gracefully by logging appropriate messages to the console.
- Execute this connection logic from
server.js
.
Task 4: API Routes and Logic
In routes/productRoutes.js
, use express.Router()
to define your API endpoints. The logic for each route should be handled directly within the route file for this assessment.
Implement the following endpoints. All endpoints must handle potential errors with try...catch
blocks and return appropriate status codes and JSON responses.
-
POST /api/products
(Create a Product)- Creates a new product based on the
req.body
. - Responds with the newly created product and a
201
status code. - If validation fails, it should return a
400
status code with a descriptive error message.
- Creates a new product based on the
-
GET /api/products/:id
(Read a Single Product)- Retrieves a single product by its
_id
. - If the product is found, responds with the product object.
- If no product is found, responds with a
404
status code.
- Retrieves a single product by its
-
PUT /api/products/:id
(Update a Product)- Updates a product by its
_id
with the data fromreq.body
. - Responds with the updated product data (use the
{ new: true }
option). - If no product is found to update, responds with a
404
status code.
- Updates a product by its
-
DELETE /api/products/:id
(Delete a Product)- Deletes a product by its
_id
. - If successful, responds with a success message.
- If no product is found to delete, responds with a
404
status code.
- Deletes a product by its
-
GET /api/products
(Read All Products with Advanced Querying)- This is the most complex endpoint. It should retrieve all products but also support the following optional query parameters:
category
: Filter products by a specific category.minPrice
: Filter products with a price greater than or equal to this value.maxPrice
: Filter products with a price less than or equal to this value.sortBy
: Sort results. For example,price_asc
for ascending price orprice_desc
for descending price.page
&limit
: For pagination (defaulting to page 1, limit 10).
- Dynamically build the Mongoose query based on which query parameters are provided.
- Respond with an array of the resulting products.
- This is the most complex endpoint. It should retrieve all products but also support the following optional query parameters:
Submission Instructions
- Ensure your application is fully functional and structured as described.
- Test all your endpoints thoroughly using an API client like Postman or Insomnia. Pay special attention to the advanced query endpoint, testing various combinations of filters, sorting, and pagination.
- Submit a link to your completed GitHub repository. Ensure your
.env
file andnode_modules
directory are not included.
Grading Rubric
Criteria | Excellent | Satisfactory | Needs Improvement | Points |
---|---|---|---|---|
Project Foundation | (18-20 pts) Project structure is perfectly modular. .env and .gitignore are correctly configured. DB connection is robust, handling success and error states. | (14-17 pts) Project is structured correctly, but some logic might be misplaced. .env is used, but .gitignore may be incomplete. DB connection works but lacks error handling. | (0-13 pts) Project lacks modular structure. Secrets are hardcoded or .gitignore is missing. DB connection is unreliable or non-functional. | 20 |
Mongoose Schema & Model | (14-15 pts) Schema perfectly matches all requirements, including all specified field types, required validations, and default values. | (11-13 pts) Schema is mostly correct but may be missing a validation rule (e.g., required ), a default value, or use a slightly incorrect type for a field. | (0-10 pts) Schema is incomplete, has multiple incorrect types, or is missing most of the required validation. | 15 |
Standard CRUD API | (36-40 pts) All four CRUD endpoints ( POST , GET /:id , PUT /:id , DELETE /:id ) are fully functional, use correct HTTP methods and status codes, and include robust error handling (e.g., for validation and 404 s). | (28-35 pts) Most CRUD endpoints work correctly, but one may be flawed. Error handling or status codes might be inconsistent (e.g., sending 200 on create, or lacking 404 logic). | (0-27 pts) Multiple CRUD endpoints are non-functional or missing. Major issues with error handling, status codes, or core logic. | 40 |
Advanced Querying API | (23-25 pts) The GET /api/products endpoint flawlessly implements and combines filtering (category/price), sorting, and pagination. The query is built dynamically and is efficient. | (18-22 pts) The endpoint works but may not handle all query parameters in combination. Pagination or sorting might be implemented incorrectly. The query logic may be inefficient. | (0-17 pts) The endpoint is missing, non-functional, or only implements one of the required features. Fails to combine query parameters correctly. | 25 |
Total | 100 |