Lesson · 40 min · Free
Production APIs for AI: FastAPI & Flask
Production APIs for AI: FastAPI & Flask body { font-family: sans-serif; line-height: 1.6; margin: 20px; } h1, h2 { color: #2c3e50; } pre { background-color: #ecf0f1; padding: 15px; border-radius: 5px; overflow-x: auto; }
Production APIs for AI: FastAPI & Flask
In the rapidly evolving landscape of generative AI within pharmacy and biotech, the ability to deploy your models as accessible services is paramount. While you might develop sophisticated models for drug discovery, personalized medicine, or diagnostic support, their true impact is realized when they can be easily integrated into existing systems or consumed by other applications. This is where Application Programming Interfaces (APIs) come into play. An API acts as a bridge, allowing different software components to communicate with each other. For AI models, an API typically exposes an endpoint where you can send input data (e.g., patient genomics, chemical structures) and receive predictions or generated content back. Python, being the dominant language for AI development, offers several excellent frameworks for building these APIs. Among the most popular and robust are FastAPI and Flask. Both serve the purpose of creating web services, but they approach it with different philosophies and offer distinct advantages, making them suitable for various use cases in a biotech or pharmaceutical context. Understanding their strengths will help you choose the right tool for deploying your next AI-powered solution, whether it's a predictive model for drug efficacy or a generative model for novel compound design.
FastAPI vs. Flask: Choosing Your API Framework
Flask is a lightweight and flexible micro-framework. It provides the bare essentials for web development, allowing developers to choose their own tools and libraries for databases, authentication, and other features. This "do it yourself" approach makes Flask highly customizable and excellent for smaller projects or when you need fine-grained control over every component. For instance, if you're building a simple internal tool to predict protein-ligand binding affinity based on a small dataset, Flask's simplicity can be a significant advantage, allowing for quick prototyping and deployment. Its maturity means there's a vast community and numerous extensions available. FastAPI, on the other hand, is a modern, high-performance web framework designed specifically for building APIs. Its key selling points are its incredible speed (on par with Node.js and Go), automatic data validation, and documentation generation (using OpenAPI/Swagger UI). FastAPI leverages Python type hints, which not only improves code readability and maintainability but also allows it to perform automatic data serialization, validation, and error handling. For complex AI applications in biotech, such as a multi-modal generative model requiring strict input validation for patient data or a high-throughput drug screening prediction service, FastAPI's built-in features for robustness and performance can significantly reduce development time and improve reliability.
Flask Example: Simple Prediction API
Here's a basic example of a Flask API that might expose a simple AI model (represented here by a placeholder function) to predict a drug's solubility based on some input features. from flask import Flask, request, jsonify app = Flask(__name__) # Placeholder for your actual AI model def predict_solubility(features): """ A dummy function representing an AI model predicting drug solubility. In a real application, this would load and use your trained model. """ # Example: Simple linear model for demonstration molecular_weight = features.get('molecular_weight', 0) logP = features.get('logP', 0) h_bond_donors = features.get('h_bond_donors', 0) # A very simplistic "prediction" solubility_score = (molecular_weight * -0.01) + (logP * -0.5) + (h_bond_donors * 0.2) + 10 return max(0, min(100, solubility_score)) # Scale to 0-100 @app.route('/predict_solubility', methods=['POST']) def predict(): data = request.json if not data or not all(k in data for k in ['molecular_weight', 'logP', 'h_bond_donors']): return jsonify({"error": "Missing required molecular features"}), 400 try: prediction = predict_solubility(data) return jsonify({"predicted_solubility_score": prediction}) except Exception as e: return jsonify({"error": str(e)}), 500 if __name__ == '__main__': app.run(debug=True) To run this Flask application, save it as a .py file (e.g., app.py ), install Flask ( pip install Flask ), and then execute python app.py in your terminal. You can then send POST requests to http://127.0.0.1:5000/predict_solubility with JSON data like {"molecular_weight": 250, "logP": 2.5, "h_bond_donors": 3} .
FastAPI Example: Drug Interaction Prediction API
This FastAPI example demonstrates how to create an API endpoint for predicting potential drug-drug interactions, leveraging type hints for automatic validation and documentation. from fastapi import FastAPI, HTTPException from pydantic import BaseModel from typing import List, Dict app = FastAPI() # Define input data structure using Pydantic class DrugInteractionRequest(BaseModel): drug_a_id: str drug_b_id: str patient_age: int patient_conditions: List[str] = [] # Optional list of conditions # Placeholder for your actual AI model def get_drug_interaction_risk(drug_a_id: str, drug_b_id: str, age: int, conditions: List[str]) -> Dict: """ A dummy function representing an AI model predicting drug interaction risk. In a real application, this would load and use your trained model. """ risk_factors = 0 if "cardiac disease" in conditions: risk_factors += 2 if age > 65: risk_factors += 1 # Simple logic for demonstration if drug_a_id == "warfarin" and drug_b_id == "aspirin": risk_level = "High" if risk_factors > 1 else "Moderate" description = "Increased bleeding risk." elif drug_a_id == "metformin" and drug_b_id == "insulin": risk_level = "Moderate" description = "Increased hypoglycemia risk." else: risk_level = "Low" description = "No significant interaction predicted." return { "drug_a": drug_a_id, "drug_b": drug_b_id, "risk_level": risk_level, "description": description, "confidence_score": 0.85 # Placeholder for model confidence } @app.post("/predict_drug_interaction") async def predict_interaction(request: DrugInteractionRequest): try: interaction_result = get_drug_interaction_risk( request.drug_a_id, request.drug_b_id, request.patient_age, request.patient_conditions ) return interaction_result except Exception as e: raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}") if __name__ == '__main__': import uvicorn uvicorn.run(app, host="0.0.0.0", port=8000) To run this FastAPI application, save it as a .py file (e.g., main.py ), install FastAPI and Uvicorn ( pip install fastapi uvicorn[standard] ), and then execute uvicorn main:app --reload in your terminal. You can then access the interactive API documentation at http://127.0.0.1:8000/docs and send POST requests to http://127.0.0.1:8000/predict_drug_interaction .
Key Takeaways
APIs are essential for making AI models accessible and integrable into larger systems, crucial for real-world application in pharmacy/biotech. Flask is a lightweight, flexible micro-framework ideal for smaller projects or when extensive customization is needed. FastAPI is a modern, high-performance framework optimized for building APIs, offering automatic data validation, serialization, and documentation through Python type hints and Pydantic. FastAPI is generally preferred for its speed, built-in validation, and automatic documentation, especially for production-grade AI services requiring robust input handling. Both frameworks allow you to serve your trained AI models (e.g., scikit-learn, TensorFlow, PyTorch models) by loading them within the application and using them to process incoming requests.
Practice Exercise
Imagine you've developed a generative AI model that can suggest novel chemical compounds based on desired pharmacological properties (e.g., high specificity for a target receptor, low toxicity). Your task is to design an API endpoint for this model. Choose either Flask or FastAPI. Justify your choice based on the features discussed. Define the input parameters your API would need (e.g., target receptor ID, desired property ranges). Define the output structure your API would return (e.g., a list of SMILES strings for suggested compounds, predicted properties, confidence scores). Write a conceptual (or actual, if you're feeling ambitious!) code snippet demonstrating how you would set up this API endpoint, including the request and response models (for FastAPI) or data handling (for Flask). You don't need to implement the actual generative model logic, just the API structure.
Watch the full lesson — free
This topic is part of Build & Ship Generative AI Applications, a complete AI-narrated video course. Press play once and watch the entire lecture like a movie.
Start the course free →