A production-ready RESTful API built with Node.js and Express.js that integrates with OpenWeatherMap API to deliver real-time weather data with intelligent caching mechanisms.
- Overview
- Key Features
- Architecture & Design Patterns
- Technical Stack
- Installation
- API Documentation
- Performance Optimization
- Error Handling
- Testing
- Project Structure
This Weather Dashboard API demonstrates professional backend development practices, including:
- RESTful API Design: Clean, intuitive endpoint structure following REST principles
- Third-party API Integration: Seamless integration with OpenWeatherMap API
- Performance Optimization: In-memory caching strategy to reduce latency and API costs
- Error Handling: Comprehensive error management with proper HTTP status codes
- Clean Code: Modular architecture with separation of concerns
Use Case: Ideal for weather applications, travel platforms, or any service requiring real-time weather information.
- 🌡️ Real-time Weather Data - Fetch current weather conditions for any global city
- 💾 Intelligent Caching - In-memory cache system with 10-minute TTL (Time To Live)
- 🌐 RESTful Architecture - Well-structured API endpoints following REST conventions
- ⚡ High Performance - Optimized response times with Express.js and smart caching
- 🔄 Data Transformation - Converts raw API data into clean, consumable JSON format
- 🛡️ Robust Error Handling - Graceful error management with descriptive messages
- 🔐 Environment Security - Secure API key management using environment variables
- 📊 Detailed Responses - Comprehensive weather metrics including temperature, humidity, wind speed
- MVC Pattern: Separation of routes (controllers) from business logic
- Middleware Pattern: Express.js middleware for JSON parsing and routing
- Cache-Aside Pattern: Data retrieved from cache if available, otherwise fetched from API
- Environment Configuration Pattern: Using dotenv for configuration management
// Cache Implementation Highlights
- Storage: In-memory JavaScript object
- TTL: 10 minutes (600,000 ms)
- Cache Key: City name
- Benefits: Reduced API calls, faster response times, cost optimization| Technology | Purpose | Version |
|---|---|---|
| Node.js | Runtime environment | v14+ |
| Express.js | Web framework | v5.1.0 |
| Axios | HTTP client for API requests | v1.13.2 |
| dotenv | Environment variable management | v17.2.3 |
| OpenWeatherMap API | Weather data provider | v2.5 |
- ✅ Node.js (v14 or higher)
- ✅ npm (Node Package Manager)
- ✅ OpenWeatherMap API key (Get it here)
1. Clone the repository:
git clone https://github.com/PasinduOG/Weather-Dashboard-API.git
cd Weather-Dashboard-API2. Install dependencies:
npm install3. Environment Configuration:
Create a .env file in the root directory:
API_KEY=your_openweathermap_api_key_here
PORT=30004. Start the server:
Development mode (with auto-reload):
npm run devProduction mode:
npm startServer will be running at: http://localhost:3000
http://localhost:3000
| Method | Endpoint | Description | Cache |
|---|---|---|---|
GET |
/ |
API information and available routes | ❌ |
GET |
/weather/current/:city |
Get current weather for a city | ✅ |
Endpoint: GET /
Description: Returns API metadata and available endpoints for discovery.
Response:
{
"message": "Weather Dashboard API",
"endpoints": {
"current": "weather/current/:city",
"forecast": "weather/forecast/:city",
"compare": "weather/compare (POST)"
}
}Endpoint: GET /weather/current/:city
Description: Retrieves real-time weather data for a specified city with automatic caching.
URL Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
city |
string | Yes | City name (e.g., "London", "New York", "Tokyo") |
Example Request:
# Using curl
curl http://localhost:3000/weather/current/Colombo
# Using JavaScript fetch
fetch('http://localhost:3000/weather/current/Colombo')
.then(response => response.json())
.then(data => console.log(data));Success Response (200 OK):
{
"title": "Weather Dashboard API",
"author": "PasinduOG",
"source": "openweathermap.org",
"data": {
"city": "Colombo",
"country": "LK",
"temperature": 32.5,
"feelsLike": 36.8,
"condition": "Clear",
"description": "clear sky",
"humidity": 75,
"windSpeed": 5.2,
"icon": "https://openweathermap.org/img/wn/01d@2x.png"
}
}Cached Response (200 OK): When data is served from cache (within 10 minutes):
{
"source": "cache",
"data": {
"city": "Colombo",
"country": "LK",
"temperature": 32.5,
"feelsLike": 36.8,
"condition": "Clear",
"description": "clear sky",
"humidity": 75,
"windSpeed": 5.2,
"icon": "https://openweathermap.org/img/wn/01d@2x.png"
}
}Error Response (404 Not Found):
{
"error": "City not found or API error",
"message": "city not found"
}Error Response (500 Internal Server Error):
{
"error": "Failed to fetch weather data",
"message": "Network error or invalid API key"
}The API implements an in-memory caching mechanism to optimize performance:
// Cache Strategy Details
{
"implementation": "In-memory JavaScript Object",
"TTL": "10 minutes (600,000ms)",
"key": "City name",
"eviction": "Time-based expiration"
}Benefits:
- ✅ Reduced Latency: Cache hits return data in <10ms vs ~500ms API calls
- ✅ Cost Optimization: Minimizes API usage and associated costs
- ✅ Better UX: Faster response times improve user experience
- ✅ API Rate Limit Management: Reduces risk of hitting rate limits
Cache Performance Metrics:
- Cache Hit: ~5-10ms response time
- Cache Miss (API Call): ~200-500ms response time
- Cache Size: Grows dynamically based on unique city requests
- 🔄 Implement Redis for distributed caching
- 📊 Add cache hit/miss metrics
- 🧹 Implement LRU (Least Recently Used) eviction policy
- ⚙️ Make TTL configurable via environment variables
The API implements comprehensive error handling:
| Error Type | HTTP Status | Description |
|---|---|---|
| City Not Found | 404 |
Invalid or non-existent city name |
| API Key Missing | 401 |
Missing or invalid OpenWeatherMap API key |
| Rate Limit Exceeded | 429 |
Too many requests to external API |
| Network Error | 500 |
Connection issues with external API |
| Server Error | 500 |
Internal server errors |
{
"error": "Error category",
"message": "Detailed error description"
}# Test valid city
curl http://localhost:3000/weather/current/Colombo
# Test invalid city
curl http://localhost:3000/weather/current/InvalidCityXYZ
# Test root endpoint
curl http://localhost:3000/- First request (Cache miss - slower):
time curl http://localhost:3000/weather/current/Kandy- Second request (Cache hit - faster):
time curl http://localhost:3000/weather/current/Kandy- After 10 minutes (Cache expired - slower):
time curl http://localhost:3000/weather/current/KandyWeather-Dashboard-API/
├── 📄 index.js # Application entry point & Express server configuration
├── 📁 routes/
│ └── 📄 weather.js # Weather route handlers & caching logic
├── 📄 package.json # Dependencies, scripts, and project metadata
├── 📄 .env # Environment variables (not version controlled)
├── 📄 README.md # Comprehensive project documentation
└── 📄 LICENSE # MIT License
index.js: Initializes Express server, configures middleware, and defines routesroutes/weather.js: Contains weather endpoint logic, API integration, and cache managementpackage.json: Defines project dependencies and npm scripts.env: Stores sensitive configuration (API keys) - excluded from Git
✅ Modular Architecture: Separation of concerns with route-based organization
✅ Environment Variables: Secure credential management using dotenv
✅ Async/Await: Modern JavaScript for cleaner asynchronous code
✅ Error Handling: Try-catch blocks with proper error propagation
✅ RESTful Design: Intuitive endpoint structure following REST principles
✅ Caching Strategy: Performance optimization through intelligent caching
✅ Clean Code: Readable, maintainable code with clear naming conventions
- API Integration: How to integrate third-party APIs securely
- Performance: Caching strategies and their trade-offs
- Error Handling: Comprehensive error management patterns
- Architecture: MVC-inspired structure in Node.js
- Scalability: Potential improvements for production (Redis, load balancing)
- Security: Environment variable usage and API key protection
- 🔑 API Keys: Stored in
.envfile, never committed to version control - 🛡️ Input Validation: City parameters are validated before API calls
- 🚫 Error Messages: Avoid exposing sensitive internal information
⚠️ Rate Limiting: Caching helps prevent API rate limit issues
.gitignore should include:
node_modules/
.env
*.log
- Heroku: Easy deployment with built-in Node.js support
- AWS EC2/Lambda: Scalable cloud infrastructure
- DigitalOcean: Cost-effective VPS hosting
- Vercel/Netlify: Serverless deployment options
API_KEY=your_production_api_key
PORT=3000
NODE_ENV=productionContributions are welcome! Here's how you can contribute:
- 🍴 Fork the repository
- 🔨 Create a feature branch:
git checkout -b feature/AmazingFeature - 💾 Commit your changes:
git commit -m 'Add AmazingFeature' - 📤 Push to the branch:
git push origin feature/AmazingFeature - 🔍 Open a Pull Request
- Write clean, documented code
- Follow existing code style
- Add tests for new features
- Update README if needed
This project is licensed under the MIT License - see the LICENSE file for details.
Copyright (c) 2025 PasinduOG
PasinduOG
- 🐙 GitHub: @PasinduOG
- 💼 LinkedIn: Connect with me
- 📧 Email: Contact
- 🌤️ Weather data provided by OpenWeatherMap
- 🟢 Built with Node.js and Express.js
- 📚 Inspired by modern REST API best practices
- 📅 5-Day Weather Forecast - Extended forecast endpoint
- 🔄 City Comparison - Compare weather across multiple cities
- 🌡️ Temperature Unit Conversion - Support for Celsius/Fahrenheit/Kelvin
- 🔴 Redis Integration - Distributed caching for scalability
- 📊 Rate Limiting - Protect API from abuse
- 📈 Analytics Dashboard - Track API usage and performance metrics
- 🐳 Docker Support - Containerization for easy deployment
- 🔐 User Authentication - JWT-based authentication
- 🗄️ Database Integration - PostgreSQL/MongoDB for persistent storage
-
⚠️ Weather Alerts - Notification system for severe weather - 🌍 Multi-language Support - Internationalization (i18n)
- 📱 WebSocket Support - Real-time weather updates
- 🧪 Unit & Integration Tests - Jest/Mocha test coverage
- 📊 Logging System - Winston/Morgan for structured logging
- 🔍 API Versioning - Version management (v1, v2)
- 📚 Swagger/OpenAPI - Interactive API documentation
- 🚨 Monitoring & Alerting - Integration with Datadog/New Relic
- ⚙️ CI/CD Pipeline - Automated testing and deployment
- 📖 Documentation: Check this README for detailed information
- 🐛 Bug Reports: Open an issue
- 💬 Questions: Start a discussion
- ⭐ Star this repo if you find it helpful!
⭐ If you found this project helpful, please consider giving it a star! ⭐
Made with ❤️ by PasinduOG