Machine learning models are powerful, but they become truly useful when deployed as APIs that real applications can use. FastAPI is one of the fastest and easiest ways to turn your trained ML model into a production ready API. In this blog, we will break down how a user sends data, how FastAPI processes it, and how the ML model finally makes a prediction.
What We Are Building
We are creating a diabetes prediction API. A client sends medical values such as Glucose, BMI, Age and more. FastAPI receives the data, validates it, converts it into a usable format, and passes it to a trained machine learning model.
The model returns
0 for Not Diabetic
1 for Diabetic
FastAPI then sends back a readable message to the user.
Understanding the Data Flow
FastAPI processes data in a very specific order.
- User sends JSON
All web APIs communicate using JSON.
Example:
{
“Pregnancies”: 6,
“Glucose”: 148,
“BloodPressure”: 72,
“BMI”: 33.6,
“Age”: 50
}
- FastAPI converts JSON → Pydantic Model
You create a Pydantic class:
class model_input(BaseModel):
Pregnancies: int
Glucose: int
BloodPressure: int
BMI: float
Age: int
This validates the input, ensures correct types, and blocks wrong data.
- Pydantic → Python Dictionary
Inside your endpoint:
input_dict = input_parametes.dict()
Now the data becomes a normal Python dict you can work with.
- Dictionary → List
Your ML model expects a list:
input_list = [
input_dict[‘Pregnancies’],
input_dict[‘Glucose’],
input_dict[‘BloodPressure’],
input_dict[‘BMI’],
input_dict[‘Age’]
]
- List → Machine Learning Model
Finally:
prediction = model.predict([input_list])
FastAPI returns the model output as text.
FastAPI Endpoint Explained
Your full endpoint looks like this:
@app.post(‘/diabetes_prediction’)
def diabetes_pred(input_parametes: model_input):
input_dict = input_parametes.dict()
input_list = [
input_dict['Pregnancies'],
input_dict['Glucose'],
input_dict['BloodPressure'],
input_dict['SkinThickness'],
input_dict['Insulin'],
input_dict['BMI'],
input_dict['DiabetesPedigreeFunction'],
input_dict['Age']
]
prediction = diabetes_model.predict([input_list])
if prediction[0] == 0:
return 'The person is not Diabetic'
else:
return 'The person is Diabetic'
Every part is simple and readable.
Testing the API Using Python
You can test the API using a simple script:
import json
import requests
url = “http://127.0.0.1:8000/diabetes_prediction”
input_data = {
“Pregnancies”: 6,
“Glucose”: 148,
“BloodPressure”: 72,
“SkinThickness”: 35,
“Insulin”: 0,
“BMI”: 33.6,
“DiabetesPedigreeFunction”: 0.627,
“Age”: 50
}
response = requests.post(url, data=json.dumps(input_data))
print(response.text)
When you run this script, the FastAPI server responds with a prediction.
We saw how FastAPI receives JSON input, validates it using Pydantic, transforms it into a list, and sends it into a machine learning model. This complete pipeline is essential for converting local ML models into real world APIs.