Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Build API using FastAPI for Classification Model produced using pycaret

I'm using pycaret as my ML workflow, I tried to create an API using FastAPI. This is my first time playing into production level, so I'm bit confused about API

I have 10 features; age: float, live_province: str, live_city: str, live_area_big: str, live_area_small: str, sex: float, marital: float, bank: str, salary: float, amount: float and a label which it contains the binary value (0 and 1).

This is what my script for building the API

from pydantic import BaseModel
import numpy as np
from pycaret.classification import *

import uvicorn
from fastapi import FastAPI

app = FastAPI()

model = load_model('catboost_cm_creditable')

class Data(BaseModel):
    age: float
    live_province: str
    live_city: str
    live_area_big: str
    live_area_small: str
    sex: float
    marital: float
    bank: str
    salary: float
    amount: float

input_dict = Data

@app.post("/predict")
def predict(model, input_dict):
    predictions_df = predict_model(estimator=model, data=input_dict)
    predictions = predictions_df['Score'][0]
    return predictions

When I tried to run uvicorn script:app and went to the documentation I can't find the parameter for my features, the parameters only show model and input_dict enter image description here

How to take my Features onto Parameters in the API?

like image 858
ebuzz168 Avatar asked Oct 27 '25 07:10

ebuzz168


1 Answers

You need to Type-hint your Pydantic model to make it work with your FastAPI

Imagine like you are really working with Standard Python, when you need to documentate that function,

def some_function(price: int) ->int:
    return price

With Pydantic there is nothing different than the example above

Your class Data is actually a python @dataclass with super-powers(comes from Pydantic)

from fastapi import Depends

class Data(BaseModel):
    age: float
    live_province: str
    live_city: str
    live_area_big: str
    live_area_small: str
    sex: float
    marital: float
    bank: str
    salary: float
    amount: float


@app.post("/predict")
def predict(data: Data = Depends()):
    predictions_df = predict_model(estimator=model, data=data)
    predictions = predictions_df["Score"][0]
    return predictions

There is a one little trick, with Depends, you 'll get a single queries like when you are defining each field seperately.

With Depends

enter image description here

Without Depends

enter image description here

like image 134
Yagiz Degirmenci Avatar answered Oct 28 '25 22:10

Yagiz Degirmenci



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!