# 🚀 Part 1: Preparing Your FastAPI + Scikit-Learn App for Deployment on Google Cloud Run

### 🧠 Why FastAPI + Scikit-Learn + Google Cloud?

FastAPI gives us a blazing-fast way to expose machine learning models as APIs. With Google Cloud Run, we can deploy those APIs **without managing servers**, scaling automatically based on traffic.

In this guide, we walk through converting a local machine learning API into a production-ready cloud service — and it all begins with structuring your project.

---

### 🗂️ Project Structure

Make sure your folder (we named it `ChurnAPI_test`) contains the following files:

```python
cssCopyEditChurnAPI_test/
├── main.py
├── model.joblib
├── requirements.txt
└── Dockerfile
```

---

### 🧾 Step 1: Preparing [`main.py`](http://main.py) for Cloud Run

The [`main.py`](http://main.py) file is the heart of your FastAPI app. Here's a sample version adapted for **Google Cloud Run**:

```python
pythonCopyEditimport uvicorn
import os
from fastapi import FastAPI
from pydantic import BaseModel
import joblib
import pandas as pd

app = FastAPI()

# Load the model
model = joblib.load("model.joblib")

# Define input schema
class Customer(BaseModel):
    data: dict

@app.post("/predict")
def predict(customer: Customer):
    try:
        df = pd.DataFrame([customer.data])
        prediction = model.predict(df)[0]
        probability = model.predict_proba(df)[0][1]
        return {
            "prediction": int(prediction),
            "churn_probability": round(probability, 3)
        }
    except Exception as e:
        return {"error": str(e)}

# ✅ Cloud Run entry point
if __name__ == "__main__":
    port = int(os.environ.get("PORT", 8080))
    uvicorn.run("main:app", host="0.0.0.0", port=port)
```

🔍 **Key differences from local testing is we include this part of code**:

`if name == "__main__":`

    `port = int(os.environ.get("PORT", 8080))`

   [`uvicorn.run`](http://uvicorn.run)`("main:app", host="0.0.0.0", port=port)`

* Uses `host="0.0.0.0"` (required by Docker)
    
* Reads `PORT` from environment variable (used by Cloud Run)
    
* No `reload=True` (that’s only for local development)
    

---

### 📄 Step 2: Create `requirements.txt`

Google Cloud needs to know which Python packages to install inside your Docker container. That’s where `requirements.txt` comes in.

#### ✅ Steps to Create It:

1. In your project folder (`ChurnAPI_test`), create a new text file.
    
2. Rename the file exactly to:
    

```python
fastapi
uvicorn
pandas
joblib
scikit-learn
```

📌 Add any extra libraries your model or code depends on (e.g., `numpy`, `xgboost`).

---

### 🐳 Step 3: Create `Dockerfile`

Docker lets us package our app, model, and dependencies into a portable container. Here’s the `Dockerfile` for our project:

#### ✅ How to Create a `Dockerfile` (Step-by-Step)

📁 In your `ChurnAPI_test` project folder:

1. Open **Notepad** or any plain text editor.
    
2. Paste the following code (this is the full working version):
    

```python
# Use official Python image
FROM python:3.10-slim

# Set working directory inside the container
WORKDIR /app

# Copy all files from your local folder into the container
COPY . .

# Install required Python packages
RUN pip install --no-cache-dir -r requirements.txt

# Expose port Cloud Run will use
ENV PORT 8080
EXPOSE 8080

# Start FastAPI app with uvicorn
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080"]
```

### 🐳 Full Dockerfile Explained (Line-by-Line)

This `Dockerfile` tells Google Cloud how to build and run your FastAPI + scikit-learn app inside a container. Below is the complete version with clear explanations for each step:

```python
# ✅ Step 1: Start with a lightweight official Python 3.10 image
FROM python:3.10-slim
```

> This pulls a minimal version of Python 3.10 as the base. The `slim` variant keeps the image small and fast, which is ideal for cloud deployments.

---

```python
# ✅ Step 2: Set the working directory inside the container
WORKDIR /app
```

> This creates a directory called `/app` inside the container and sets it as the working directory. All subsequent commands will run from here.

---

```python
# ✅ Step 3: Copy all project files into the container
COPY . .
```

> This copies everything from your local project folder (`ChurnAPI_test`) into the `/app` directory inside the container. That includes [`main.py`](http://main.py), `model.joblib`, `requirements.txt`, and your Dockerfile itself.

---

```python
# ✅ Step 4: Install the Python dependencies listed in requirements.txt
RUN pip install --no-cache-dir -r requirements.txt
```

> This installs all the required Python packages inside the container.
> 
> * The `--no-cache-dir` flag helps reduce the final image size.
>     

---

```python
# ✅ Step 5: Set the environment variable for the port (used by Cloud Run)
ENV PORT 8080
EXPOSE 8080
```

> Google Cloud Run sends requests to your app through port 8080.
> 
> * `ENV PORT 8080` sets the environment variable.
>     
> * `EXPOSE 8080` tells Docker this is the port your app will listen on.
>     

---

```python
# ✅ Step 6: Start the FastAPI server using Uvicorn
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080"]
```

> This is the command Docker runs when your container starts.  
> It launches your FastAPI app using `uvicorn`, making it accessible publicly.

* `main:app` → [`main.py`](http://main.py) file and `app = FastAPI()`
    
* `--host 0.0.0.0` → ensures the app listens to external traffic (not just [localhost](http://localhost))
    
* `--port 8080` → matches the port Cloud Run will send traffic to
    

---

### ✅ Summary

This Dockerfile:

* Sets up a clean Python environment
    
* Installs your machine learning app's dependencies
    
* Starts your FastAPI app correctly for production
    

Once built, this container can be deployed to **any cloud platform**, including Google Cloud Run, with no code changes.

## 🚀 Part 2: Setting Up Google Cloud SDK and CLI for FastAPI Deployment

In [Part 1](#), we built a FastAPI app with a scikit-learn model, added a `Dockerfile`, and got everything ready for deployment. In this post, we’ll walk through how to set up Google Cloud CLI (gcloud) and prepare your environment to deploy that app to the cloud.

Let’s get started!

---

### 🧩 Step 1: Install the Google Cloud SDK

Google Cloud CLI is a command-line tool used to deploy, manage, and monitor services on Google Cloud.

#### 🔗 Download and Install:

👉 [https://cloud.google.com/sdk/docs/install](https://cloud.google.com/sdk/docs/install)

✅ Follow the instructions for your operating system (Windows/macOS/Linux). After installing, open **Command Prompt** (or Terminal) and check if it's working:

```python
gcloud --version
```

You should see the version number and some installed components.

---

### 🔐 Step 2: Authenticate with Google Cloud

To link your terminal with your Google Cloud account, run:

```python
gcloud auth login
```

This will:

* Open a browser window
    
* Ask you to log in to your Google account
    
* Authenticate your terminal session with Google Cloud
    

---

### 🏗️ Step 3: Set Your Google Cloud Project

You must tell `gcloud` which project you're working on. Based on your dashboard, your Project ID is:

```python
churnapi-456817
```

Run:

```python
gcloud config set project churnapi-456817
```

✅ This ensures all future commands (like build and deploy) apply to your churn project.

---

### ⚙️ Step 4: Enable Required Google Cloud Services

By default, services like **Cloud Run** and **Cloud Build** are not enabled. These must be turned on manually:

```python
gcloud services enable run.googleapis.com
gcloud services enable cloudbuild.googleapis.com
```

#### 💡 Why?

| Service | Why It's Needed |
| --- | --- |
| `run.googleapis.com` | Hosts your FastAPI container on Google Cloud Run |
| `cloudbuild.googleapis.com` | Builds your Docker image from your folder |

Once enabled, you're ready to build and deploy 🚀

---

### 🧭 Confirm Everything Is Set

You can confirm your project and services are configured by running:

```python
gcloud config list
```

You should see:

```python
[core]
project = churnapi-456817
```

And you're ready for deployment!

## 🚀 Part 3: Deploying Your FastAPI + Scikit-Learn App to Google Cloud Run

In [Part 1](#), we prepared your FastAPI app and Dockerfile. In [Part 2](#), we set up Google Cloud SDK and enabled required services. Now, in **Part 3**, we’ll build the container and deploy it to the cloud!

Let’s put your API into production.

---

### 🏗️ Step 1: Build and Submit Your Docker Image to Google Cloud

Make sure you're in your project folder that contains:

```python
main.py
Dockerfile
requirements.txt
model.joblib
```

Then run this in your terminal:

```python
cd C:\Users\nickolat\Desktop\ChurnAPI_test
```

Now build and upload your Docker image using Cloud Build:

```python
gcloud builds submit --tag gcr.io/churnapi-456817/churn-api
```

#### 🔍 What this does:

* Uses your `Dockerfile` to build an image
    
* Tags it as `churn-api`
    
* Uploads it to your Google Container Registry
    

Once it finishes, you'll see:

```python
DONE
IMAGE: gcr.io/churnapi-456817/churn-api
```

✅ You’ve now got a ready-to-deploy container!

---

### 🚀 Step 2: Deploy to Google Cloud Run

Now deploy your container to Cloud Run using this command:

```python
gcloud run deploy churn-api \
  --image gcr.io/churnapi-456817/churn-api \
  --platform managed \
  --region asia-south1 \
  --allow-unauthenticated
```

#### 💡 Explanation:

| Option | What it does |
| --- | --- |
| `churn-api` | The name of your service |
| `--image` | Points to your built Docker image |
| `--platform managed` | Uses the fully managed Cloud Run platform |
| `--region asia-south1` | Deploys to the Mumbai region |
| `--allow-unauthenticated` | Makes your API publicly accessible |

You’ll then see output like:

```python
Service [churn-api] revision [churn-api-00001-xzy] has been deployed.
Service URL: https://churn-api-1069019972109.asia-south1.run.app
```

✅ This is your **live API URL**!

---

### 🔍 Step 3: Test Your API on the Web

Visit the Swagger UI:

👉 https://churn-api-1069019972109.asia-south1.run.app/docs

You’ll see an interactive interface where you can test the `/predict` endpoint.

#### 🔁 Sample JSON to Use:

```python
jsonCopyEdit{
  "data": {
    "Online Security": "No",
    "Online Backup": "Yes",
    "Device Protection": "Yes",
    "Tech Support": "No",
    "Contract": "Month-to-month",
    "Paperless Billing": "Yes",
    "Payment Method": "Electronic check",
    "Married": "No",
    "Offer": "None",
    "Premium Tech Support": "No",
    "Unlimited Data": "Yes",
    "Internet Info": "Fiber Optic",
    "Revenue Category": "2000–5000",
    "Total Charges Category": "200–400",
    "Monthly Charge Category": "70–90",
    "Total Long Distance Charge Category": "0–20",
    "Avg Monthly GB Download Category": "20–40",
    "Age Category": "26–35",
    "Dependents_Category": "No",
    "Referrals_Category": "1–2",
    "Tenure_Category": "6–12 months"
  }
}
```

Hit **“Execute”** and you’ll get a prediction result and churn probability!

---

### ✅ Final Thoughts

You’ve now:

* Packaged your machine learning model
    
* Deployed it with FastAPI inside a Docker container
    
* Made it publicly accessible on Google Cloud Run
    

Your churn prediction API is now production-ready and can be called from anywhere — including your .NET frontend, mobile apps, or third-party tools.
