Khalil Habib Shariff
Posted on December 23, 2023
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
- Install FastAPI and Dependencies:
pip install fastapi uvicorn[standard] tensorflow numpy pillow
2.Create Your FastAPI App:
from fastapi import FastAPI, File, UploadFile, BackgroundTasks
# ... other imports
app = FastAPI()
3.Load Your Trained Model:
model = keras.models.load_model('./models/model.weights.best.hdf5')
4.Define Prediction Function:
async def predict_leaf_class(image: UploadFile):
# ... image preprocessing and prediction logic
return predicted_class
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})
6.Enable CORS (Optional):
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Adjust for production
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
7.Run The API
uvicorn main:app --reload
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]
Posted on December 23, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.