AI Deepfake Detection API: A Developer’s Step-by-Step Integration Guide (With Code)

Software application uploads can easily be faked. It’s relatively simple these days to create a very realistic image, PDF, video or voice note, which would most likely go undetected by users.

Tools that have previously resided in the research labs of companies who developed synthetic media can now be rented by the hour in a browser tab for the price of a cup of coffee.

While whether or not synthetic media reaches your system is no longer the practical issue, how fast you can score and respond to the media is.

This guide will take you through the process of integrating a deepfake detection API into your existing technology stack. 

The code examples below will utilize the APIs of TruthScan’s detection services. But the same patterns will apply to any other modern, RESTful detector. We’ll take you from your first API call to full production readiness.

Let’s dive in.


Key Takeaways

  • Deepfakes can bypass basic file and OCR checks, making automated detection essential before media triggers financial or trust-related decisions.

  • A deepfake detection API can analyze images, PDFs, video, and audio for generative artifacts, metadata anomalies, and other forensic signals.

  • Developers should use confidence-score bands to automate approvals, flag suspicious media, and route borderline cases to human review.

  • Production-ready integrations need async processing, retries, fail-safe policies, load testing, and careful handling of false positives.

  • TruthScan provides detection APIs for images, PDFs, video, voice, and real-time AI, helping teams integrate automated deepfake detection into existing workflows.


Why Bother Scoring Media in the First Place?

It’s easy to underestimate how fast this shifted. According to Entrust’s Identity Fraud Report, a deepfake attack was recorded somewhere in the world roughly every five minutes in 2024, and the number of deepfake files floating around online jumped from about 500,000 in 2023 to more than eight million by 2025.

Research from Onfido and Entrust also found that digitally generated document forgeries have now overtaken physical ones, largely because a generated file carries none of the tampering marks the old tools were tuned to catch.

For you as a developer, that quietly breaks an assumption your code has probably been making for years: that a file which passes format checks and reads cleanly through OCR is real. It isn’t, not anymore.

AI Detection AI Detection

Never Worry About AI Fraud Again. TruthScan Can Help You:

  • Detect AI generated images, text, voice, and video.
  • Avoid major AI driven fraud.
  • Protect your most sensitive enterprise assets.
Try for FREE

A forged PDF extracts perfectly. A synthetic face clears a basic match. The only reliable place to catch these is below the surface at the pixel, frequency, and metadata level and it has to be automatic, because people spot a good video deepfake only about a quarter of the time.

Manual review already lost this race

Eyeballing submissions worked when faking evidence took real skill and time. That era is over. A support agent glancing at a “damaged item” photo, or an underwriter skimming a pay stub between a dozen other files, has no realistic shot at spotting a well-made fake.

An API doesn’t replace their judgment, it hands them a number they can actually act on, in milliseconds.

Where the check belongs in your stack

Most teams put the call right at the moment of upload, before the media triggers anything with money or trust attached. Do that and the happy path stays instant for the honest majority; only the suspicious stuff gets slowed down.

The usual spots:

  • Onboarding and KYC document checks, where ID photos and supporting PDFs get scored before an account goes live.
  • Claims and refund intake, where damage photos and receipts are checked before you issue a credit.
  • Marketplace listings, where product images are screened before buyers ever see them.
  • Video and voice channels, where deepfake video and cloned voices get flagged during verification.

What Actually Happens When You Call the Endpoint

The mental model is simple: you send a file, you get back a structured opinion.

Behind that endpoint, the service runs your media through models trained on millions of real and AI-generated samples, hunting for the fingerprints generation leaves behind odd frequency patterns, lighting and compression that don’t add up, facial landmarks that sit slightly wrong, and metadata that no real camera or app would have produced.

Under the hood

For an image, the image detection API looks at generative artifacts, pixel-level edits, compression quirks, and metadata anomalies in one pass.

For documents, a PDF detection API adds forensic checks on fonts, layer structure, and edit history. Video gets analyzed frame by frame for temporal glitches; audio gets checked for the spectral signature of synthetic speech.

You don’t have to implement any of that — you just need to know it’s what the score is built on.

Read the response as a signal, not a verdict

A good response gives you more than true or false. Expect three things: a confidence score telling you how likely the media is generated or edited, a plain-language explanation you can log and show a reviewer, and a heatmap that lights up exactly which regions look synthetic.

