• About Us
  • Disclaimer
  • Contact Us
  • Privacy Policy
Friday, June 26, 2026
mGrowTech
No Result
View All Result
  • Technology And Software
    • Account Based Marketing
    • Channel Marketing
    • Marketing Automation
      • Al, Analytics and Automation
      • Ad Management
  • Digital Marketing
    • Social Media Management
    • Google Marketing
  • Direct Marketing
    • Brand Management
    • Marketing Attribution and Consulting
  • Mobile Marketing
  • Event Management
  • PR Solutions
  • Technology And Software
    • Account Based Marketing
    • Channel Marketing
    • Marketing Automation
      • Al, Analytics and Automation
      • Ad Management
  • Digital Marketing
    • Social Media Management
    • Google Marketing
  • Direct Marketing
    • Brand Management
    • Marketing Attribution and Consulting
  • Mobile Marketing
  • Event Management
  • PR Solutions
No Result
View All Result
mGrowTech
No Result
View All Result
Home Al, Analytics and Automation

Securing FastAPI Endpoints for MLOps: An Authentication Guide

Josh by Josh
July 17, 2025
in Al, Analytics and Automation
0
Securing FastAPI Endpoints for MLOps: An Authentication Guide


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.

READ ALSO

MIT in the media: Exploring how curiosity-driven science is an essential ingredient in America’s success | MIT News

DeepReinforce Releases Ornith-1.0: An Open-Source Coding Model Family That Learns Its Own RL Scaffolds

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.

python –m venv venv

source venv/bin/activate      # Windows: venv\Scripts\activate

pip install fastapi uvicorn scikit–learn pandas joblib python–dotenv

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.

from sklearn.datasets import load_wine

from sklearn.ensemble import RandomForestClassifier

import joblib

 

X, y = load_wine(return_X_y=True, as_frame=False)

model = RandomForestClassifier(n_estimators=200, random_state=42).fit(X, y)

joblib.dump(model, “wine_clf.joblib”)

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

import os

from typing import List, Optional

import joblib

import uvicorn

from dotenv import load_dotenv

from fastapi import Depends, FastAPI, HTTPException, Security, status

from fastapi.security.api_key import APIKeyHeader

from pydantic import BaseModel

 

app = FastAPI(title=“Secured Wine Classifier”)

MODEL = joblib.load(“wine_clf.joblib”)

CLASS_NAMES = [“Cultivar-0”, “Cultivar-1”, “Cultivar-2”]

 

class WineRequest(BaseModel):

    data: List[List[float]]  # each inner list: 13 numeric features

class WineResponse(BaseModel):

    predictions: List[str]

 

@app.post(“/predict”, response_model=WineResponse)

async def predict(payload: WineRequest):

    preds = MODEL.predict(payload.data)

    labels = [CLASS_NAMES[i] for i in preds]

    return WineResponse(predictions=labels)

if __name__ == “__main__”:

    uvicorn.run(“main:app”, host=“localhost”, port=8000, reload=True)

Run the FastAPI app:

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

curl –X POST http://localhost:8000/predict \

     –H “Content-Type: application/json” \

     –d ‘{“data”: [[14.23,1.71,2.43,15.6,127,2.80,3.06,0.28,2.29,5.64,1.04,3.92,1065]]}’

Response:

{“predictions”:[“Cultivar-0”]}

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:

load_dotenv()

API_KEY = os.getenv(“API_KEY”)

API_KEY_NAME = “X-API-Key”

api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=False)

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. 

async def get_api_key(api_key: Optional[str] = Security(api_key_header)):

    if api_key == API_KEY:

        return api_key

    raise HTTPException(

        status_code=status.HTTP_401_UNAUTHORIZED,

        detail=“Invalid API Key”,

        headers={“WWW-Authenticate”: “Bearer”},

    )

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:

@app.post(“/predict”, response_model=WineResponse, dependencies=[Depends(get_api_key)])

async def predict(payload: WineRequest):

    preds = MODEL.predict(payload.data)

    labels = [CLASS_NAMES[i] for i in preds]

    return WineResponse(predictions=labels)

 

if __name__ == “__main__”:

    uvicorn.run(“main:app”, host=“localhost”, port=8000, reload=True)

After updating the endpoint, run the application again:

You should see the following output in the terminal:

INFO:     Will watch for changes in these directories: [‘C:\\Repository\\GitHub\\securing-fastapi-endpoints’]            

INFO:     Uvicorn running on http://localhost:8000 (Press CTRL+C to quit)                                                

INFO:     Started reloader process [8372] using StatReload                                                                

INFO:     Started server process [19020]                                                                                  

INFO:     Waiting for application startup.

INFO:     Application startup complete.

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. 

curl –X POST http://localhost:8000/predict \

     –H “Content-Type: application/json” \

     –d ‘{“data”: [[14.23,1.71,2.43,15.6,127,2.80,3.06,0.28,2.29,5.64,1.04,3.92,1065]]}’

