Transform your ML model to an API with FastAPI. Follow our step-by-step guide for a quick, easy, and powerful deployment.

Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
// Import the necessary libraries for model loading
import joblib
// Load the pre-trained model from the file system
model = joblib.load('saved\_model.pkl')
// Import FastAPI for creating the API
from fastapi import FastAPI
// Import pydantic for request body validation
from pydantic import BaseModel
// Create a FastAPI instance
app = FastAPI()
// Define the expected request body structure using a Pydantic model
class InputData(BaseModel):
// Example: a list of float numbers that the model requires as input
features: list[float]
// Define an endpoint to handle prediction requests
@app.post("/predict")
async def predict(data: InputData):
// Convert input features to the format needed by your model (e.g., list to numpy array)
sample = [data.features]
// Get the prediction from the loaded model
prediction = model.predict(sample)
// Return the prediction in a dictionary, which FastAPI automatically serializes to JSON
return {"prediction": prediction.tolist()}
// Running the server via command line
// uvicorn app:app --reload
// The --reload flag is useful for development as it restarts the server on code changes
// Example curl command to test the API
// curl -X POST "http://127.0.0.1:8000/predict" -H "Content-Type: application/json" -d '{"features": [5.1, 3.5, 1.4, 0.2]}'
// Example of exception handling in the prediction endpoint
@app.post("/predict")
async def predict(data: InputData):
try:
sample = [data.features]
prediction = model.predict(sample)
except Exception as e:
// Return an error message with a proper HTTP status code
return {"error": str(e)}
return {"prediction": prediction.tolist()}
From startups to enterprises and everything in between, see for yourself our incredible impact.
Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We’ll discuss your project and provide a custom quote at no cost.Â