That last piece matters more than people expect, it turns a black-box number into evidence you can put in front of a customer during a dispute or an auditor during a review.

A Few Decisions to Make Before You Write Any Code

Ten minutes of planning here saves you a painful refactor later.

Sort out four things first:

  • Which media types? Images, PDFs, video, voice, or a mix? Each has its own endpoint, and a single fraud case often shows up as more than one — say, a fake selfie plus a forged statement.
  • Sync or async? Small images come back in real time. Big videos are happier handled asynchronously with a webhook.
  • Where are your thresholds? Decide up front where you’ll auto-approve, auto-reject, and send to a human. Those bands are yours to set, not the vendor’s.
  • What volume? Your monthly scan count shapes both the architecture and the bill, worth a glance at the pricing tiers before you commit.

Wiring It Up, Step by Step

Quick note: the snippets below are illustrative. Always confirm the exact endpoints, parameters, and field names in the API documentation before you ship.

Step 1: Grab your API key

Sign up, open your dashboard, and generate a key. Treat it like any other secret: keep it in an environment variable or a secrets manager, never in source control, and use separate keys for test and production so you’re never guessing which environment you’re hitting.

Step 2: Send your first file

Start with a single image so you can see the shape of what comes back. The smallest possible cURL call:

curl -X POST https://api.truthscan.com/v1/image \

  -H “Authorization: Bearer $TRUTHSCAN_API_KEY” \

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

  -d ‘{

    “image_url”: “https://example.com/user-upload.jpg”,

    “include_heatmap”: true

  }’

Step 3: Read what comes back

You’ll typically get a verdict, a confidence score between 0 and 1, an explanation, and a heatmap reference. Read the score against your own thresholds instead of trusting the label alone:

{

  “id”: “scan_9f2c…”,

  “verdict”: “likely_ai_generated”,

  “confidence”: 0.94,

  “explanation”: “Generative artifacts in facial region; metadata inconsistent with camera capture.”,

  “heatmap_url”: “https://…/scan_9f2c_heatmap.png”

}

Step 4: Go async for video and batch jobs

For video or big batch runs, submit the media, take the job ID you get back immediately, and let the service call your webhook when the result is ready. Your request threads stay free and your users stay fast.

Step 5: Turn the score into a decision

This is the part that actually matters. Auto-approve below your low threshold, auto-reject above the high one, and send the narrow band in between to a human queue with the heatmap attached. That one pattern is what lets detection scale without adding friction for the real people using your product.

The Same Scan in Python and Node

Here it is in Python with the requests library. Notice the routing at the bottom bands, not a single cutoff:

import os, requests

resp = requests.post(

    “https://api.truthscan.com/v1/image”,

    headers={“Authorization”: f”Bearer {os.environ[‘TRUTHSCAN_API_KEY’]}”},

    json={“image_url”: image_url, “include_heatmap”: True},

    timeout=10,

)

resp.raise_for_status()

result = resp.json()

if result[“confidence”] >= 0.90:

    route_to_rejection(result)

elif result[“confidence”] >= 0.60:

    route_to_review(result)     # pass heatmap_url to the reviewer

else:

    auto_approve(result)

And the same thing in Node.js with fetch:

const res = await fetch(“https://api.truthscan.com/v1/image”, {

  method: “POST”,

  headers: {

    “Authorization”: `Bearer ${process.env.TRUTHSCAN_API_KEY}`,

    “Content-Type”: “application/json”,

  },

  body: JSON.stringify({ image_url: imageUrl, include_heatmap: true }),

});

const result = await res.json();

if (result.confidence >= 0.9) rejectSubmission(result);

else if (result.confidence >= 0.6) routeToReview(result);

else autoApprove(result);

If you’d rather not hand-roll the HTTP plumbing, check whether there’s an image detection client SDK for your language, it’ll take care of auth, retries, and file uploads for you.

Video and Voice Need a Little More Care

These formats deserve their own handling, partly because they’re heavier and partly because they’re where the scariest fraud is showing up.

One engineering firm lost roughly 25 million US dollars in 2024 after an employee joined a video call where every other “colleague” on the screen, including the CFO, was a deepfake. That’s the threat your video path is really up against.

For recorded or streamed video, submit to the video detection endpoint and read the result off a webhook. For audio, the voice detection API scores speech for synthetic signatures.

And if you run live channels video KYC, call-center verification look at a real-time detection setup so the scoring happens during the interaction instead of after everyone’s hung up.

