Offer the machine learning model in less than 10 minutes via Rest APIS

by SkillAiNest

Offer the machine learning model in less than 10 minutes via Rest APIS
Photo by Author | Canva

If you like to create a machine learning model and experience with new things, it’s really good – but telling the truth, it is only useful to others when you make it available to them. For this, you need to serve it – expose it through the web API so that other programs (or humans) can send data and return the predictions. The rest of the APIs come in.

In this article, you will learn how we will go using a fast PI in API for production from a simple machine learning model, which is one of the fastest and most developed friendly web framework in less than 10 minutes. And we just won’t stop “drive it” on the demo, but we’ll add things like:

  • Verifying incoming data
  • Login each request
  • Adding background tasks to avoid slow behavior
  • The errors of dealing with grace

So, I quickly show you how our project structure is visible before going to the code section:

ml-api/
│
├── model/
│   └── train_model.py        # Script to train and save the model
│   └── iris_model.pkl        # Trained model file
│
├── app/
│   └── main.py               # FastAPI app
│   └── schema.py             # Input data schema using Pydantic
│
├── requirements.txt          # All dependencies
└── README.md                 # Optional documentation

Step 1: Install the item you need

We will need some packages for this project: Fastep for API, skate long for the model, and some helpers such as Jubilee and Padintic. You can install them using PIP:

pip install fastapi uvicorn scikit-learn joblib pydantic

And save your environment:

pip freeze > requirements.txt

Step 2: Train and save a simple model

Let’s keep the machine learning section easy so we can focus on the model service. We will use the famous Irus Datasit And train a Random forest rating Erus flower type prediction based on its petal and apple measurement.

Here is a training script. Create a file that says Train_model.p A Model/ Directory:

from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
import joblib, os

X, y = load_iris(return_X_y=True)
clf = RandomForestClassifier()
clf.fit(*train_test_split(X, y, test_size=0.2, random_state=42)(:2))

os.makedirs("model", exist_ok=True)
joblib.dump(clf, "model/iris_model.pkl")
print("✅ Model saved to model/iris_model.pkl")

This script loads, distributes it, trains the model, and saves it using the heart. Run once to produce the model file:

python model/train_model.py

Step 3: Explain what your API should expect input

Now we need to describe how the user will interact with your API. What should they send, and in what form?

We will use a built -in part of the fast PI, PART, to make a scheme, which describes and verifies incoming data. Specifically, we will make sure that consumers provide four positive float values ​​- for apple length/width and petal length/width.

In a new file App/Scheme.PAdd:

from pydantic import BaseModel, Field

class IrisInput(BaseModel):
    sepal_length: float = Field(..., gt=0, lt=10)
    sepal_width: float = Field(..., gt=0, lt=10)
    petal_length: float = Field(..., gt=0, lt=10)
    petal_width: float = Field(..., gt=0, lt=10)

Here, we have added value obstacles (more than 0 and less than 10) to keep our inputs clean and realistic.

Step 4: Make API

The time has come to build the original API. We will use Fastepi:

  • Load the model
  • Accept JSON input
  • Predict class and possibilities
  • Log in the request in the background
  • Clear JSON Return the answer

Let’s write the main API code inside App/main.p:

from fastapi import FastAPI, HTTPException, BackgroundTasks
from fastapi.responses import JSONResponse
from app.schema import IrisInput
import numpy as np, joblib, logging

# Load the model
model = joblib.load("model/iris_model.pkl")

# Set up logging
logging.basicConfig(filename="api.log", level=logging.INFO,
                    format="%(asctime)s - %(message)s")

# Create the FastAPI app
app = FastAPI()

@app.post("/predict")
def predict(input_data: IrisInput, background_tasks: BackgroundTasks):
    try:
        # Format the input as a NumPy array
        data = np.array(((input_data.sepal_length,
                          input_data.sepal_width,
                          input_data.petal_length,
                          input_data.petal_width)))
        
        # Run prediction
        pred = model.predict(data)(0)
        proba = model.predict_proba(data)(0)
        species = ("setosa", "versicolor", "virginica")(pred)

        # Log in the background so it doesn’t block response
        background_tasks.add_task(log_request, input_data, species)

        # Return prediction and probabilities
        return {
            "prediction": species,
            "class_index": int(pred),
            "probabilities": {
                "setosa": float(proba(0)),
                "versicolor": float(proba(1)),
                "virginica": float(proba(2))
            }
        }

    except Exception as e:
        logging.exception("Prediction failed")
        raise HTTPException(status_code=500, detail="Internal error")

# Background logging task
def log_request(data: IrisInput, prediction: str):
    logging.info(f"Input: {data.dict()} | Prediction: {prediction}")

Let’s stop and understand what’s going on here.

When the app starts, we load the model once. When someone kills a user /Forecast The closing point with the correct JSON input, we turn it into a moisture array, move it through the model, and return the predicted class and possibilities. If something goes wrong, we log it and return a friendly mistake.

Notice Background Tasks Part – This is a clean phostep feature that facilitates us to work after sending the answer (such as login savings). Which holds API accountable and avoids delay.

Step 5: Run your API

To launch the server, thus use Yukorin:

uvicorn app.main:app --reload

See: http://127.0.1:8000/docs
You will see an interactive swiger UI where you can test API.
Try this sample input:

{
  "sepal_length": 6.1,
  "sepal_width": 2.8,
  "petal_length": 4.7,
  "petal_width": 1.2
}

Or you can use curl to make the request like this:

curl -X POST " -H  "Content-Type: application/json" -d \
'{
  "sepal_length": 6.1,
  "sepal_width": 2.8,
  "petal_length": 4.7,
  "petal_width": 1.2
}'

They both produce the same reaction that is:

{"prediction":"versicolor",
 "class_index":1,
 "probabilities": {
	 "setosa":0.0,
	 "versicolor":1.0,
	 "virginica":0.0 }
 }

Optional Step: Deploy your API

You can deploy on the Fastep app:

  • Rader.com (Zero Configorous Deployment)
  • Railways. App (for continuous integration)
  • Heroco (through the Doker)

You can also expand your view, monitor applications with promotase and graphic, and use radius or celery for background job row, and also extend it to the product ready for production by adding verification (such as API keys or Oauth) to protect your perspective. You can also refer to my article: Step guide for deployment of machine learning model with the Doker.

Wrap

Just – and it’s already better than the demo. What we have made is more than just a toy example. However, it:

  • Automatically verifies the input data
  • Lifts meaningful reactions with the confidence of forecasting
  • Login each application on file (API.LOG)
  • Uses background tasks so API remains fast and responsible
  • Failures handle beautifully

And all this in 100 lines of code.

Kanwal seals Kanwal is a machine learning engineer and a technical writer who has a deep passion for data science and has AI intersection with medicine. He authored EBook with “Maximum Production Capacity with Chat GPT”. As a Google Generation Scholar 2022 for the APAC, the Champions Diversity and the Educational Virtue. He is also recognized as a tech scholar, Mitacs Global Research Scholar, and Harvard Vacod Scholar as a Taradata diversity. Kanwal is a passionate lawyer for change, who has laid the foundation of a Fame Code to empower women in stem fields.

You may also like

Leave a Comment

At Skillainest, we believe the future belongs to those who embrace AI, upgrade their skills, and stay ahead of the curve.

Get latest news

Subscribe my Newsletter for new blog posts, tips & new photos. Let's stay updated!

@2025 Skillainest.Designed and Developed by Pro