A scalable API for basic arithmetic operations with features like input validation, caching, error handling, and monitoring.
-
API Endpoint: Accepts two numbers and an operation type.
-
Supported Operations: Addition (
+), Subtraction (-), Multiplication (*), Division (/). -
Asynchronous Processing: Use asynchronous handling (e.g., Promises) to ensure a non-blocking API flow.
-
Database Integration: Log all requests and responses in a MongoDB database, including:
- Operation type.
- Input numbers.
- Calculated result.
- Request timestamp.
- Response time.
-
Caching: Implement Redis to cache results for repeated calculations with a TTL (e.g., 60 seconds).
-
Input Validation: Validate inputs using libraries like Joi or Yup to handle:
- Non-numeric inputs.
- Division by zero.
- Missing/invalid operation type.
- Excessive input size.
-
Error Handling: Return detailed error messages in a consistent JSON format with appropriate HTTP status codes:
-
400 Bad Requestfor invalid inputs. -
404 Not Foundfor unsupported operations. -
500 Internal Server Errorfor unexpected issues.
-
-
Response Format: Return results in a JSON structure:
{ "status": "success", "operation": "<operation>", "inputs": { "number1": <number1>, "number2": <number2> }, "result": <result>, "timestamp": "<timestamp>", "responseTime": "<response_time_in_ms>" } -
Scalability: Ensure the API is stateless and handles concurrent requests efficiently.
- Concurrent testing done with Postman. Download the Postman Collection to replicate the tests.
-
Deployability: Deploy with scalable tools like Docker and Kubernetes.
- Deployed the API endpoint by building a Docker image and running it on a network where another Redis container runs. For instructions, check this Running the Application with Docker.
-
Security: Use HTTPS for secure communication.
- Implement rate-limiting to prevent abuse.
- Sanitize inputs to guard against injection attacks.
- Protect sensitive data and handle CORS.
-
Testing with Jest: Create unit and integration tests with Jest for:
- Successful operations.
- Edge cases (e.g., division by zero).
- Error-handling scenarios.
-
API Documentation: Provide comprehensive Swagger/OpenAPI documentation detailing endpoints, parameters, and example responses.
-
Deployment
- Deploy to a cloud platform like AWS, GCP, or Azure.
- Use CI/CD pipelines for automated testing and seamless deployment.
-
Monitoring
- Use tools like Prometheus and Grafana for health, latency, and error rate tracking.
- Log performance metrics centrally with tools like ElasticSearch or CloudWatch.
-
Versioning: Implement versioning (e.g.,
/v1/) to accommodate future updates without disrupting existing clients.
- Clone the repo:
git clone https://github.com/Txaverria/Calculate-API-Endpoint.git
- Install dependencies:
npm install
- Configure
.env:PORT=3000 REDIS_HOST=localhost REDIS_PORT=6379 MONGO_URI=INPUT_YOUR_OWN_MONGO_URI - Start the server:
npm start
- Access the API:
http://localhost:3000/api/v2/calculate(for the v2 version incl)
Follow these steps to run the application using Docker. Ensure you have Docker installed and running on your system.
Build the Docker image for the application:
docker build -t my_api .Create a custom Docker network to allow communication between the app and Redis containers:
docker network create my_app_networkStart a Redis container connected to the custom network:
docker run -d \
--name my_redis \
--network my_app_network \
-p 6380:6379 \
redisThis runs Redis on the internal port 6379 and maps it to port 6380 on the host (this is due to some versions of WSL for Windows 10 running on port 6379).
Ensure you have an .env file in the root of your project directory with the following content:
REDIS_HOST=my_redis
REDIS_PORT=6379
This file configures the app to connect to the Redis container.
Run the API container, connecting it to the same network:
docker run -d --name my_api_container --network my_app_network -p 3000:3000 --env-file .env my_apiThis exposes the application on port 3000 and ensures it uses the .env file for configuration.
- Access the API at
http://localhost:3000using Postman or any browser. - The app will communicate with Redis internally via the Docker network.
To stop and remove the containers:
docker stop my_api_container my_redis
docker rm my_api_container my_redisTo remove the custom Docker network:
docker network rm my_app_network- Modify the
.envfile as needed to customize your Redis or application configuration. - Ensure Docker is running before executing the commands.
- Update the
Dockerfileand.dockerignoreas necessary for your project's needs.