Getting it Ready for Real Traffic

Speed and throughput

For in-line checks, aim to keep the whole round trip under two seconds so honest users never feel it.

Call the API asynchronously wherever the flow allows, and load-test at your actual peak not your average because a detector that’s snappy on one image can back up badly under a flood of concurrent uploads.

Living with false positives

No detector is perfect, and a false positive lands on a real customer, which is expensive in a different way. So treat the score as a signal, not a sentence.

Keep your auto-reject threshold conservative, route the gray zone to a person, and, once you’re at volume, ask about models tuned on your own submission patterns they push the false-positive rate down as you grow.

Security and compliance

If you’re handling identity or health data, your detection vendor becomes part of your own compliance story. Confirm SOC 2 Type II and ISO 27001, GDPR-aligned processing, and when you need it regional or on-prem deployment plus a zero-data-retention option.

And log every verdict with its score and heatmap, so the decision is still defensible months later when someone asks why you made it.

Mistakes we see teams make

  • Treating the score as binary. A 0.55 and a 0.98 are very different situations. Use bands.
  • Scanning after the fact. Catching a fake receipt after you refunded the money defeats the point. Score before the payout.
  • Ignoring the heatmap. That visual evidence is what wins the dispute and satisfies the auditor. Store it.
  • Wiring up only one media type. Fraud rarely arrives as a single clean file. Plan for images and documents and often video and voice from day one.
  • Skipping the load test. Fast on one request tells you nothing about ten thousand at once.

When things break: retries and failing safe

Real traffic is messy. Networks time out, files arrive half-uploaded, rate limits kick in mid-spike. Plan for it.

Put a timeout on every call, retry the transient failures (429s and 5xxs) with exponential backoff, and decide in advance what an unavailable detector should do hold the submission for review, or let it through? Make that a deliberate policy, not the accidental behavior of an unhandled exception.

Use an idempotency key so a retried request doesn’t double-charge or create duplicate scans, and store the scan ID from each response against your own record so you can reconcile later. A minimal retry wrapper in Python:

import time, requests

def scan_with_retry(payload, attempts=3):

    for i in range(attempts):

        try:

            r = requests.post(URL, headers=HEADERS, json=payload, timeout=10)

            if r.status_code in (429, 500, 502, 503):

                time.sleep(2 ** i)      # backoff: 1s, 2s, 4s

                continue

            r.raise_for_status()

            return r.json()

        except requests.Timeout:

            time.sleep(2 ** i)

    raise RuntimeError(“detection unavailable”)  # apply your fail-safe policy

Questions developers actually ask us

Which file types can it handle?

Images (JPEG, PNG, WebP), PDFs, video, and audio each through its own endpoint. Since one fraud case often spans more than one, plan to call a couple of endpoints rather than expecting one to cover everything.

How fast is it, really?

For images and single-page PDFs, figure on roughly one to two seconds end to end, fast enough to run in-line at upload. Video and batch jobs take longer, which is exactly why you hand them off to a webhook.

Will it slow my users down?

Not if you place it well. Score in-line only where a decision depends on it, keep the clean path instant, and send only flagged media to review. Most people never notice a thing.

What do I do about false positives?

Use bands, send the middle to a human with the heatmap, and, at scale, ask about custom-tuned models. Never auto-reject on a borderline score by itself.

Is my data safe?

Pick a vendor with SOC 2 Type II, ISO 27001, and GDPR-aligned processing. For sensitive data, look for regional or on-prem deployment and a zero-data-retention option and get it in the contract.

What it costs as you grow

Per-scan price is the number that matters at volume, and it should fall as you scale. TruthScan meters by the scan one image or one PDF page with rates that drop from a few cents on the entry tiers toward a fraction of a cent at enterprise volume, plus a free tier so you can test before you commit.

If you’re weighing detectors on cost, accuracy, and speed together, we put the trade-offs side by side in our detection API comparison.

Ready to start building?

None of this is a research project anymore. It’s a few well-placed API calls and a sensible routing policy. Start with one image endpoint, check the response against your own traffic, add documents and video once you trust it, and tune your thresholds as you learn what your real fraud looks like.

Generate a key and dig into the detection API documentation, or book a technical walkthrough and we’ll help you design the integration around your workflow.

Copyright © 2025 TruthScan. All Rights Reserved