<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Akalanka Prabodani on Medium]]></title>
        <description><![CDATA[Stories by Akalanka Prabodani on Medium]]></description>
        <link>https://medium.com/@akalankaprabodani?source=rss-da031917fd58------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hHK0H5bOHZzlSvzaOm571w.jpeg</url>
            <title>Stories by Akalanka Prabodani on Medium</title>
            <link>https://medium.com/@akalankaprabodani?source=rss-da031917fd58------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 02:25:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@akalankaprabodani/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to deploy a FastAPI Machine Learning application in Render]]></title>
            <link>https://medium.com/@akalankaprabodani/how-to-deploy-a-fastapi-machine-learning-application-in-render-d24c64a4bde8?source=rss-da031917fd58------2</link>
            <guid isPermaLink="false">https://medium.com/p/d24c64a4bde8</guid>
            <dc:creator><![CDATA[Akalanka Prabodani]]></dc:creator>
            <pubDate>Mon, 09 Sep 2024 20:14:01 GMT</pubDate>
            <atom:updated>2024-09-09T20:14:01.870Z</atom:updated>
            <content:encoded><![CDATA[<p>In this tutorial, I’ll walk you through how to train a machine learning model, expose it using FastAPI, and deploy the application on Render. I used a simple machine learning model (Titanic Survival Prediction) as an example. By the end of this guide, you’ll be able to deploy your own FastAPI machine learning application to the cloud with Render.</p><p><strong>Step 1: Training the Machine Learning Model in Google Co-lab</strong></p><p>First, we need to train the model before deploying it. I’ve used the Titanic dataset to predict passenger survival. Follow the steps below to load the dataset, train the model, and save it.</p><pre># Import necessary libraries<br>import pandas as pd<br>from sklearn.model_selection import train_test_split<br>from sklearn.ensemble import RandomForestClassifier<br>import joblib<br><br># Load dataset<br>url = &#39;https://path-to-your-dataset&#39;<br>data = pd.read_csv(url)<br><br># Split data into training and testing sets<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)<br><br># Train model<br>model = RandomForestClassifier()<br>model.fit(X_train, y_train)</pre><p>In this step, I load the Titanic dataset, clean the data by imputing missing values, encode the categorical features like “Sex”, and finally train a <strong>Random Forest Classifier</strong>. The trained model is saved as titanic_model.pkl for deployment in FastAPI.</p><pre># Save the model<br>joblib.dump(model, &#39;titanic_model.pkl&#39;)</pre><h4><strong>Step 2: Create a FastAPI Application</strong></h4><p>Now that we have trained the model, the next step is to create the FastAPI application that will serve predictions using this model.</p><p>Here’s the app.py file:</p><pre>import os<br>from fastapi import FastAPI<br>from pydantic import BaseModel<br>import pandas as pd<br>import joblib<br><br># 1. Initialize FastAPI app<br>app = FastAPI()<br>@app.get(&quot;/&quot;)<br>def read_root():<br>    return {&quot;message&quot;: &quot;Welcome to the Titanic Survival Prediction API!&quot;}<br><br># 2. Load the trained model<br>model_path = os.getenv(&#39;MODEL_PATH&#39;, &#39;titanic_model.pkl&#39;)  <br># Read model path from environment variable<br>model = joblib.load(model_path)<br><br># 3. Define the input data model<br>class PassengerInput(BaseModel):<br>    Pclass: int<br>    Sex: int<br>    Age: float<br>    SibSp: int<br>    Parch: int<br>    Fare: float<br>    Embarked_Q: int<br>    Embarked_S: int<br>    FamilySize: int<br><br># 4. Define the prediction endpoint<br>@app.post(&quot;/predict/&quot;)<br>def predict_survival(input_data: PassengerInput):<br>    # Convert input data to DataFrame for model<br>    input_df = pd.DataFrame([input_data.dict()])<br>    <br>    # Make prediction<br>    prediction = model.predict(input_df)<br>    <br>    # Return prediction result<br>    return {&quot;Survived&quot;: int(prediction[0])}<br><br># 5. Run the API with uvicorn<br>if __name__ == &quot;__main__&quot;:<br>    import uvicorn<br>    uvicorn.run(app, host=&quot;0.0.0.0&quot;, port=int(os.environ.get(&quot;PORT&quot;, 8000)))</pre><p>In the code presented above, I utilized the FastAPI library to create an efficient and user-friendly REST API. The application starts with the initialization of the FastAPI app using the app = FastAPI() command, followed by defining the root endpoint with the @app.get(&quot;/&quot;) decorator, which returns a simple welcome message when accessed. I used the joblib library to load the pre-trained Titanic survival prediction model from a file (titanic_model.pkl). The model file path is obtained from an environment variable MODEL_PATH, ensuring flexibility in different deployment environments. If the MODEL_PATH is not set, it defaults to the local model file. The PassengerInput class, which inherits from FastAPI’s BaseModel, defines the structure of the input data the API expects. This data includes attributes like passenger class (Pclass), sex (Sex), age (Age), family details, and other relevant features. FastAPI automatically validates the incoming JSON request to ensure it conforms to this model, providing immediate feedback to the client if the data is invalid. To handle predictions, I defined a /predict/ endpoint using @app.post(&quot;/predict/&quot;). When a POST request with passenger data is sent, the input is converted into a Pandas DataFrame, which the model uses to make a prediction. The result is then returned as a JSON response, indicating whether the passenger survived or not. Lastly, I used Uvicorn, an ASGI server, to run the FastAPI application locally on localhost (127.0.0.1) at port 8000. This setup is crucial for testing and debugging before deploying the application in a production environment.</p><p><em>Then need to run the server using this command by opening a shell in the relevant project folder. “</em>uvicorn app:app<em>”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*tv2ufUG6uINsnzWSYVdaJQ.png" /><figcaption><em>output will looks like this once you run the server</em></figcaption></figure><p>Now I enter<strong><em> /docs</em></strong> to the URL to load the GUI interface of the created FastAPI and you can see the page like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JWVDzuZjqIBbyg0t5bGyhQ.png" /></figure><h4>Now, let’s explore how the POST method works</h4><p>The POST method is responsible for making predictions on whether a passenger would survive based on the input data. This method is accessible via the /predict path. I used the FastAPI GUI to test this functionality without needing any additional tools.</p><p>lets see how the POST method is work. You can see that using the below image with the output. First I need to directed to the <strong><em>/university/predict</em></strong> path to get access of it. then press the <strong><em>try it out</em></strong> in the right corner of the page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MUzCmGnbOiEZ52M3xjRofA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Glx20jULUYTK4R0ihDT-Ww.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w1kO1ma_8ZWgYY3I6wxSuQ.png" /></figure><p>This result indicates that the model predicts the passenger <strong>would survive</strong> based on the provided input data.</p><p><strong>Step 3: Setting up the Render Platform</strong></p><p>To deploy your FastAPI app on Render, start by creating an account on Render but I don’t have one already. After logging in, navigate to the dashboard and click on “New” to begin the deployment process. Select “Web Service” to deploy your FastAPI application. Connect my GitHub repository by clicking “Connect account,” which will enable Render to access my code. This integration streamlines the deployment process and I ensures that my FastAPI app can be automatically built and deployed from my GitHub repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jMYzsV94gi13G6XvGXxS3w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xPwi3h_9vFwpsKusQBz_kQ.png" /></figure><p>After selecting my repository and branch, I directed to the service configuration page and Replace app with my FastAPI application file&#39;s name, uvicorn app:app — host 0.0.0.0 — port 10000. To configure environment variables like the model path Scroll down to <strong>Environment Variables</strong> and add variables such as: MODEL_PATH: titanic_model.pkl. To add the required files, Make sure the project includes the following essential files.</p><p>Once i configured my FastAPI app on Render, click “Create Web Service” to start the deployment process. Render will then pull the code from the GitHub repository and proceed to install all the dependencies specified in my `requirements.txt` file. Following this, Render I deployed the application using the `START_COMMAND` i provided, ensuring that myFastAPI app is up and running according to the specified settings. This automated process simplifies deployment and ensures that my application is deployed efficiently and correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*id4zzH6hrm_xE9bq0TfAcg.png" /></figure><p>Once I successfully deployed, my FastAPI application will be accessible via the unique Render URL provided.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iWkPrztloroRW6NWRFtfDw.png" /></figure><p><strong>Step 4: Automating Deployment with GitHub Actions</strong></p><p>To automate the deployment process, we can set up a CI/CD pipeline using GitHub Actions. Here’s the GitHub Actions YAML file to build and deploy the FastAPI application whenever changes are pushed to the repository.</p><p>To set this up, I created a GitHub Actions workflow file and test.yml file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*RxZgQVU7xzpA5iIe6ADdxw.png" /></figure><p>This pipeline automates the deployment whenever a new commit is pushed to the main branch.</p><pre>name: CI/CD Pipeline for FastAPI Deployment<br><br>on:<br>  push:<br>    branches:<br>      - main<br><br>jobs:<br>  build-and-deploy:<br>    runs-on: ubuntu-latest<br><br>    steps:<br>    # Checkout the code<br>    - name: Checkout code<br>      uses: actions/checkout@v3<br><br>    # Set up Python environment<br>    - name: Set up Python 3.11<br>      uses: actions/setup-python@v3<br>      with:<br>        python-version: &#39;3.11&#39;<br><br>    # Install dependencies<br>    - name: Install dependencies<br>      run: |<br>        python -m pip install --upgrade pip<br>        pip install -r requirements.txt<br><br><br>    # Install Render CLI<br>    - name: Install Render CLI<br>      run: |<br>        curl -fsSL https://cli.render.com/install | bash<br>        export PATH=$PATH:/root/.local/bin<br>        render --version  # Verify installation<br><br>    # Deploy to Render<br>    - name: Deploy to Render<br>      run: |<br>        export PATH=$PATH:/root/.local/bin  # Ensure PATH includes Render CLI<br>        render services update api --api-key rnd_fJ4PumLUh0CL5KUby29Vi0Wp7nhJ --envfile .env</pre><p>Finally I successful CI/CD pipeline execution for deploying a FastAPI application using GitHub Actions. This pipeline automates several critical steps in the deployment process, starting with setting up the job environment and checking out the latest version of the code from the repository. It then configures Python 3.11, installs the necessary dependencies from the `requirements.txt` file, and prepares the environment for deployment. After these steps, the job completes successfully, indicating that the application is ready for deployment. This automated process ensures that any changes pushed to the repository trigger tests and deployment, streamlining the development workflow and minimizing manual intervention, making it a more reliable and efficient deployment solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5yvz81V3iN7Qh9gNxh24jQ.png" /></figure><p>In conclusion, deploying a FastAPI Machine Learning application on Render is a straightforward and efficient process when paired with an automated CI/CD pipeline through GitHub Actions. By following these steps, you can ensure seamless deployment with minimal manual intervention, allowing your application to scale and run reliably in a production environment. Leveraging tools like FastAPI for API development, GitHub Actions for continuous integration, and Render for deployment, you can streamline the development workflow and focus on improving the performance and capabilities of your application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d24c64a4bde8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>