Machine Learning API: Crop recommendation and yield prediction
A recommendation that cannot be explained is hard to trust, and hard to verify. The FildraAI ML API returns predictions from validated agronomic models with transparent reasoning traces, so agronomists can review the logic, and developers can build products that explain recommendations rather than just delivering them.
What is the Machine Learning API?
The Machine Learning API gives you direct access to the prediction models that power FildraAI's agronomic intelligence. Rather than going through a conversational interface, you can call these models programmatically, submitting structured farm data and receiving structured predictions in return.
All endpoints support both a basic (result-only) mode and a with-trace mode that returns a step-by-step explanation of the model's reasoning. The trace is designed to help agronomists and extension officers verify model outputs and explain recommendations to farmers in their own words.
Transparent predictions
Every endpoint returns 200 when the request includes the full required feature set. The most common 400 is an underspecified yield request: yield needs fertilizer rates plus soil composition values, not just rainfall and temperature.
Authentication
All Machine Learning API endpoints require a valid API key. The current production policy accepts both user keys and server keys for these routes when the key has machine_learning:predict.
X-Api-Key: YOUR_API_KEY
# Bearer style is also accepted
Authorization: Bearer YOUR_API_KEY
Your key must have the machine_learning API enabled and carry the machine_learning:predict scope. ML inference endpoints are billed 1 credit per call. Locale can be passed in the request body, as a query parameter, or via the Accept-Language header. The request body takes precedence.
Endpoints
POST /api/v1/ml/crop/basic
Returns a crop recommendation based on soil and climate features. Result only, no reasoning trace.
POST /api/v1/ml/crop/with_trace
Crop recommendation with a full reasoning trace. Includes the feature importances and decision path the model used to reach its recommendation.
POST /api/v1/ml/yield/basic
Yield prediction given fertilizer rates and soil composition. Returns predicted yield metrics. Result only.
POST /api/v1/ml/yield/with_trace
Yield prediction with reasoning trace and optional constraints such as target_yield and budget.
POST /api/v1/ml/snapshot
Combined endpoint. Runs crop recommendation, yield analysis, or both in a single call. Useful for generating a complete farm intelligence snapshot with minimal round-trips.
Crop recommendation
The crop recommendation endpoints accept a features object describing the farm's soil and climate conditions. The country field narrows predictions to region-appropriate crops.
Required fields
features(object):N,P,K(soil nutrient levels),temperature(°C),humidity(%),ph(0 to 14), andrainfall(mm)
Optional fields
country(string), ISO country code to localise recommendationslocale(string), Response language locale key
Example request
curl -X POST "https://api.fildraai.com/api/v1/ml/crop/with_trace" \
-H "X-Api-Key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"features": {
"N": 90,
"P": 42,
"K": 43,
"temperature": 26.5,
"humidity": 80.0,
"ph": 6.4,
"rainfall": 180.0
},
"country": "zambia",
"locale": "en-us"
}'
Example response
The recommendation is nested under prediction: recommended_crop, a confidence score from 0 to 1, and the top_3_crops ranked alternatives. inputs echoes what you sent. The with_trace variant adds a trace object (see Reasoning traces below). Crop names and scores are model output and will vary with your inputs.
{
"model_task": "crop",
"locale": "en-us",
"inputs": {
"features": { "N": 90, "P": 42, "K": 43, "temperature": 26.5, "humidity": 80.0, "ph": 6.4, "rainfall": 180.0 }
},
"prediction": {
"recommended_crop": "rice",
"confidence": 0.86,
"top_3_crops": [
{ "crop": "rice", "confidence": 0.86 },
{ "crop": "maize", "confidence": 0.07 },
{ "crop": "banana", "confidence": 0.03 }
]
}
}
Yield analysis
Yield analysis endpoints accept fertilizer application data and soil/climate conditions. Production requires meaningful fertilizer values and soil composition fields. A payload with only rainfall, temperature, and soil type is rejected with 400 Bad Request.
Required fields (basic)
fertilizer(object), Fertilizer application datasoil_climate(object), Rainfall, temperature, phosphorus, potassium, sand, organic carbon, and pH values
Optional fields (with_trace only)
target_yield, Desired yield target for optimisationbudget, Budget constraint for input optimisationcountry(string), Region contextlocale(string), Response language
Example yield request
curl -X POST "https://api.fildraai.com/api/v1/ml/yield/basic" \
-H "X-Api-Key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"fertilizer": {
"nitrogen": 120,
"phosphorus": 60,
"potassium": 40
},
"soil_climate": {
"rainfall": 850,
"temperature": 24,
"phosphorus": 18,
"potassium": 145,
"sand": 35,
"organic_carbon": 1.9,
"ph": 6.3
},
"country": "zambia",
"locale": "en-us"
}'
Example response
The forecast is under prediction.predicted_yield_kg_ha (kg per hectare). metrics describes the model's accuracy on its validation set (not your specific request), and input echoes the normalised values the model used. The predicted value depends on your inputs.
{
"model_task": "yield",
"locale": "en-us",
"prediction": {
"predicted_yield_kg_ha": 489.38,
"model_name": "xgboost",
"metrics": { "r2": 0.66, "rmse": 1097.85, "mae": 776.17, "mape": 31.53 },
"input": {
"fertilizer": { "N": 120, "P": 60, "K": 40 },
"soil_climate": {
"rainfall": 850, "mean_temperature": 24, "extractable_phosphorous": 18,
"total_potassium": 145, "sand_content": 35, "soil_organic_carbon": 1.9, "pH": 6.3
}
}
}
}
Combined ML snapshot
POST /api/v1/ml/snapshot runs multiple models in a single call. All input objects are optional, you can run crop recommendation only, yield analysis only, or both together. This minimises round-trips when building a comprehensive farm intelligence view.
Example snapshot request
curl -X POST "https://api.fildraai.com/api/v1/ml/snapshot" \
-H "X-Api-Key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"crop_features": {
"N": 90,
"P": 42,
"K": 43,
"temperature": 26.5,
"humidity": 80.0,
"ph": 6.4,
"rainfall": 180.0
},
"fertilizer": {
"nitrogen": 120,
"phosphorus": 60,
"potassium": 40
},
"soil_climate": {
"rainfall": 850,
"temperature": 24,
"phosphorus": 18,
"potassium": 145,
"sand": 35,
"organic_carbon": 1.9,
"ph": 6.3
},
"include_traces": true,
"country": "zambia",
"locale": "en-us"
}'
Example response
Each model you requested appears under modules.<name>.result with the same shape it returns on its own endpoint. With include_traces: true, each result also carries its trace.
{
"locale": "en-us",
"timestamp": "2026-06-19T07:00:00+00:00",
"extra_context": {},
"modules": {
"crop": {
"result": {
"model_task": "crop",
"prediction": { "recommended_crop": "rice", "confidence": 0.86, "top_3_crops": [ /* ... */ ] }
}
},
"yield": {
"result": {
"model_task": "yield",
"prediction": { "predicted_yield_kg_ha": 489.38, "model_name": "xgboost", "metrics": { /* ... */ } }
}
}
}
}
Reasoning traces
The with_trace variants and the include_traces: true snapshot option return a structured explanation of the model's reasoning alongside the prediction. This includes:
Feature importance
Which input features (e.g. soil pH, nitrogen level, rainfall) most strongly influenced the prediction, expressed as relative weights.
Decision path
The step-by-step path through the model's decision logic, showing which thresholds or rules were applied to reach the final output.
Confidence score
A confidence score from 0 to 1 for the top prediction, indicating how strongly the model's training supports this recommendation for the given inputs. Treat a lower score as a prompt for local expert review, not a hard rule.
Alternatives
Runner-up recommendations with their scores, helping agronomists consider fallback options if the primary recommendation is not feasible.
How to use traces
Traces are designed for agronomist review and farmer communication, not for raw display to end users. Use the feature importance data to explain to a farmer why a particular crop was recommended given their soil conditions. If the top feature is rainfall and the farmer has irrigation, the recommendation may need to be reconsidered locally.
Error codes
The Machine Learning API maps service errors to standard HTTP status codes:
Client errors (4xx)
400, Invalid or missing input object (e.g. missingfeatures, invalid field type)401, Missing or invalid API key403, Key lacks the required scope429, Rate limit exceeded
Server errors (5xx)
500, Model inference failed (internal error)503, ML service temporarily unavailable; retry with backoff504, Inference timeout; the model took longer than the allowed window