SIH-Crop-Yield-API / docs /API_DOCUMENTATION.md
AshrafGalibSk's picture
Upload folder using huggingface_hub
bbd5f9c verified
|
Raw
History Blame Contribute Delete
6.15 kB

🌾 Crop Yield Prediction API Documentation

Overview

FastAPI-based REST API for crop yield prediction using Random Forest model.

πŸš€ Quick Start

Local Development

# 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

# 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):

{
  "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:

{
  "model": "Random Forest",
  "predicted_yield": "2017.7 kg/hectare",
  "total_expected_production": "20.18 tons",
  "assessment": "Good yield expected"
}

Example cURL Request:

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:

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:

{
  "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:

{
  "status": "healthy",
  "timestamp": "2024-09-11T08:00:00.000000",
  "model_loaded": true
}

GET /available-options

Get available states, crops, and seasons.

Response:

{
  "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

{
  "detail": "Missing required field: crop"
}

500 Internal Server Error

{
  "detail": "Predictor not initialized. Please check if trained models are available."
}

πŸ”§ Testing Examples

Test Cases

1. Complete Input:

{
  "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):

{
  "year": 2024,
  "state": "Uttar Pradesh",
  "crop": "Wheat",
  "season": "Rabi",
  "area": 15.5,
  "production": 40.2
}

3. Different Crop:

{
  "year": 2024,
  "state": "Maharashtra",
  "crop": "Sugarcane",
  "season": "Kharif",
  "area": 20.0,
  "production": 80.0,
  "rainfall": 800
}

🐳 Docker Commands

# 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