# 🌾 Crop Yield Prediction API Documentation ## Overview FastAPI-based REST API for crop yield prediction using Random Forest model. ## 🚀 Quick Start ### Local Development ```bash # Install dependencies pip install fastapi uvicorn # Run the API uvicorn app:app --host 0.0.0.0 --port 8000 # API will be available at: http://localhost:8000 ``` ### Docker Deployment ```bash # Build the container docker build -t crop-yield-api . # Run the container docker run -p 8000:8000 crop-yield-api # Or use docker-compose docker-compose up -d ``` ## 📋 API Endpoints ### Base URL ``` http://localhost:8000 ``` --- ## 🎯 Main Prediction Endpoint ### POST `/predict` Predict crop yield based on agricultural parameters. **Input Format (JSON):** ```json { "year": 2024, "state": "Punjab", "crop": "Rice", "season": "Kharif", "area": 10.0, "production": 25.0, "rainfall": 1200, "fertilizer": 75, "pesticide": 8 } ``` **Fields:** - `year` (required): Crop year (integer, e.g., 2024) - `state` (required): State name (string, e.g., "Punjab") - `crop` (required): Crop name (string, e.g., "Rice") - `season` (required): Season (string, e.g., "Kharif", "Rabi", "Summer") - `area` (required): Area in hectares (float) - `production` (required): Production in tons (float) - `rainfall` (optional): Annual rainfall in mm (float, default: 1000) - `fertilizer` (optional): Fertilizer usage in kg (float, default: 50) - `pesticide` (optional): Pesticide usage in kg (float, default: 5) **Response Format:** ```json { "model": "Random Forest", "predicted_yield": "2017.7 kg/hectare", "total_expected_production": "20.18 tons", "assessment": "Good yield expected" } ``` **Example cURL Request:** ```bash curl -X POST "http://localhost:8000/predict" \ -H "Content-Type: application/json" \ -d '{ "year": 2024, "state": "Punjab", "crop": "Rice", "season": "Kharif", "area": 10.0, "production": 25.0, "rainfall": 1200, "fertilizer": 75, "pesticide": 8 }' ``` **Example Python Request:** ```python import requests import json url = "http://localhost:8000/predict" data = { "year": 2024, "state": "Punjab", "crop": "Rice", "season": "Kharif", "area": 10.0, "production": 25.0, "rainfall": 1200, "fertilizer": 75, "pesticide": 8 } response = requests.post(url, json=data) result = response.json() print(json.dumps(result, indent=2)) ``` --- ## 📊 Other Endpoints ### GET `/` Root endpoint with API information. **Response:** ```json { "message": "Crop Yield Prediction API. Use /docs for interactive API documentation.", "version": "1.0.0", "endpoints": { "predict": "/predict", "health": "/health", "docs": "/docs", "available_options": "/available-options" } } ``` ### GET `/health` Health check endpoint. **Response:** ```json { "status": "healthy", "timestamp": "2024-09-11T08:00:00.000000", "model_loaded": true } ``` ### GET `/available-options` Get available states, crops, and seasons. **Response:** ```json { "states": ["Punjab", "Haryana", "Uttar Pradesh", "..."], "crops": ["Rice", "Wheat", "Maize", "..."], "seasons": ["Kharif", "Rabi", "Summer", "Whole Year", "Autumn", "Winter", "Total"], "note": "This shows first 10 states and crops. All are supported in predictions." } ``` ### GET `/docs` Interactive API documentation (Swagger UI). ### GET `/redoc` Alternative API documentation (ReDoc). --- ## 🎯 Assessment Levels The API returns assessment based on predicted yield: | Yield Range | Assessment | |-------------|------------| | > 3000 kg/hectare | "Excellent yield expected" | | 2000-3000 kg/hectare | "Good yield expected" | | 1000-2000 kg/hectare | "Moderate yield expected" | | < 1000 kg/hectare | "Low yield expected" | --- ## ⚠️ Error Responses ### 400 Bad Request ```json { "detail": "Missing required field: crop" } ``` ### 500 Internal Server Error ```json { "detail": "Predictor not initialized. Please check if trained models are available." } ``` --- ## 🔧 Testing Examples ### Test Cases **1. Complete Input:** ```json { "year": 2024, "state": "Punjab", "crop": "Rice", "season": "Kharif", "area": 10.0, "production": 25.0, "rainfall": 1200, "fertilizer": 75, "pesticide": 8 } ``` **2. Minimal Input (using defaults):** ```json { "year": 2024, "state": "Uttar Pradesh", "crop": "Wheat", "season": "Rabi", "area": 15.5, "production": 40.2 } ``` **3. Different Crop:** ```json { "year": 2024, "state": "Maharashtra", "crop": "Sugarcane", "season": "Kharif", "area": 20.0, "production": 80.0, "rainfall": 800 } ``` --- ## 🐳 Docker Commands ```bash # Build image docker build -t crop-yield-api . # Run container docker run -d -p 8000:8000 --name crop-api crop-yield-api # View logs docker logs crop-api # Stop container docker stop crop-api # Remove container docker rm crop-api ``` --- ## 📱 Integration Notes 1. **Content-Type**: Always use `application/json` 2. **HTTP Method**: Use `POST` for predictions 3. **Required Fields**: year, state, crop, season, area, production 4. **Optional Fields**: rainfall, fertilizer, pesticide (have sensible defaults) 5. **Response Format**: Always returns JSON with units included in values 6. **Error Handling**: Check HTTP status codes and `detail` field in errors --- ## 🌍 Production Deployment For production deployment, consider: 1. **Environment Variables**: Configure port, host via env vars 2. **Load Balancing**: Use nginx or similar for multiple instances 3. **Monitoring**: Add logging and metrics collection 4. **Security**: Add authentication if needed 5. **CORS**: Configure CORS for web applications --- ## 🆘 Troubleshooting **Model Not Loading:** - Ensure `trained_models/` directory exists with model files - Check `preprocessor.pkl` and `random_forest_model.pkl` are present **Port Already in Use:** - Change port: `uvicorn app:app --port 8001` - Kill existing process: `pkill -f uvicorn` **API Not Responding:** - Check health endpoint: `curl http://localhost:8000/health` - View logs for errors - Ensure all dependencies are installed