Skip to content

ASR134/Rainfall-prediction-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

11 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐ŸŒง๏ธ Rainfall Prediction API

FastAPI Python scikit-learn License: MIT

A machine learning-powered REST API that predicts whether it will rain based on weather parameters. Built with FastAPI and a trained ML model, this API can be easily integrated with any frontend application (Streamlit, React, Vue, mobile apps, etc.).


๐Ÿš€ Features

  • ๐Ÿ”ฎ Intelligent Rain Prediction โ€“ Binary classification (Rain / No Rain)
  • โšก FastAPI Backend โ€“ High-performance async API with automatic Swagger UI
  • ๐Ÿง  Server-Side Feature Engineering โ€“ Automatically computes derived features (e.g., temp_range)
  • ๐Ÿงช Interactive Testing โ€“ Built-in Swagger documentation at /docs
  • ๐ŸŒ Cloud-Ready โ€“ Deploy to Render, Railway, AWS, or any cloud platform
  • ๐Ÿ“Š Production-Ready โ€“ Optimized model loading and efficient inference

๐Ÿง  Model Inputs

The API expects the following weather parameters:

Parameter Type Description Example
pressure float Atmospheric pressure (hPa) 1012.5
temperature float Average temperature (ยฐC) 26.0
humidity float Relative humidity (%) 70.0
cloud float Cloud cover (%) 60.0
sunshine float Hours of sunshine 5.0
winddirection float Wind direction (0โ€“360ยฐ, 0 = North) 180.0
windspeed float Wind speed (km/h) 10.0
max_temp float Maximum temperature of the day (ยฐC) 30.0
min_temp float Minimum temperature of the day (ยฐC) 22.0

โ„น๏ธ Note: temp_range = max_temp - min_temp is computed automatically by the API during inference.


๐Ÿ“ฆ Project Structure

rainfall-api/
โ”‚
โ”œโ”€โ”€ main.py                  # FastAPI application
โ”œโ”€โ”€ rainfall_model.pkl       # Trained ML model
โ”œโ”€โ”€ requirements.txt         # Python dependencies
โ”œโ”€โ”€ README.md               # Project documentation
โ”œโ”€โ”€ .gitignore              # Git ignore rules
โ””โ”€โ”€ Dockerfile              # (Optional) Docker configuration

๐Ÿ› ๏ธ Setup & Run Locally

1๏ธโƒฃ Clone the Repository

git clone https://github.com/your-username/rainfall-api.git
cd rainfall-api

2๏ธโƒฃ Create a Virtual Environment (Recommended)

# On Windows
python -m venv venv
venv\Scripts\activate

# On macOS/Linux
python3 -m venv venv
source venv/bin/activate

3๏ธโƒฃ Install Dependencies

pip install -r requirements.txt

4๏ธโƒฃ Run the API

uvicorn main:app --reload

The API will start at http://127.0.0.1:8000

5๏ธโƒฃ Open Swagger UI

Visit the interactive API documentation:

๐Ÿ‘‰ http://127.0.0.1:8000/docs


๐Ÿ”Œ API Endpoints

POST /predict

Predicts whether it will rain based on input weather parameters.

Request Body (JSON)

{
  "pressure": 1012.5,
  "temperature": 26.0,
  "humidity": 70.0,
  "cloud": 60.0,
  "sunshine": 5.0,
  "winddirection": 180.0,
  "windspeed": 10.0,
  "max_temp": 30.0,
  "min_temp": 22.0
}

Response

{
  "prediction": "Rain"
}

or

{
  "prediction": "No Rain"
}

GET /

Health check endpoint.

Response

{
  "message": "Rainfall Prediction API is running!"
}

๐Ÿงช Testing the API

Using cURL

curl -X POST http://127.0.0.1:8000/predict \
  -H "Content-Type: application/json" \
  -d '{
    "pressure": 1012.5,
    "temperature": 26.0,
    "humidity": 70.0,
    "cloud": 60.0,
    "sunshine": 5.0,
    "winddirection": 180.0,
    "windspeed": 10.0,
    "max_temp": 30.0,
    "min_temp": 22.0
  }'

Using Python requests

import requests

url = "http://127.0.0.1:8000/predict"
data = {
    "pressure": 1012.5,
    "temperature": 26.0,
    "humidity": 70.0,
    "cloud": 60.0,
    "sunshine": 5.0,
    "winddirection": 180.0,
    "windspeed": 10.0,
    "max_temp": 30.0,
    "min_temp": 22.0
}

response = requests.post(url, json=data)
print(response.json())

โ˜๏ธ Deployment

Deploy to Render

  1. Push your code to GitHub
  2. Create a new Web Service on Render
  3. Connect your GitHub repository
  4. Set the following:
    • Build Command: pip install -r requirements.txt
    • Start Command: uvicorn main:app --host 0.0.0.0 --port $PORT
  5. Deploy! ๐Ÿš€

Deploy to Railway

  1. Install the Railway CLI
  2. Run:
    railway login
    railway init
    railway up

Deploy with Docker

FROM python:3.9-slim

WORKDIR /app

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

Build and run:

docker build -t rainfall-api .
docker run -p 8000:8000 rainfall-api

๐Ÿง  How the Model Was Trained

The rainfall prediction model was trained using historical weather data with the following approach:

  1. Data Collection: Weather observations including temperature, humidity, pressure, wind metrics, and rainfall records
  2. Feature Engineering:
    • Created temp_range feature (max_temp - min_temp)
    • Normalized numerical features
    • Handled missing values and outliers
  3. Model Selection: Tested multiple algorithms (Logistic Regression, Random Forest, XGBoost)
  4. Training: Used scikit-learn with cross-validation for robust performance
  5. Evaluation: Achieved strong performance on validation set using metrics like accuracy, precision, and recall
  6. Serialization: Saved the trained model using joblib for efficient loading

๐Ÿ’ก Future Improvements: Plans to integrate time-series features and ensemble methods for better accuracy.


๐Ÿงฐ Tech Stack

  • FastAPI โ€“ Modern, fast web framework for building APIs
  • scikit-learn โ€“ Machine learning library for model training
  • pandas โ€“ Data manipulation and preprocessing
  • joblib โ€“ Model serialization
  • uvicorn โ€“ ASGI server for production deployment

๐Ÿ“ Requirements

fastapi==0.104.1
uvicorn==0.24.0
scikit-learn==1.3.2
pandas==2.1.3
joblib==1.3.2
pydantic==2.5.0

๐Ÿ“Œ Important Notes

  • โœ… Ensure feature names and order match the training data exactly
  • โœ… The model is loaded once at startup for optimal performance
  • โœ… API is designed to be consumed by any frontend or mobile application
  • โœ… CORS is enabled for cross-origin requests (configure as needed)

๐Ÿค Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the project
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.


๐Ÿ™Œ Author

Aman Rawat


๐ŸŒŸ Support

If you found this project helpful, please give it a โญ๏ธ!


Built with โค๏ธ using FastAPI and Machine Learning

About

Api for rainfall prediction using fastapi

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages