---
title: "AI Deploy - Tutorial - Deploy and call a spam classifier with FastAPI"
description: "Learn how to deploy an API for Spam classification."
url: https://docs.us.ovhcloud.com/en/public-cloud/ai-machine-learning/ai-deploy-fastapi-spam-classifier
lang: en
---
> For AI agents: the complete documentation index is available at https://docs.us.ovhcloud.com/en/llms.txt, the full documentation bundle is available at https://docs.us.ovhcloud.com/en/llms-full.txt.

# AI Deploy - Tutorial - Deploy and call a spam classifier with FastAPI

**Learn how to deploy an API for Spam classification.**

**Note:**

AI Deploy is covered by **[OVHcloud Public Cloud Special Conditions](https://us.ovhcloud.com/legal/service-specific-terms/)**.

The use case is the [Spam Ham Collection Dataset](https://archive.ics.uci.edu/ml/datasets/SMS+Spam+Collection).

The objective of this tutorial is to show how it is possible to _create_, _deploy_, and _call_ an API with **AI Deploy**.

To do this, we will use [FastAPI](https://fastapi.tiangolo.com/), a web framework for developing RESTful APIs in Python. You will also learn how to build and use a custom Docker image for a **FastAPI** API.

 

## Requirements

- Access to the [OVHcloud Control Panel](https://manager.us.ovhcloud.com/)
- An AI Deploy project created inside a [Public Cloud project](https://us.ovhcloud.com/public-cloud/) in your OVHcloud account
- A [user for AI Deploy](https://docs.us.ovhcloud.com/en/public-cloud/ai-machine-learning/manage-users-roles.md)
- [Docker](https://www.docker.com/get-started) installed on your local computer
- Some knowledge about building an image and [Dockerfile](https://docs.docker.com/engine/reference/builder/)
- You also should have followed the tutorial [AI Notebooks - Tutorial - Build your spam classifier](https://docs.us.ovhcloud.com/en/public-cloud/ai-machine-learning/ai-notebooks-spam-classifier.md). Find the code on the [GitHub repository](https://github.com/ovh/ai-training-examples/blob/main/notebooks/natural-language-processing/text-classification/miniconda/spam-classifier/notebook-spam-classifier.ipynb). You will be able to understand the creation of the spam classification model.

 

## Instructions

You are going to follow different steps to build your **FastAPI** app.

- More information about FastAPI capabilities can be found [here](https://fastapi.tiangolo.com/).
- A direct link to the full code can be found [here](https://github.com/ovh/ai-training-examples/tree/main/apps/fastapi/spam-classifier-api).

Here we will mainly discuss how to write the `model.py` and `app.py` codes, the `requirements.txt` file, and the `Dockerfile`. If you want to see the whole code, please refer to the [GitHub repository](https://github.com/ovh/ai-training-examples/tree/main/apps/fastapi/spam-classifier-api).

 

### Create the API

Two Python files are created to define the model and build the API.

 

#### Define the model.py file

This Python file is dedicated to building and defining the **Logistic Regression** model. You can find the full code [here](https://github.com/ovh/ai-training-examples/blob/main/apps/fastapi/spam-classifier-api/model.py).

**Note:**

You can find all the information on the method used in this [notebook](https://github.com/ovh/ai-training-examples/blob/main/notebooks/natural-language-processing/text-classification/miniconda/spam-classifier/notebook-spam-classifier.ipynb). You will be able to understand the process and the different steps to follow to build a spam classifier based on **logistic regression**.

First, we have to load the [Spam Ham Collection Dataset](https://archive.ics.uci.edu/ml/datasets/SMS+Spam+Collection).

```python
def load_data():

    PATH = 'SMSSpamCollection'
    df = pd.read_csv(PATH, delimiter = "\t", names=["classe", "message"])
    X = df['message']
    y = df['classe']

    return X, y
```

Then, we create the function to split the dataset for _training_ and _test_.

```python
def split_data(X, y):

    ntest = 2000/(3572+2000)
    X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=ntest, random_state=0)

    return X_train, y_train
```

The last function allows us to build the model.

```python
def spam_classifier_model(Xtrain, ytrain):

    model_logistic_regression = LogisticRegression()
    model_logistic_regression = model_logistic_regression.fit(Xtrain, ytrain)

    coeff = model_logistic_regression.coef_
    coef_abs = np.abs(coeff)

    quantiles = np.quantile(coef_abs,[0, 0.25, 0.5, 0.75, 0.9, 1])

    index = np.where(coeff[0] > quantiles[1])
    newXtrain = Xtrain[:, index[0]]

    model_logistic_regression = LogisticRegression()

    model_logistic_regression.fit(newXtrain, ytrain)

    return model_logistic_regression, index
```

**Note:**

By calling the different functions as follows, you will be able to get a **classification result** (spam or not) as well as a **confidence score**.

```python

# extract input and output data

data_input, data_output = load_data()

# split data

X_train, ytrain = split_data(data_input, data_output)

# transform and fit training set

vectorizer = CountVectorizer(stop_words='english', binary=True, min_df=10)
Xtrain = vectorizer.fit_transform(X_train.tolist())
Xtrain = Xtrain.toarray()

# use the model and index for prediction

model_logistic_regression, index = spam_classifier_model(Xtrain, ytrain)
```

 

#### Write the app.py file

Initialize an instance of **FastAPI**.

```python
app = FastAPI()
```

Define the data format.

```python
class request_body(BaseModel):
    message : str
```

Process the message sent by the user.

```python
def process_message(message):

    desc = vectorizer.transform(message)
    dense_desc = desc.toarray()
    dense_select = dense_desc[:, index[0]]

    return dense_select
```

Define the `GET` method.

```python
@app.get('/')
def root():
    return {'message': 'Welcome to the SPAM classifier API'}
```

Create the `POST` method.

**Note:**

The `classify_message` function allows the user to send a message.

It will then call the model and return the result of the classification.

```python
@app.post('/spam_detection_path')
def classify_message(data : request_body):

    message = [
        data.message
    ]

    if (not (message)):
        raise HTTPException(status_code=400, detail="Please Provide a valid text message")

    dense_select = process_message(message)
    label = model_logistic_regression.predict(dense_select)
    proba = model_logistic_regression.predict_proba(dense_select)

    if label[0]=='ham':
        label_proba = proba[0][0]
    else:
        label_proba = proba[0][1]

    return {'label': label[0], 'label_probability': label_proba}
```

**Note:**

All the functions defined above are in the `app.py` Python file.

You can find the code on the [GitHub repository](https://github.com/ovh/ai-training-examples/blob/main/apps/fastapi/spam-classifier-api/app.py).

 

### Write the requirements.txt file for the API

The `requirements.txt` file will allow us to write all the modules needed to make our application work. This file will be useful when writing the `Dockerfile`.

```console
fastapi==0.87.0
pydantic==1.10.2
uvicorn==0.20.0
pandas==1.5.1
scikit-learn==1.1.3
```

 

### Write the Dockerfile for the application

Your Dockerfile should start with the `FROM` instruction indicating the parent image to use. In our case we choose to start from the `python:3.8` image:

```console
python:3.8
```

Create the home directory and add your files to it:

```console
WORKDIR /workspace
ADD . /workspace
```

Install the `requirements.txt` file which contains your needed Python modules using a `pip install ...` command:

```console
RUN pip install -r requirements.txt
```

Set the listening port of the container:

```console
EXPOSE 8000
```

Define the entrypoint and the default launching command to start the application:

```console
ENTRYPOINT ["uvicorn"]
CMD ["app:app", "--host", "0.0.0.0"]
```

Give correct access rights to an **ovhcloud user** (`42420:42420`):

```console
RUN chown -R 42420:42420 /workspace
ENV HOME=/workspace
```

 

### Build the Docker image from the Dockerfile

From the directory containing your **Dockerfile**, run one of the following commands to build your application image:

```console

# Build the image using your machine's default architecture

docker build . -t fastapi-spam-classification:latest

# Build image targeting the linux/amd64 architecture

docker buildx build --platform linux/amd64 -t fastapi-spam-classification:latest .
```

- The **first command** builds the image using your system’s default architecture. This may work if your machine already uses the `linux/amd64` architecture, which is required to run containers with our AI products. However, on systems with a different architecture (e.g. `ARM64` on `Apple Silicon`), the resulting image will not be compatible and cannot be deployed.

- The **second command** explicitly targets the `linux/AMD64` architecture to ensure compatibility with our AI services. This requires `buildx`, which is not installed by default. If you haven’t used `buildx` before, you can install it by running: `docker buildx install`

**Note:**

The dot argument `.` indicates that your build context (place of the **Dockerfile** and other needed files) is the current directory.

**Note:**

The `-t` argument allows you to choose the identifier to give to your image. Usually, image identifiers are composed of a **name** and a **version tag** `<name>:<version>`. For this example, we chose **fastapi-spam-classification:latest**.

 

### Test it locally (optional)

Launch the following **Docker command** to launch your application locally on your computer:

```console
docker run --rm -it -p 8000:8000 --user=42420:42420 fastapi-spam-classification:latest
```

**Note:**

The `-p 8000:8000` argument indicates that you want to execute a port redirection from the port **8000** of your local machine into the port **8000** of the Docker container. The port **8000** is the default port used by **FastAPI** applications.

**Warning:**

**NOTE:** Don't forget the `--user=42420:42420` argument if you want to simulate the exact same behavior that will occur on **AI Deploy apps**. It executes the Docker container as the specific OVHcloud user (user **42420:42420**).

Once started, your application should be available on `http://localhost:8000`.

 

### Push the image into the shared registry

**Warning:**

**NOTE:** The shared registry should only be used for testing purposes. Please consider creating and attaching your own registry. More information about this can be found [here](https://docs.us.ovhcloud.com/en/public-cloud/ai-machine-learning/manage-registries.md). The images pushed to this registry are for AI Tools workloads only, and will not be accessible for external uses.

Find the address of your shared registry by launching this command:

```console
ovhai registry list
```

Log in on the shared registry with your usual AI Platform user credentials:

```console
docker login -u <user> -p <password> <shared-registry-address>
```

Push the compiled image into the shared registry:

```console
docker tag fastapi-spam-classification:latest <shared-registry-address>/fastapi-spam-classification:latest
docker push <shared-registry-address>/fastapi-spam-classification:latest
```

 

### Launch the AI Deploy app

The following command starts a new app running your FastAPI application:

```console
ovhai app run \
      --default-http-port 8000 \
      --cpu 4 \
      <shared-registry-address>/fastapi-spam-classification:latest
```

**Note:**

`--default-http-port 8000` indicates that the port to reach on the app URL is the `8000`.

`--cpu 4` indicates that we request 4 CPUs for that app.

**Note:**

Consider adding the `--unsecure-http` attribute if you want your application to be reachable without any authentication.

 

### Interact with the deployed API through the dashboard

By clicking on the link of your AI Deploy app, you will arrive at the following page.

How to interact with your API?

You can add `/docs` at the end of the URL of your app.

**Note:**

In our example, the URL is as follows: `https://faf8ea3b-7095-4352-8e22-28f1f4107c77.app.us-east-va.ai.cloud.ovh.us/docs`.

It provides a complete dashboard for interacting with the API!

To be able to send a message for classification, select `/spam_detection_path` in the green box. Click on `Try it out` and type the message of your choice in the dedicated zone.

To get the result of the prediction, click on the `Execute` button.

Congratulations! You have obtained the result of the prediction with the **label** and the **confidence score**.

 

## Go further

- You can imagine deploying an AI model with another tool: **Gradio**. Read this [tutorial](https://docs.us.ovhcloud.com/en/public-cloud/ai-machine-learning/ai-deploy-gradio-sketch-recognition.md).
- Another way to create an AI Deploy app is to use **Streamlit**! [Follow this tutorial](https://docs.us.ovhcloud.com/en/public-cloud/ai-machine-learning/ai-deploy-streamlit-eda-iris.md).

Browse all the [AI & Machine Learning guides](https://docs.us.ovhcloud.com/en/public-cloud/ai-machine-learning/landing-page-ai-machine-learning.md).

Browse the rest of the [OVHcloud US documentation](https://docs.us.ovhcloud.com/en/index.md) for guides on our other products and services.

Learn more about [AI & Machine Learning](https://us.ovhcloud.com/public-cloud/ai-machine-learning/) on the OVHcloud US website.

If you need training or technical assistance to implement our solutions, contact your sales representative or click on [this link](https://us.ovhcloud.com/professional-services/) to get a quote and ask our Professional Services experts for a custom analysis of your project.
