File size: 8,943 Bytes
bbd5f9c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
# ๐ŸŒพ 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