title: Can we use Pydantic models (Basemodel) directly inside model.predict() using FastAPI, and if not ,why?
body: <p>I'm using Pydantic model (<code>Basemodel</code>) with FastAPI and converting the input into a <code>dictionary</code>, and then converting it into a Pandas <code>DataFrame</code> to assign it into <code>model.predict()</code> function for Machine Learning prediction, as shown below :</p>
  <pre class="lang-py prettyprint-override"><code>from fastapi import FastAPI
  import uvicorn
  from pydantic import BaseModel
  import pandas as pd
  from typing import List
  
  class Inputs(BaseModel):
      f1: float,
      f2: float,
      f3: str
  
  @app.post('/predict')
  def predict(features: List[Inputs]):
      output = []
  
      # loop the list of input features
      for data in features:
           result = {}
  
           # Convert data into dict() and then into a DataFrame
              data = data.dict()
              df = pd.DataFrame([data])
  
           # get predictions
              prediction = classifier.predict(df)[0]
  
           # get probability
              probability = classifier.predict_proba(df).max()
  
           # assign to dictionary 
              result[&quot;prediction&quot;] = prediction
              result[&quot;probability&quot;] = probability
  
           # append dictionary to list (many outputs)
              output.append(result)
  
      return output
  </code></pre>
  <p>It works fine, I'm just not quite sure if it's <strong>optimized</strong> or the right way to do it, since I convert the input two times to get the predictions. Also, I'm not sure if it is going to work <strong>fast</strong> in the case of having a <strong>huge number</strong> of inputs. Any improvements for this? If there's a way (even other than using Pydantic models, where I can work directly and avoid going through conversions and the loop.</p>