Spaces:
Sleeping
Sleeping
πΎ 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
- Content-Type: Always use
application/json - HTTP Method: Use
POSTfor predictions - Required Fields: year, state, crop, season, area, production
- Optional Fields: rainfall, fertilizer, pesticide (have sensible defaults)
- Response Format: Always returns JSON with units included in values
- Error Handling: Check HTTP status codes and
detailfield in errors
π Production Deployment
For production deployment, consider:
- Environment Variables: Configure port, host via env vars
- Load Balancing: Use nginx or similar for multiple instances
- Monitoring: Add logging and metrics collection
- Security: Add authentication if needed
- CORS: Configure CORS for web applications
π Troubleshooting
Model Not Loading:
- Ensure
trained_models/directory exists with model files - Check
preprocessor.pklandrandom_forest_model.pklare 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