FastAPI endpoint — accept .pkl file upload
The FastAPI route that receives the .pkl file + form fields. Uses UploadFile = File() + Form().
The 8 steps of a benchmark endpoint: (1) Validate file extension — defend against non-.pkl uploads. (2) await model_file.read() — streams the file as bytes. Async, doesn't load all at once. (3) pickle.loads(bytes) — deserialize. NOTE: loads (from bytes), not load (from file). (4) Duck-type check — hasattr(model, 'predict'). Rejects non-model files. (5) Load dataset — could be from CSV, DB, or generated. Here we generate fake data. (6) Time the prediction — perf_counter before/after. (7) Compute metrics — MAE, R² (add more as needed). (8) Return JSONResponse — the benchmark result. Form(...) reads from form-encoded body. File(...) reads from multipart upload. Both are required by the HTML form's enctype='multipart/form-data'.
-
Change the validation to also accept .joblib files→ model_file.filename.endswith(('.pkl', '.joblib')) -
Add a try/except around model.predict()→ catches models that crash on the dataset -
Add cross-validation (5-fold) before returning→ more honest metrics -
Change the response to include a 'model_size_bytes' field→ len(file_bytes)