Summarize this article with:
- AI-generated content can be used for both beneficial and harmful purposes.
- Let's begin by creating a simple FastAPI application that will host our AI detection endpoints.
- This function takes a text input and uses the Eden AI API to detect if it's AI-generated.
- Whether you're working in media, cybersecurity, or simply seeking to improve your personal content validation practices, integrating this API into your projects will allow you to spot fake content in seconds!
- VIDEO | How to Create an AI Content Detector for Text, Images, and Deepfakes: A Step-by-Step Tutorial enables automation, accuracy improvements, and cost reduction across AI-powered applications.
The rise of AI-generated content has made it increasingly difficult to distinguish between human and machine-created text, images, and deepfakes.
Whether you're a journalist, a researcher, or simply a concerned internet user, detecting AI-generated content is a crucial skill.
In this guide, we will explore how to build an AI content detection API using FastAPI and Eden AI APIs to spot fake content quickly and efficiently.
Why AI Detection Matters
AI-generated content can be used for both beneficial and harmful purposes. While it helps automate content creation, it also poses risks such as misinformation, fraud, and deepfake scams.
With the right tools, we can verify content authenticity and mitigate these risks.
Setting Up the AI Content Detection API
If you want a complete, in-depth breakdown of this tutorial, be sure to watch our YouTube tutorial with Developer Advocate Krishna Kompalli, where we walk you through each step, explain the details of the code, and discuss how to best integrate these tools into your projects.
Prerequisites
Before we begin, ensure you have the following installed:
- Python 3.8+
- FastAPI (for building the API)
- Uvicorn (for running the FastAPI server)
- Requests (for making API calls)
- Dotenv (for managing environment variables)
You can install the required packages using:
pip install fastapi uvicorn requests python-dotenv python-multipart
Creating the FastAPI Application
Let's begin by creating a simple FastAPI application that will host our AI detection endpoints. FastAPI makes it easy to build RESTful APIs with automatic interactive documentation.
from fastapi import FastAPI, File, UploadFile, Form, HTTPException
from fastapi.middleware.cors import CORSMiddleware
import requests
import os
from dotenv import load_dotenv
import logging
Configuring Logging and Environment Variables
Before diving into the API endpoints, it’s important to set up logging and manage sensitive data like API keys using environment variables. Logging helps track API requests and potential errors, while environment variables store sensitive data such as API keys.
# Configure logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger("ai_detection")
# Load environment variables
load_dotenv()
EDENAI_API_KEY = os.getenv("EDENAI_API_KEY")
if not EDENAI_API_KEY:
raise ValueError("EDENAI_API_KEY environment variable not set")
Here, we use dotenv to load the EDENAI_API_KEY from a .env file. This key is necessary to interact with the Eden AI API, which provides AI content detection services.
Initializing FastAPI and CORS Middleware
Next, we initialize FastAPI and set up CORS (Cross-Origin Resource Sharing) to allow requests from any domain. This is important if the API is going to be used across different client applications.
app = FastAPI(title="AI Content Detection API", description="Detect AI-generated content", version="1.0.0")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
Now, we’re ready to define the API endpoints.
Defining API Endpoints
We will create three key endpoints to detect different types of AI-generated content:
- Text AI Detection: Detects whether the given text is AI-generated.
- Image AI Detection: Identifies AI-generated images, either uploaded as a file or provided via a URL.
- Deepfake Detection: Analyzes images or videos for deepfake content.
1. Detecting AI-Generated Text
This function sends the given text to Eden AI's AI Detection API and checks whether it's AI-generated.
@app.post("/text-ai-detection")
async def detect_ai_text(text: str = Form(...), provider: str = Form("sapling")):
url = "https://api.edenai.run/v3/universal-ai"
payload = {"model": f"text/ai_detection/{provider}", "input": {"text": text}}
headers = {"accept": "application/json", "authorization": f"Bearer {EDENAI_API_KEY}"}
try:
response = requests.post(url, json=payload, headers=headers)
response.raise_for_status()
result = response.json()
except requests.exceptions.RequestException as e:
raise HTTPException(status_code=500, detail=f"Error: {str(e)}")
if result["status"] != "success":
raise HTTPException(status_code=500, detail=result["error"])
return {"results": result, "message": "Text analysis completed successfully"}
This function takes a text input and uses the Eden AI API to detect if it's AI-generated. The API response is then returned as JSON, which includes the analysis result. The text must be at least 300 characters long. Eden AI answers with HTTP 200 even when the provider fails, so the function checks the status field first.
2. Detecting AI-Generated Images
This endpoint checks if an uploaded image or a provided image URL is AI-generated.
def file_input(file: UploadFile, file_url: str):
"""Return the image URL, or upload the file to Eden AI and return its file_id."""
if file_url:
return file_url
upload = requests.post(
"https://api.edenai.run/v3/upload",
files={"file": (file.filename, file.file, file.content_type)},
headers={"authorization": f"Bearer {EDENAI_API_KEY}"},
)
upload.raise_for_status()
return upload.json()["file_id"]
@app.post("/image-ai-detection")
async def detect_ai_image(file: UploadFile = File(None), file_url: str = Form(None), provider: str = Form("winstonai")):
if not file and not file_url:
raise HTTPException(status_code=400, detail="Provide either a file or a file URL")
url = "https://api.edenai.run/v3/universal-ai"
headers = {"accept": "application/json", "authorization": f"Bearer {EDENAI_API_KEY}"}
try:
payload = {"model": f"image/ai_detection/{provider}", "input": {"file": file_input(file, file_url)}}
response = requests.post(url, json=payload, headers=headers)
response.raise_for_status()
result = response.json()
except requests.exceptions.RequestException as e:
raise HTTPException(status_code=500, detail=f"Error: {str(e)}")
if result["status"] != "success":
raise HTTPException(status_code=500, detail=result["error"])
return {"results": result, "message": "Image analysis completed successfully"}
Here, we handle both file uploads and URLs. An uploaded file is first sent to Eden AI's /v3/upload endpoint, which returns a file_id. The file_id or URL is then sent to Eden AI's Universal AI endpoint with the image/ai_detection model for analysis. The deepfake endpoint below reuses the same file_input helper.
3. Detecting Deepfakes
This function detects deepfake content by analyzing uploaded files or URLs.
@app.post("/deepfake-detection")
async def detect_deepfake(file: UploadFile = File(None), file_url: str = Form(None), provider: str = Form("sightengine")):
if not file and not file_url:
raise HTTPException(status_code=400, detail="Provide either a file or a file URL")
url = "https://api.edenai.run/v3/universal-ai"
headers = {"accept": "application/json", "authorization": f"Bearer {EDENAI_API_KEY}"}
try:
payload = {"model": f"image/deepfake_detection/{provider}", "input": {"file": file_input(file, file_url)}}
response = requests.post(url, json=payload, headers=headers)
response.raise_for_status()
result = response.json()
except requests.exceptions.RequestException as e:
raise HTTPException(status_code=500, detail=f"Error: {str(e)}")
if result["status"] != "success":
raise HTTPException(status_code=500, detail=result["error"])
return {"results": result, "message": "Deepfake analysis completed successfully"}
This endpoint focuses on detecting deepfake images or videos, which is critical for verifying the authenticity of media content.
Running the API
To run the FastAPI server, use the following command:
uvicorn fake_content_detection:app --host 0.0.0.0 --port 8000
This command will start the API server, making it accessible on localhost at port 8000.
Testing the API
Once the server is running, you can test the endpoints using Postman or cURL.
For example, to test the text detection endpoint, you can use the following cURL command:
curl -X 'POST' 'http://localhost:8000/text-ai-detection' \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d 'text=Paste here the text to check, at least 300 characters long&provider=sapling'
Conclusion
In this guide, we built an AI content detection API using FastAPI and Eden AI APIs. With this API, you can:
- Detect AI-generated text
- Identify AI-created images
- Spot deepfake media
By implementing this solution, you’ll be able to enhance your content verification workflows and help mitigate the risks of misinformation and deception. Don't forget to watch our Youtube tutorial for a thorough breakthrough.
Whether you're working in media, cybersecurity, or simply seeking to improve your personal content validation practices, integrating this API into your projects will allow you to spot fake content in seconds!

.jpg)

