DEV Community

Cover image for Building A Simple API For Your ML Model With FastAPI
Khalil Habib Shariff
Khalil Habib Shariff

Posted on • Edited on

Building A Simple API For Your ML Model With FastAPI

Machine learning models are powerful tools, but their impact is often confined to notebooks and research environments. To realize their full potential, we need to integrate them into real-world applications. FastAPI offers a streamlined and efficient way to create APIs that bridge this gap, making your models accessible to diverse use cases.
In this post, I will guide you through the process of building a simple API for a plant disease classification model using FastAPI.

KEY STEPS

  1. Install FastAPI and Dependencies:
pip install fastapi uvicorn[standard] tensorflow numpy pillow
Enter fullscreen mode Exit fullscreen mode

2.Create Your FastAPI App:

from fastapi import FastAPI, File, UploadFile, BackgroundTasks
# ... other imports

app = FastAPI()
Enter fullscreen mode Exit fullscreen mode

3.Load Your Trained Model:

model = keras.models.load_model('./models/model.weights.best.hdf5')

Enter fullscreen mode Exit fullscreen mode

4.Define Prediction Function:

async def predict_leaf_class(image: UploadFile):
    # ... image preprocessing and prediction logic
    return predicted_class

Enter fullscreen mode Exit fullscreen mode

5.Create API Endpoint:

@app.post("/predict")
async def predict_leaf_disease(image: UploadFile = File(...)):
    predicted_class = await predict_leaf_class(image)
    return JSONResponse(content={"predicted_class": predicted_class})

Enter fullscreen mode Exit fullscreen mode

6.Enable CORS (Optional):

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Adjust for production
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

Enter fullscreen mode Exit fullscreen mode

7.Run The API

uvicorn main:app --reload

Enter fullscreen mode Exit fullscreen mode

You can find the complete code in this repo [https://github.com/Khaleelhabeeb/Fastapi-ML-Model-API]

Conclusion
FastAPI simplifies the process of creating robust and scalable APIs for machine learning models. By following these steps, you can effectively share your models with other applications and users, enabling a wider range of practical applications.
visit [https://github.com/Khaleelhabeeb/Fastapi-ML-Model-API]

Top comments (0)