The Sleep Tracker API allows users to track their sleep duration and timestamps. It supports creating, retrieving, and deleting sleep records for each user.
- POST
/api/sleep
: Create a new sleep record. - GET
/api/sleep/:userId
: Retrieve all sleep records for a given user, sorted by date. - DELETE
/api/sleep/:recordId
: Delete a specific sleep record by its ID.
-
Clone the Repository
git clone https://github.com/RajdeepDas43/Sleep-Tracker-REST-API.git
-
Install Dependencies
npm install
-
Set Up Environment Variables
Create a
.env
file in the root directory of the project and add the following variables:DB_URI=mongodb://localhost:27017/sleep-tracker PORT=3000
Adjust the
DB_URI
to match your MongoDB configuration. -
Run the Server
npm start
The server will start on the port specified in the
.env
file (default is3000
). -
Run Tests
To run the test suite, use the following command:
npm test
-
Endpoint:
POST /api/sleep
-
Description: Adds a new sleep record.
-
Request Body:
{ "userId": "string", // MongoDB ObjectId "hours": "number", // Number of hours slept "timestamp": "string" // ISO 8601 format date }
-
Response:
-
201 Created:
{ "_id": "string", "userId": "string", "hours": "number", "timestamp": "string", "createdAt": "string", "updatedAt": "string" }
-
400 Bad Request:
{ "message": "Invalid input data" }
-
-
Endpoint:
GET /api/sleep/:userId
-
Description: Retrieves all sleep records for a given user, sorted by date.
-
Parameters:
userId
: MongoDB ObjectId of the user
-
Response:
-
200 OK:
[ { "_id": "string", "userId": "string", "hours": "number", "timestamp": "string", "createdAt": "string", "updatedAt": "string" } ]
-
400 Bad Request:
{ "message": "Invalid user ID" }
-
-
Endpoint:
DELETE /api/sleep/:recordId
-
Description: Deletes a specific sleep record by its ID.
-
Parameters:
recordId
: MongoDB ObjectId of the sleep record
-
Response:
-
204 No Content: Successfully deleted the record.
-
404 Not Found:
{ "message": "Record not found" }
-
400 Bad Request:
{ "message": "Invalid record ID" }
-
The API uses consistent error handling for various scenarios:
- 400 Bad Request: For invalid inputs or parameters.
- 404 Not Found: For non-existing records.
- 500 Internal Server Error: For unexpected server errors.
Contributions are welcome! Please follow these steps:
- Fork the repository.
- Create a new branch (
git checkout -b feature-branch
). - Make your changes.
- Commit your changes (
git commit -m 'Add new feature'
). - Push to the branch (
git push origin feature-branch
). - Open a Pull Request.
This project is licensed under the MIT License.
For any questions or issues, please open an issue on GitHub or contact at the email sohom432@gmail.com.