Securing FastAPI Endpoints for MLOps: An Authentication Guide

Securing FastAPI Endpoints for MLOps: An Authentication Guide
Image by Author

Introduction

In today’s AI world, data scientists are not just focused on training and optimizing machine learning models. Companies are increasingly seeking data scientists who possess skills in machine learning operations (MLOps), which includes building REST APIs for model inference and deploying these models to the cloud. While creating a simple API can be effective for testing purposes, deploying a model in a production environment requires a more robust approach, particularly in terms of security.

In this tutorial, we will build a straightforward machine learning application using FastAPI. Then, we will guide you on how to set up authentication for the same application, ensuring that only users with the correct token can access the model to generate predictions.

1. Setting Up A Project

We will be building a “wine classifier”, and to get started, we will first create a Python virtual environment and install the necessary Python libraries for training and serving the model.

Next, we will create a train_model.py file and write a training script to load the toy dataset from Scikit-learn, train it using a random forest classifier, and save the trained model in the root directory.

Run the training script:

2. Building a Simple FastAPI App

Now, we will create a main.py file to build a REST API for model inference. This app will load the trained model, define a /predict endpoint, and handle incoming requests for predictions. The /predict endpoint accepts user input, passes it through the model, and returns the predicted class name.

Run the FastAPI app:

You can now test the /predict endpoint using a curl command:

Response:

As you can see, the endpoint is currently unsecured, meaning anyone can access it, which is not ideal for production.

3. Setting Up the API Key and Custom Header

To secure the API, we will implement authentication using an API key. First, create a .env file and add the API key:

Next, update the main.py file to include the API key logic. Add the following code after initializing the CLASS_NAMES variable:

4. Implementing the Authentication Dependency

In this step, we will implement an authentication dependency to validate the API key provided by the client. This ensures that only authorized users with a valid API key can access the endpoints. 

5. Protecting the Endpoints with Authentication

Once the authentication dependency is defined, we can use it to protect the /predict endpoint. By adding the dependency to the endpoint, we ensure that only requests with a valid API key can access the prediction service.

Here’s the updated /predict endpoint with the authentication dependency:

After updating the endpoint, run the application again:

You should see the following output in the terminal:

Swagger UI is automatically generated by FastAPI and provides an interactive interface to explore and test your API endpoints. Once your FastAPI application is running, you can access the Swagger UI by navigating to the following URL in your browser: http://localhost:8000/docs

Securing FastAPI Endpoints

6. Testing the Secured Endpoints

In this section, we will test the /predict endpoint with various cases to verify that the API key authentication is working correctly. This includes testing for missing API keys, invalid API keys, and valid API keys.

Testing Without an API Key

In this test, we will send a request to the /predict endpoint without providing the X-API-Key header. 

Response:

This confirms that the endpoint correctly denies access when no API key is provided.

Testing With an Incorrect API Key

Next, we will test the endpoint by providing an incorrect API key in the X-API-Key header.

Response:

This confirms that the endpoint correctly denies access when an invalid API key is provided.

Testing With a Correct API Key

Finally, we will test the endpoint by providing the correct API key in the X-API-Key header. 

Response:

This confirms that the endpoint correctly processes requests when a valid API key is provided.

Final Thoughts

We have successfully trained the model and served it by creating a simple FastAPI application. Additionally, we enhanced the application by implementing authentication, showcasing how security can be integrated into a web API.

FastAPI also includes built-in security features for efficient user management and role-based OAuth2 authentication systems. Its simplicity makes it a great choice for building secure and scalable web applications.



Source link