Response:

{“detail”:“Invalid API Key”}

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.

curl –X POST http://localhost:8000/predict \

     –H “Content-Type: application/json” \

     –H “X-API-Key: abid11111” \

     –d ‘{“data”: [[14.23,1.71,2.43,15.6,127,2.80,3.06,0.28,2.29,5.64,1.04,3.92,1065]]}’

Response:

{“detail”:“Invalid API Key”}

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. 

curl –X POST http://localhost:8000/predict \

     –H “Content-Type: application/json” \

     –H “X-API-Key: abid1234” \

     –d ‘{“data”: [[14.23,1.71,2.43,15.6,127,2.80,3.06,0.28,2.29,5.64,1.04,3.92,1065]]}’

Response:

{“predictions”:[“Cultivar-0”]}

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

Related Posts

MIT in the media: Exploring how curiosity-driven science is an essential ingredient in America’s success | MIT News
Al, Analytics and Automation

MIT in the media: Exploring how curiosity-driven science is an essential ingredient in America’s success | MIT News

June 26, 2026
DeepReinforce Releases Ornith-1.0: An Open-Source Coding Model Family That Learns Its Own RL Scaffolds
Al, Analytics and Automation

DeepReinforce Releases Ornith-1.0: An Open-Source Coding Model Family That Learns Its Own RL Scaffolds

June 26, 2026
Al, Analytics and Automation

Clustering Unstructured Text with LLM Embeddings and HDBSCAN

June 25, 2026
Improving the speed and energy-efficiency of AI agents | MIT News
Al, Analytics and Automation

Improving the speed and energy-efficiency of AI agents | MIT News

June 25, 2026
Baidu Releases Unlimited OCR, a 3B Model That Keeps the KV Cache Flat for Long-Document Parsing
Al, Analytics and Automation

Baidu Releases Unlimited OCR, a 3B Model That Keeps the KV Cache Flat for Long-Document Parsing

June 25, 2026
Al, Analytics and Automation

Context Windows Are Not Memory: What AI Agent Developers Need to Understand

June 25, 2026
Next Post
Microsoft is buying tons of carbon removal from Xprize startup Vaulted Deep

Microsoft is buying tons of carbon removal from Xprize startup Vaulted Deep

POPULAR NEWS

Trump ends trade talks with Canada over a digital services tax

Trump ends trade talks with Canada over a digital services tax

June 28, 2025
15 Trending Songs on TikTok in 2025 (+ How to Use Them)

15 Trending Songs on TikTok in 2025 (+ How to Use Them)

June 18, 2025
Communication Effectiveness Skills For Business Leaders

Communication Effectiveness Skills For Business Leaders

June 10, 2025
App Development Cost in Singapore: Pricing Breakdown & Insights

App Development Cost in Singapore: Pricing Breakdown & Insights

June 22, 2025
Comparing the Top 7 Large Language Models LLMs/Systems for Coding in 2025

Comparing the Top 7 Large Language Models LLMs/Systems for Coding in 2025

November 4, 2025

EDITOR'S PICK

Google Home will soon get better at recognizing you

Google Home will soon get better at recognizing you

June 24, 2026
How best to learn marketing skills for strategy

How best to learn marketing skills for strategy

September 26, 2025
Proven Tips to Grow Your Followers on Instagram Fast

Proven Tips to Grow Your Followers on Instagram Fast

June 3, 2025
Meta Ads Attribution Reporting: What Your Results Really Mean

Meta Ads Attribution Reporting: What Your Results Really Mean

June 2, 2026

About

We bring you the best Premium WordPress Themes that perfect for news, magazine, personal blog, etc. Check our landing page for details.

Follow us

Categories

  • Account Based Marketing
  • Ad Management
  • Al, Analytics and Automation
  • Brand Management
  • Channel Marketing
  • Digital Marketing
  • Direct Marketing
  • Event Management
  • Google Marketing
  • Marketing Attribution and Consulting
  • Marketing Automation
  • Mobile Marketing
  • PR Solutions
  • Social Media Management
  • Technology And Software
  • Uncategorized

Recent Posts

  • Insider One as a MoEngage Alternative: Why Brands Switch
  • AI Data Security Platform Development: Cost, Benefits & Process
  • Welcoming New Members: A Guide for Churches
  • 5 Google Gemini AI tips for parents
  • About Us
  • Disclaimer
  • Contact Us
  • Privacy Policy
No Result
View All Result
  • Technology And Software
    • Account Based Marketing
    • Channel Marketing
    • Marketing Automation
      • Al, Analytics and Automation
      • Ad Management
  • Digital Marketing
    • Social Media Management
    • Google Marketing
  • Direct Marketing
    • Brand Management
    • Marketing Attribution and Consulting
  • Mobile Marketing
  • Event Management
  • PR Solutions