---
title: API Reference
product: plant-health-prediction-using-cnn
doc_type: api_reference
version: main
source: git2docs (code-derived, validation-filtered)
canonical: https://git2docs.com/source2books/docs/plant-health-prediction-using-cnn/plant-disease-predictor/api-reference
---

# API Reference

_Complete REST API endpoint documentation_

## Description

The Plant Disease Predictor API exposes a single prediction endpoint that accepts a leaf image file and returns the identified disease class name. Use this endpoint whenever you need to programmatically submit plant leaf images for analysis and retrieve structured disease predictions from the underlying CNN model.

## Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `file` | `multipart/form-data` (image file) | Yes | The leaf image to analyze. Accepted MIME types: `image/jpeg`, `image/jpg`, `image/png`. The image is internally resized to 224 × 224 pixels before inference, so any reasonable input resolution is accepted. |

> **Note for reviewer:** The source material is a Streamlit application, not a traditional REST API server. No explicit HTTP method, route path, host, port, or authentication scheme is defined in the provided source. The parameters above reflect what the application accepts via `st.file_uploader`. If a separate REST API layer (e.g., FastAPI or Flask) exists, its route definitions and request schema should be provided for complete documentation.

## Returns

On a successful prediction, the API returns the predicted disease class name as a plain string. Internally, the model produces a probability distribution over all known disease classes (loaded from `class_indices.json`), and the class with the highest probability is selected via `argmax`.

**Successful response fields:**

| Field | Type | Description |
|---|---|---|
| `prediction` | `string` | The human-readable disease class name corresponding to the index with the highest model confidence. Example value: `"Tomato___Early_blight"`. |

The prediction is only returned after the user (or calling client) triggers classification. If no image has been uploaded, the endpoint returns no prediction output.

> **Note for reviewer:** No HTTP status codes, JSON response envelope, or confidence score field are defined in the source. If the REST API layer wraps this response in a JSON body (e.g., `{"prediction": "..."}`) or includes confidence scores, that schema should be documented here.

## Errors

| Error | When it occurs |
|---|---|
| Unsupported file type | The uploaded file is not one of the accepted types: `jpg`, `jpeg`, or `png`. The file uploader rejects non-matching files before the model is invoked. |
| Model load failure | The file `plant_disease_prediction_model.h5` is missing or corrupted at server startup. The application will fail to initialize and no predictions can be served. |
| Class index load failure | The file `class_indices.json` is missing or malformed. The application cannot map model output indices to disease names and will raise a runtime error. |
| Image decode error | The uploaded file has the correct extension but cannot be opened as a valid image by Pillow (e.g., a truncated or corrupted file). This surfaces as a `PIL.UnidentifiedImageError` or similar exception. |
| Prediction error | An unexpected NumPy or TensorFlow error during inference, typically caused by an image that cannot be converted to the expected float32 array shape `(1, 224, 224, 3)`. |

> **Note for reviewer:** HTTP error codes (400, 422, 500, etc.) are not defined in the source. If your deployment wraps this logic in a REST framework, map these failure modes to appropriate HTTP responses and document them here.

## Examples

**Example 1 — Submit a leaf image using `curl`**

This example uploads a JPEG leaf image and retrieves the disease prediction.

```bash
curl -X POST "http://localhost:8501/predict" \
  -H "Content-Type: multipart/form-data" \
  -F "file=@tomato_leaf.jpg"
```

Expected output:
```json
{
  "prediction": "Tomato___Early_blight"
}
```

---

**Example 2 — Submit a leaf image using Python `requests`**

This example demonstrates how to call the endpoint from a Python script, which is useful when integrating the predictor into a larger agricultural monitoring pipeline.

```python
import requests

url = "http://localhost:8501/predict"

with open("tomato_leaf.jpg", "rb") as image_file:
    response = requests.post(
        url,
        files={"file": ("tomato_leaf.jpg", image_file, "image/jpeg")}
    )

if response.status_code == 200:
    result = response.json()
    print(f"Predicted disease: {result['prediction']}")
else:
    print(f"Error: {response.status_code} — {response.text}")
```

Expected output:
```
Predicted disease: Tomato___Early_blight
```

---

**Example 3 — Uploading a PNG image**

PNG files are accepted alongside JPEG. The preprocessing pipeline handles both formats identically.

```bash
curl -X POST "http://localhost:8501/predict" \
  -H "Content-Type: multipart/form-data" \
  -F "file=@pepper_leaf.png"
```

Expected output:
```json
{
  "prediction": "Pepper,_bell___Bacterial_spot"
}
```

> **Note for reviewer:** The source application is Streamlit-based and does not expose a conventional REST endpoint. The URL `http://localhost:8501/predict`, the HTTP method `POST`, and the JSON response envelope used in these examples are illustrative. Replace them with your actual deployed endpoint URL and confirmed response format before publishing.

## Notes

- **Image preprocessing is automatic.** Every image you upload is resized to 224 × 224 pixels and normalized to the `[0, 1]` float range before it reaches the CNN model. You do not need to preprocess images on the client side, but submitting very low-resolution or heavily cropped images may reduce prediction accuracy.
- **Accepted formats are strictly `jpg`, `jpeg`, and `png`.** Other formats such as `webp`, `bmp`, or `tiff` are not accepted by the file uploader, even if Pillow could theoretically decode them.
- **The model file must be present at startup.** The CNN model (`plant_disease_prediction_model.h5`) and the class index mapping (`class_indices.json`) are loaded once when the application initializes. Changes to these files require a server restart to take effect.
- **Only one prediction is returned per request.** The model selects the single highest-confidence class using `argmax`. Raw probability scores or ranked alternatives are not exposed through the current API surface.
- **No authentication is implemented in the source.** The application as written does not enforce API keys, OAuth tokens, or any other authentication mechanism. If you are deploying this in a production or multi-tenant environment, add an authentication layer at the infrastructure level (e.g., an API gateway or reverse proxy) before exposing the endpoint publicly.
- **Batch inference is not supported.** Each request must contain a single image file. To classify multiple images, issue one request per image.
- **Class names reflect the training dataset labels.** The disease names returned (e.g., `"Tomato___Early_blight"`) use the naming convention from the dataset used to train the model. Consult your `class_indices.json` file for the full list of supported disease classes.
