Spaces:
Sleeping
Sleeping
๐พ Crop Yield Prediction API - Endpoints Documentation
Base URL
- Local:
http://localhost:8000 - Railway Production:
https://sih-2-production.up.railway.app/
Authentication
No authentication required for any endpoints.
๐ API Endpoints Overview
| Endpoint | Method | Purpose | Input Required |
|---|---|---|---|
/ |
GET | API Information | None |
/health |
GET | Health Check | None |
/predict |
POST | Crop Yield Prediction | JSON Body |
/available-options |
GET | Available Options | None |
/docs |
GET | Interactive API Documentation | None |
1. ๐ Root Endpoint
GET /
Purpose: Get basic API information and available endpoints.
Input
- Method: GET
- Headers: None required
- Body: None
Output
{
"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"
}
}
cURL Example
curl -X GET https://sih-2-production.up.railway.app/
2. ๐ฅ Health Check Endpoint
GET /health
Purpose: Check API health status and model loading status.
Input
- Method: GET
- Headers: None required
- Body: None
Output
{
"status": "healthy",
"timestamp": "2024-09-12T12:35:47.123456",
"model_loaded": true
}
Field Descriptions
status: Always "healthy" when API is runningtimestamp: Current server time in ISO formatmodel_loaded: Boolean indicating if prediction models are loaded
cURL Example
curl -X GET https://sih-2-production.up.railway.app/health
3. ๐ฎ Prediction Endpoint (Main Feature)
POST /predict
Purpose: Predict crop yield based on agricultural parameters.
Input
- Method: POST
- Content-Type:
application/json - Headers:
Content-Type: application/json
Request Body Schema
{
"year": integer, // REQUIRED: Crop year (e.g., 2024)
"state": "string", // REQUIRED: State name (e.g., "Punjab")
"crop": "string", // REQUIRED: Crop name (e.g., "Rice")
"season": "string", // REQUIRED: Season (e.g., "Kharif")
"area": float, // REQUIRED: Area in hectares (e.g., 10.0)
"production": float, // REQUIRED: Previous production in tons (e.g., 25.0)
"rainfall": float, // OPTIONAL: Annual rainfall in mm (default: 1000.0)
"fertilizer": float, // OPTIONAL: Fertilizer usage in kg (default: 50.0)
"pesticide": float // OPTIONAL: Pesticide usage in kg (default: 5.0)
}
Field Validation
year: Integer, typically 2020-2030state: String, any Indian state namecrop: String, major crops like "Rice", "Wheat", "Cotton", etc.season: String, options: "Kharif", "Rabi", "Summer", "Whole Year", etc.area: Positive float, hectaresproduction: Positive float, tonsrainfall: Positive float, millimeters (optional)fertilizer: Positive float, kilograms (optional)pesticide: Positive float, kilograms (optional)
Output (Success - 200)
{
"model": "Random Forest", // Or "Fallback Model (Rule-based)"
"predicted_yield": "2845.67 kg/hectare", // Predicted yield with units
"total_expected_production": "28.46 tons", // Total production estimate
"assessment": "Good yield expected" // Qualitative assessment
}
Output Field Descriptions
model: Model type used ("Random Forest" for ML, "Fallback Model (Rule-based)" for rule-based)predicted_yield: Predicted yield per hectare in kg/hectare formattotal_expected_production: Total expected production in tons (yield ร area รท 1000)assessment: Qualitative assessment based on yield:"Excellent yield expected": > 3000 kg/hectare"Good yield expected": 2000-3000 kg/hectare"Moderate yield expected": 1000-2000 kg/hectare"Low yield expected": < 1000 kg/hectare
Output (Error - 400/500)
{
"detail": "Error message describing what went wrong"
}
Complete cURL Example
curl -X POST https://sih-2-production.up.railway.app/predict \
-H "Content-Type: application/json" \
-d '{
"year": 2024,
"state": "Punjab",
"crop": "Rice",
"season": "Kharif",
"area": 15.5,
"production": 35.0,
"rainfall": 1250,
"fertilizer": 80,
"pesticide": 10
}'
Python Example
import requests
url = "https://sih-2-production.up.railway.app/predict"
data = {
"year": 2024,
"state": "Maharashtra",
"crop": "Cotton",
"season": "Kharif",
"area": 20.0,
"production": 15.0,
"rainfall": 900,
"fertilizer": 60,
"pesticide": 12
}
response = requests.post(url, json=data)
print(response.json())
4. ๐ Available Options Endpoint
GET /available-options
Purpose: Get available values for crops, states, and seasons.
Input
- Method: GET
- Headers: None required
- Body: None
Output
{
"states": [
"Punjab", "Maharashtra", "Karnataka", "Gujarat", "Rajasthan"
],
"crops": [
"Rice", "Wheat", "Cotton", "Sugarcane", "Maize"
],
"seasons": [
"Kharif", "Rabi", "Summer", "Whole Year", "Autumn", "Winter", "Total"
],
"note": "This shows first 10 states and crops. All are supported in predictions."
}
cURL Example
curl -X GET https://sih-2-production.up.railway.app/available-options
5. ๐ Interactive Documentation
GET /docs
Purpose: Access Swagger/OpenAPI interactive documentation.
Input
- Method: GET (open in browser)
- URL:
https://sih-2-production.up.railway.app/docs
Output
Interactive web interface with:
- All endpoint documentation
- Try-it-out functionality
- Request/response examples
- Schema validation
๐ Complete Usage Examples
JavaScript/Node.js
const axios = require('axios');
async function predictYield() {
try {
const response = await axios.post('https://sih-2-production.up.railway.app/predict', {
year: 2024,
state: 'Karnataka',
crop: 'Rice',
season: 'Kharif',
area: 25.0,
production: 60.0,
rainfall: 1100,
fertilizer: 70,
pesticide: 8
});
console.log('Prediction:', response.data);
} catch (error) {
console.error('Error:', error.response.data);
}
}
predictYield();
PHP
<?php
$url = 'https://sih-2-production.up.railway.app/predict';
$data = array(
'year' => 2024,
'state' => 'Punjab',
'crop' => 'Wheat',
'season' => 'Rabi',
'area' => 12.5,
'production' => 30.0,
'rainfall' => 800,
'fertilizer' => 85,
'pesticide' => 6
);
$options = array(
'http' => array(
'header' => "Content-Type: application/json\r\n",
'method' => 'POST',
'content' => json_encode($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
$response = json_decode($result, true);
echo json_encode($response, JSON_PRETTY_PRINT);
?>
โ ๏ธ Error Handling
Common Error Responses
400 Bad Request
{
"detail": "Validation error: field 'area' must be positive"
}
500 Internal Server Error
{
"detail": "Prediction failed: Model initialization error"
}
Error Scenarios
- Missing required fields: Returns 422 with field validation errors
- Invalid data types: Returns 422 with type validation errors
- Negative values: Returns 400 with validation error
- Model loading failure: Returns 500 but API continues with fallback
- Server errors: Returns 500 with error description
๐ Response Time & Performance
- Health Check: ~10-50ms
- Prediction (Fallback Mode): ~50-200ms
- Prediction (ML Mode): ~100-500ms
- Available Options: ~20-100ms
๐ Rate Limiting
Currently no rate limiting is implemented. For production use, consider:
- Maximum 100 requests per minute per IP
- Maximum 1000 requests per hour per IP
๐ฏ Model Information
Random Forest Mode (When Available)
- Algorithm: Random Forest Regression
- Features: 15+ agricultural and environmental features
- Training Data: Historical crop yield data across Indian states
- Accuracy: Varies by crop and region
Fallback Mode (Always Available)
- Algorithm: Rule-based prediction system
- Method: Crop-specific base yields adjusted by rainfall factor
- Base Yields:
- Rice: 2500 kg/hectare
- Wheat: 3000 kg/hectare
- Cotton: 1200 kg/hectare
- Sugarcane: 60000 kg/hectare
- Maize: 2800 kg/hectare
- Reliability: Provides reasonable estimates when ML models unavailable