SIH-Crop-Yield-API / API_ENDPOINTS_DOCUMENTATION.md
AshrafGalibSk's picture
Upload folder using huggingface_hub
bbd5f9c verified
|
Raw
History Blame Contribute Delete
8.94 kB
# ๐ŸŒพ 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
```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"
}
}
```
#### cURL Example
```bash
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
```json
{
"status": "healthy",
"timestamp": "2024-09-12T12:35:47.123456",
"model_loaded": true
}
```
#### Field Descriptions
- `status`: Always "healthy" when API is running
- `timestamp`: Current server time in ISO format
- `model_loaded`: Boolean indicating if prediction models are loaded
#### cURL Example
```bash
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
```json
{
"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-2030
- `state`: String, any Indian state name
- `crop`: String, major crops like "Rice", "Wheat", "Cotton", etc.
- `season`: String, options: "Kharif", "Rabi", "Summer", "Whole Year", etc.
- `area`: Positive float, hectares
- `production`: Positive float, tons
- `rainfall`: Positive float, millimeters (optional)
- `fertilizer`: Positive float, kilograms (optional)
- `pesticide`: Positive float, kilograms (optional)
#### Output (Success - 200)
```json
{
"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 format
- `total_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)
```json
{
"detail": "Error message describing what went wrong"
}
```
#### Complete cURL Example
```bash
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
```python
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
```json
{
"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
```bash
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
```javascript
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
<?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
```json
{
"detail": "Validation error: field 'area' must be positive"
}
```
#### 500 Internal Server Error
```json
{
"detail": "Prediction failed: Model initialization error"
}
```
### Error Scenarios
1. **Missing required fields**: Returns 422 with field validation errors
2. **Invalid data types**: Returns 422 with type validation errors
3. **Negative values**: Returns 400 with validation error
4. **Model loading failure**: Returns 500 but API continues with fallback
5. **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