> Complete API documentation for TruthScan's AI image detection API. Learn how to integrate our API into your applications.

Source: https://truthscan.com/truthscan-ai-image-detection-api-documentation
Documentation index: https://truthscan.com/llms.txt
Plans and pricing: https://truthscan.com/pricing

For AI agents: the documentation index is at <https://truthscan.com/llms.txt> and a Markdown version of this page is at <https://truthscan.com/truthscan-ai-image-detection-api-documentation.md> and the OpenAPI spec is at <https://truthscan.com/openapi/image.json>.

API Documentation

[![ISO 27001](https://truthscan.com/_next/image?url=%2Fimages%2Fcertifications%2Fiso-27001.webp&w=256&q=75&dpl=dpl_Dh67afZ51B2ixD2rNhn7885kcKAC)](https://trust.truthscan.com/?lang=en)

[![SOC 2 Certified](https://truthscan.com/_next/image?url=%2Fimages%2Fcertifications%2Fsoc2.webp&w=256&q=75&dpl=dpl_Dh67afZ51B2ixD2rNhn7885kcKAC)](https://trust.truthscan.com/?lang=en)

[![GDPR Compliant](https://truthscan.com/_next/image?url=%2Fimages%2Fcertifications%2Fgdpr.webp&w=256&q=75&dpl=dpl_Dh67afZ51B2ixD2rNhn7885kcKAC)](https://trust.truthscan.com/?lang=en)

[![GASA Partner](https://truthscan.com/_next/image?url=%2Fimages%2Fcertifications%2Fgasa.png&w=256&q=75&dpl=dpl_Dh67afZ51B2ixD2rNhn7885kcKAC)](https://gasa.org/knowledge-base/blog/global-anti-scam-alliance-partners-with-truthscan-to-integrate-deepfake-detection-on-scam.org)

# AI Image Detection API

Complete documentation for integrating TruthScan's AI image detection API into your applications.

Try it out without code by visiting our FastAPI endpoint: <https://detect-image.truthscan.com/docs>

Prefer a client library? Use our official SDKs instead of calling the REST API directly. [View Client SDK Documentation](https://truthscan.com/truthscan-ai-image-detection-client-sdk-documentation)

Pricing & credits

Each successful image detection consumes credits. Bulk ZIP uploads bill only images that complete analysis; skipped or failed files are not charged.

Check your balance with `GET /check-user-credits`. [View pricing plans](#pricing-plans)

## Authentication

TruthScan uses API keys to allow access to the API. You can get your API key at the [top of the page in our developer portal](https://truthscan.com/account).

TruthScan expects the API key to be included in API requests to the server in a JSON body like the following (unless an endpoint documents header-only auth, e.g. check-user-credits):

```json
{
  "key": "YOUR API KEY GOES HERE"
}
```

You must replace YOUR API KEY GOES HERE with your personal API key.

## Rate Limits

The API enforces a per-minute request budget for each API key. Heavier write endpoints cost more than lighter read endpoints. The default limit is 250 requests per minute — contact us if you need a higher limit.

### Endpoint weights

Each call deducts its weight from your per-minute budget:

| Endpoint                | Type  | Weight           |
| ----------------------- | ----- | ---------------- |
| POST /detect            | Write | 1                |
| POST /bulk-upload       | Write | 1                |
| GET /get-presigned-url  | Read  | 0.2              |
| GET /check-user-credits | Read  | 0.2              |
| POST /heatmap/{id}      | Read  | 0.2              |
| POST /preview/{id}      | Read  | 0.2              |
| POST /query             | Read  | Not rate-limited |
| GET /health             | Read  | Not rate-limited |

Example: with a 250/minute budget, you can send up to 250 write calls, or up to \~1,250 read calls, or any mix where the weighted total stays ≤ 250 per minute.

### Throttled response (HTTP 429)

When you exceed your per-minute budget, the API returns:

```http
HTTP/1.1 429 Too Many Requests
X-RateLimit-Limit: 250
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 3
X-RateLimit-Retry-After: 3
Content-Type: application/json

{
  "error": "Too many requests"
}
```

Rate-limit response headers

- X-RateLimit-Limit — your per-minute capacity.
- X-RateLimit-Remaining — calls remaining for the current minute (after this request).
- X-RateLimit-Reset — (only on 429) seconds until you can send another write request.
- X-RateLimit-Retry-After — (only on 429) same value as X-RateLimit-Reset, returned in Retry-After style.

Recommended client behavior

- Watch X-RateLimit-Remaining on successful responses to pace your requests.
- On a 429, wait at least X-RateLimit-Retry-After seconds before retrying — use exponential backoff with jitter.
- For batches, prefer POST /bulk-upload (one call processes up to 50 images) over many parallel /detect calls.

## AI Image Detector

### Detect (3-Step Process)

The AI Image Detection workflow consists of the following steps:

- Obtain a Pre-signed Upload URL
- Upload the Image
- Submit the Image for Detection

#### 1\. Obtain a Pre-signed Upload URL

Begin by requesting a pre-signed URL from the API. This URL allows you to securely upload your image file to the storage server.

Supported File Formats

JPG, JPEG, PNG, WebP, JFIF, HEIC, HEIF, AVIF, BMP, TIFF, TIF, GIF, SVG, PDF

Filename

Remove spaces from the image filename when requesting a pre-signed URL.

For PDF files, only the first image will be detected (single-file flow).

Use a .zip filename on this endpoint when you intend to submit a ZIP via bulk upload.

Query parameters

- file\_name (required) — Original filename; the server may normalize it (spaces and unsafe characters are adjusted). Use a .zip extension for bulk upload.
- expiration (optional) — Presigned URL lifetime in seconds (default: 3600).

```bash
GET https://detect-image.truthscan.com/get-presigned-url?file_name=example.jpg
```

Example Request

```bash
curl -X GET 'https://detect-image.truthscan.com/get-presigned-url?file_name=example.jpg' \
--header 'apikey: YOUR API KEY GOES HERE'
```

Example Response

```json
{
  "status": "success",
  "presigned_url": "https://nyc3.digitaloceanspaces.com/ai-image-detector-dev/uploads/581d47c7-3ef4-42af-88d9-6dab6bf69389_20250611-121955_example.jpg...",
  "file_path": "uploads/example.jpg",
  "document_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
}
```

The document\_id is a new UUID generated for this upload request (for correlation/logging). The id you use for /detect or /bulk-upload is assigned when you submit those endpoints unless you pass an optional id on /detect.

HTTP responses

Required header: `apikey: YOUR-API-KEY-GOES-HERE`

| Status | Body                                                   | When                               |
| ------ | ------------------------------------------------------ | ---------------------------------- |
| 200    | JSON: status, presigned\_url, file\_path, document\_id | Success                            |
| 400    | {"error": "..."}                                       | Unsupported file type / bad params |
| 403    | {"error": "..."}                                       | Invalid API key                    |
| 404    | {"error": "..."}                                       | TruthScan key validation failed    |
| 500    | {"error": "..."}                                       | Server error                       |

#### 2\. Upload the Image

Use the provided presigned\_url to upload your image via a PUT request. Ensure the correct Content-Type is set according to your image format.

Filename

Remove spaces from the image filename when uploading the image.

Set Content-Type to match your file extension exactly

- image/jpeg: jpg, jpeg, jfif
- image/png: png
- image/webp: webp
- image/heic: heic
- image/heif: heif
- image/avif: avif
- image/bmp: bmp
- image/tiff: tiff, tif
- image/gif: gif
- image/svg+xml: svg
- application/pdf: pdf

Common mistakes to avoid

- Do not use image/jpg (incorrect). Use image/jpeg.
- Do not mismatch file and header (e.g., .png file with image/jpeg).
- Do not change the extension without updating the header (or vice versa).
- Do not include spaces in filenames when requesting/uploading.

Example Request

```bash
curl -X PUT 'https://nyc3.digitaloceanspaces.com/ai-image-detector-dev/uploads/581d47c7-3ef4-42af-88d9-6dab6bf69389_20250611-121955_example.jpg...' \
  --header 'Content-Type: image/jpeg' \
  --header 'x-amz-acl: private' \
  --data-binary '@example.jpg'
```

Additional upload examples (PNG, PDF, SVG)

```bash
curl -X PUT '<PRESIGNED_URL_FOR_example.png>' \
  --header 'Content-Type: image/png' \
  --header 'x-amz-acl: private' \
  --data-binary '@example.png'
```

```bash
curl -X PUT '<PRESIGNED_URL_FOR_example.pdf>' \
  --header 'Content-Type: application/pdf' \
  --header 'x-amz-acl: private' \
  --data-binary '@example.pdf'
```

```bash
curl -X PUT '<PRESIGNED_URL_FOR_example.svg>' \
  --header 'Content-Type: image/svg+xml' \
  --header 'x-amz-acl: private' \
  --data-binary '@example.svg'
```

File Size Limits

- Minimum file size: 1KB
- Maximum file size: 10MB

Ensure that the file format remains consistent during the upload process. A successful upload returns HTTP 200.

Storage PUT response

Step 2 is a direct PUT to object storage (presigned URL), not our API. Single-image and ZIP bulk uploads behave the same way.

Success returns HTTP 200 with an empty body — by design. There is no JSON to parse.

After PUT to presigned\_url: treat res.ok (status 200–299) as success. Do not call response.json() on success — an empty body is expected. Surface errors only on non-2xx responses.

#### 3\. Submit Image for AI Detection

After uploading, submit the image for AI detection by referencing the file\_path from the previous step. For PDF uploads, only the first image will be analyzed/detected.

```bash
POST https://detect-image.truthscan.com/detect
```

Example Request

```bash
curl -X 'POST' \
  'https://detect-image.truthscan.com/detect' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -d '{
  "key": "YOUR-API-KEY-GOES-HERE",
  "url": "https://ai-image-detector-prod.nyc3.digitaloceanspaces.com/<FILE_PATH>",
  "generate_preview": true
}'
```

The FILE\_PATH refers to the path returned from the presigned-URL step (e.g. uploads/...). Build the full URL with your storage host as shown in the example.

Optional Parameters

- `id`: Optional UUID string. If omitted, the server generates a new document id. If provided, it must not already exist; otherwise the API returns an error.
- `generate_preview`: Set to true to generate a preview URL for the image (default: true). Set to false to skip preview generation.
- `document_type`: Type of document (default: Image).
- `email`: Email address for processing.
- `generate_analysis_details`: Set to false to skip generating detailed analysis (default: true).
- `generate_heatmap`: When false, skip heatmap generation entirely (default: true). Heatmaps are only produced for AI-classified images when this is true. Real images never receive a heatmap.
- `generate_heatmap_overlayed`: Controls how the heatmap image is produced when a heatmap is generated (default: true). Only applies when generate\_heatmap is true and the image is classified as AI-generated. When true, the heatmap is blended onto the original image (standard overlay). When false, the service returns a transparent heatmap: an RGBA image with the JET-colored activation map and alpha from the model, with a transparent background so you can composite it in your UI.
- `generate_heatmap_normalized`: When false, heatmap generation skips the normalization step used for the activation map (default: true). Only applies when generate\_heatmap is true and the image is classified as AI-generated. Use together with generate\_heatmap\_overlayed to control heatmap appearance.
- `model`: Model or routing hint (default: generic). Supported examples include generic or instance\_id/model (e.g. my-instance-id/generic) to send the job to a dedicated queue for that instance. Invalid instance\_id values are rejected with 400.
- `user_agent`: Optional string stored with the document for analytics/support.

Heatmap flag validation

If generate\_heatmap is false, do not explicitly set generate\_heatmap\_overlayed or generate\_heatmap\_normalized to true. The API returns 422 Unprocessable Entity with messages such as "generate\_heatmap\_overlayed cannot be true when generate\_heatmap is false." or "generate\_heatmap\_normalized cannot be true when generate\_heatmap is false."

Example Request (heatmap enabled, default)

```bash
curl -X 'POST' \
  'https://detect-image.truthscan.com/detect' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -d '{
  "key": "YOUR-API-KEY-GOES-HERE",
  "url": "https://ai-image-detector-dev.nyc3.digitaloceanspaces.com/uploads/example.jpg",
  "generate_heatmap": true,
  "generate_preview": false,
  "generate_analysis_details": false,
  "model": "generic"
}'
```

Example Request (heatmap disabled)

```bash
curl -X 'POST' \
  'https://detect-image.truthscan.com/detect' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -d '{
  "key": "YOUR-API-KEY-GOES-HERE",
  "url": "https://ai-image-detector-dev.nyc3.digitaloceanspaces.com/uploads/example.jpg",
  "generate_heatmap": false,
  "generate_preview": false,
  "generate_analysis_details": false,
  "model": "generic"
}'
```

Invalid Request (422)

```bash
curl -X 'POST' \
  'https://detect-image.truthscan.com/detect' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -d '{
  "key": "YOUR-API-KEY-GOES-HERE",
  "url": "https://ai-image-detector-dev.nyc3.digitaloceanspaces.com/uploads/example.jpg",
  "generate_heatmap": false,
  "generate_heatmap_overlayed": true
}'
```

Example Response

```json
{
    "id": "77565038-9e3d-4e6a-8c80-e20785be5ee9",
    "status": "pending"
}
```

The response includes a unique image ID for tracking the detection status.

HTTP responses

| Status | Body                                   | When                                                                                                    |
| ------ | -------------------------------------- | ------------------------------------------------------------------------------------------------------- |
| 200    | JSON: id, status (typically "pending") | Job accepted — this is what the API returns on success                                                  |
| 400    | {"error": "..."}                       | Validation (no URL, file not uploaded, size/type, duplicate id, bad model, heatmap flag conflict, etc.) |
| 403    | {"error": "..."}                       | Invalid key / insufficient credits                                                                      |
| 422    | {"error": "..."}                       | Invalid request body (e.g. generate\_heatmap\_overlayed true when generate\_heatmap is false)           |
| 500    | {"error": "..."}                       | Server error                                                                                            |

Treat any 2xx response whose JSON includes id and status as success — not only HTTP 200\. Proxies or other HTTP stacks may return 201 or 202 for async-accept patterns; validate the JSON body.

### Query Detection Status and Results

To check the status and retrieve the results, use the /query endpoint with the image ID.

Authentication: The request body only includes id; the API does not send an API key on this call. Anyone who knows the UUID can poll results—treat document IDs as sensitive if you need to restrict who can see scores.

HTTP responses

| Status | Body                             | When         |
| ------ | -------------------------------- | ------------ |
| 200    | Single-image or bulk result JSON | Found        |
| 404    | Error detail                     | Unknown id   |
| 500    | Error detail                     | Server error |

```bash
POST https://detect-image.truthscan.com/query
```

Example Request

```bash
curl -X 'POST' \
  'https://detect-image.truthscan.com/query' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -d '{
  "id": "IMAGE-ID-GOES-HERE"
}'
```

Example Response

```json
{
    "id": "00fee5ff-a55b-42fb-b7c7-d14f05ae0769",
    "status": "done",
    "result": 90.2371538185235,
    "result_details": {
        "is_valid": true,
        "detection_step": 3,
        "final_result": "AI Generated",
        "metadata": [
            "No Information Detected for Real/AI",
            "Could not find anything from ExifTool and Pillow metadata"
        ],
        "metadata_basic_source": "null",
        "ocr": [
            "OCR did not detect AI",
            0.0
        ],
        "ml_model": [
            "AI Generated",
            90.2371538185235
        ],
        "confidence": 90.2371538185235,
        "final_label_confidence": 90.2371538185235,
        "heatmap_status": "ready",
        "heatmap_url": "https://ai-image-detector-prod.nyc3.digitaloceanspaces.com/uploads/....",
        "analysis_results_status": "pending",
        "analysis_results": null,
        "warnings": [
            { "type": "blur_dark", "label": "Blurred" },
            { "type": "watermark", "label": "Gemini", "confidence": 0.95 },
            { "type": "screen_recapture", "label": "screen", "metrics": { "is_screen": false }, "confidence": 99.99 }
        ]
    },
    "preview_url": "https://ai-image-detector-prod.nyc3.digitaloceanspaces.com/previews/..."
}
```

Example Response (/query, secure URLs enabled on the org)

```json
{
    "id": "00fee5ff-a55b-42fb-b7c7-d14f05ae0769",
    "status": "done",
    "result": 90.2371538185235,
    "result_details": {
        "is_valid": true,
        "detection_step": 3,
        "final_result": "AI Generated",
        "confidence": 90.2371538185235,
        "final_label_confidence": 90.2371538185235,
        "heatmap_status": "ready",
        "heatmap_url": "https://ai-image-detector-prod.nyc3.digitaloceanspaces.com/uploads/00fee5ff-a55b-42fb-b7c7-d14f05ae0769",
        "analysis_results_status": "ready",
        "analysis_results": null
    },
    "preview_url": "https://ai-image-detector-prod.nyc3.digitaloceanspaces.com/previews/00fee5ff-a55b-42fb-b7c7-d14f05ae0769"
}
```

Example Response when analysis results are ready

```json
{
    "id": "00fee5ff-a55b-42fb-b7c7-d14f05ae0769",
    "status": "done",
    "result": 90.2371538185235,
    "result_details": {
        "heatmap_status": "ready",
        "heatmap_url": "https://ai-image-detector-prod.nyc3.digitaloceanspaces.com/uploads/....",
        "analysis_results_status": "ready",
        "analysis_results": {
            "imageTags": ["person", "portrait", "outdoor", "vineyard", "smiling"],
            "agreement": "strong",
            "confidence": 92,
            "keyIndicators": [
                "Unnaturally smooth skin texture",
                "Consistent lighting anomalies"
            ],
            "detailedReasoning": "The image shows clear signs of AI generation with unnaturally smooth textures and consistent lighting patterns not typical of real photography.",
            "visualPatterns": ["Uniform noise pattern typical of diffusion models"],
            "recommendations": [
                "Cross-reference with original source if available",
                "Check for metadata inconsistencies",
                "Compare with known AI generation patterns"
            ]
        }
    },
    "preview_url": "https://ai-image-detector-prod.nyc3.digitaloceanspaces.com/previews/..."
}
```

Result Details

- `is_valid`: Indicates if the image file is valid (true/false).
- `detection_step`: Stage at which detection completed: 1 = only metadata; 2 = metadata and ocr; 3 = metadata, ocr, and ml\_model.
- `result`: Stage 1 AI score, 0–100: the probability the image is AI-generated. It is always an AI probability, never confidence in the verdict, so a real photo scores low. It is not changed when Stage 2 labels an image edited, so do not use it to decide or display the outcome. Use \`final\_result\` with \`final\_label\_confidence\` instead.
- `final_result`: Overall determination (e.g. "AI Generated", "Real", "Digitally Edited", "AI Edited").
- `confidence`: When present, the same value as \`result\` (the Stage 1 AI score). Despite the name, it is not confidence in \`final\_result\`. Use \`final\_label\_confidence\` for that.
- `final_label_confidence`: How sure the model is of \`final\_result\`, from 0 to 100\. Read it as “this image is N% \[label\]”. Use this field, not \`result\`, to display or threshold a verdict. How it is calculated: \`"AI Generated"\` = the AI score; \`"Real"\` = 100 minus the AI score; \`"Digitally Edited"\` and \`"AI Edited"\` = the Stage 2 edit probability, which can differ from \`result\`. For example, \`"Real"\` with \`result\` \`20\` returns \`final\_label\_confidence\` \`80\` (80% confident the image is real). It can be absent or \`null\` on older detections: check that it is a non-null number before using it, and do not substitute \`result\` when it is absent or \`null\`.
- `metadata`: Information extracted from image metadata using ExifTool and Pillow.
- `metadata_basic_source`: May indicate whether the image was captured with a specific mobile camera model, generated by an AI tool, or modified with photo-editing software.
- `ocr`: Watermark-detection result under the historical field name ocr. Two-element array \[label, score\]: label is a detected watermark class (e.g. "Gemini") or "OCR did not detect AI"; score is on a 0–100 scale (or 0 when unsure). Summarized in warnings when a label is present.
- `ml_model`: Results from the machine learning model.
- `warnings`: Optional array of heterogeneous warning objects (type blur\_dark, watermark, screen\_recapture, etc.). May be empty or omitted. blur\_dark and screen\_recapture: both are good candidates for a Capture retake rather than a hard decision.
- `preview_url`: Preview image URL if generate\_preview was true. May be direct storage or, when secure URLs are enabled, an API path such as https://<api-host>/preview/<document\_id>.
- `heatmap_status`: pending, ready, or failed. Omitted when the image is not AI-generated or when generate\_heatmap was false on submit. Heatmap generation is asynchronous and only runs for AI-classified images when generate\_heatmap is true.
- `heatmap_url`: Present when heatmap\_status is ready, the image was AI-classified, and generate\_heatmap was enabled at submit time. Appearance depends on generate\_heatmap\_overlayed. May be direct storage or API path https://<api-host>/heatmap/<document\_id> (use POST /heatmap/{id} with key when secure).
- `analysis_results_status`: pending, ready, skipped, failed, or analyzing. Omitted or null when generate\_analysis\_details was false.
- `analysis_results`: Detailed narrative analysis when enabled; see Analysis Result Explanation below.

Analysis Result Explanation

When analysis\_results is ready, it typically includes: agreement (strong | moderate | weak | disagreement), imageTags (up to five short tags), confidence (0–100), keyIndicators, detailedReasoning, visualPatterns, and recommendations.

Notes

- Heatmap generation is asynchronous and only runs for AI-classified images when generate\_heatmap is true (default). Poll /query until heatmap\_status is ready.
- Detailed analysis is asynchronous unless generate\_analysis\_details=false. Poll for analysis\_results\_status and analysis\_results.
- Secure URLs: When enabled, heatmap\_url and preview\_url may use the API host; fetch with POST /heatmap/{id} and POST /preview/{id} with your key (see Secure heatmap and preview assets).
- Poll /query again after the main score is ready to pick up heatmap and analysis\_results when they finish.

Heatmap and overlay behavior

The file at heatmap\_url reflects generate\_heatmap\_overlayed and generate\_heatmap\_normalized from your /detect (or /bulk-upload) request when generate\_heatmap was true: default overlay (true) is a normal image with the heatmap overlaid; false is typically a PNG with transparency for compositing. Real images and requests with generate\_heatmap: false omit heatmap\_status and heatmap\_url.

Example Response (AI image, heatmap disabled at submit)

```json
{
    "id": "00fee5ff-a55b-42fb-b7c7-d14f05ae0769",
    "status": "done",
    "result": 90.2371538185235,
    "result_details": {
        "is_valid": true,
        "detection_step": 3,
        "final_result": "AI Generated",
        "confidence": 90.2371538185235,
        "final_label_confidence": 90.2371538185235
    }
}
```

Example Response (AI image, heatmap pending)

```json
{
    "id": "00fee5ff-a55b-42fb-b7c7-d14f05ae0769",
    "status": "done",
    "result": 90.2371538185235,
    "result_details": {
        "is_valid": true,
        "detection_step": 3,
        "final_result": "AI Generated",
        "confidence": 90.2371538185235,
        "final_label_confidence": 90.2371538185235,
        "heatmap_status": "pending",
        "heatmap_url": null
    }
}
```

Example: result \~90.24 with final\_result AI Generated and detection\_step 3 means full pipeline metadata, OCR, and ML model completed. A real photo might instead return result 20, final\_result Real, and final\_label\_confidence 80: the AI score is low because the image is real, and the verdict to display is “80% real”. For Digitally Edited and AI Edited images, result stays the Stage 1 AI score while final\_label\_confidence is the Stage 2 edit probability.

### Handling flagged results

Beta

The API returns a classification and a confidence, not a decision. Most production integrations use three bands. Below your lower threshold, auto-approve. Above your upper threshold, route to review with the heatmap and analysis\_results attached. Between the two, request a live retake with TruthScan Capture (beta) before involving a reviewer.

A Capture request is a good fit whenever the result is uncertain or the image itself is the problem: final\_label\_confidence in your middle band, analysis\_results.agreement of weak or disagreement, or a warnings entry of blur\_dark or screen\_recapture. In each case the cheapest resolution is a fresh photo taken live on the submitter's device, not a human judgment on a poor one.

Capture returns a new detection result linked to the original request id, so your decision layer sees both. During beta, Capture is enabled per account.

[Get Capture beta access](https://truthscan.com/contact?interest=capture-beta#contact-form)

```python
result = client.detect(image)
conf = result.result_details.final_label_confidence
if conf < LOWER:            approve(result)
elif conf > UPPER:          route_to_review(result)
else:                       # gray band, or warnings / weak agreement
    capture = client.capture.request(result.request_id, contact=submitter)
    # poll capture.request_id for the linked, verified result
```

### Analysis Results (Asynchronous Deep Analysis)

When generate\_analysis\_details is true in /detect, detailed analysis may complete after the main score. Poll /query until analysis\_results\_status is ready (or skipped/failed).

#### 1\. Initial result may be ready before analysis

Core detection (result, final\_result, confidence) can be done while analysis\_results\_status is still pending.

```json
{
    "id": "00fee5ff-a55b-42fb-b7c7-d14f05ae0769",
    "status": "done",
    "result": 90.2371538185235,
    "result_details": {
        "is_valid": true,
        "detection_step": 3,
        "final_result": "AI Generated",
        "confidence": 90.2371538185235,
        "final_label_confidence": 90.2371538185235,
        "analysis_results_status": "pending",
        "analysis_results": null
    }
}
```

What to do

Use core fields immediately; keep polling if you need analysis\_results.

#### 2\. Keep polling

Call /query with the same id until analysis\_results\_status changes from pending.

```bash
curl -X 'POST' \
  'https://detect-image.truthscan.com/query' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -d '{
  "id": "00fee5ff-a55b-42fb-b7c7-d14f05ae0769"
}'
```

#### 3\. Analysis complete

When analysis\_results\_status is ready, analysis\_results includes agreement, imageTags, confidence, keyIndicators, detailedReasoning, visualPatterns, and recommendations.

```json
{
    "id": "00fee5ff-a55b-42fb-b7c7-d14f05ae0769",
    "status": "done",
    "result": 90.2371538185235,
    "result_details": {
        "is_valid": true,
        "detection_step": 3,
        "final_result": "AI Generated",
        "confidence": 90.2371538185235,
        "final_label_confidence": 90.2371538185235,
        "heatmap_status": "ready",
        "heatmap_url": "https://ai-image-detector-prod.nyc3.digitaloceanspaces.com/uploads/....",
        "analysis_results_status": "done",
        "analysis_results": {
            "imageTags": [
                "person",
                "portrait",
                "outdoor",
                "vineyard",
                "smiling"
            ],
            "agreement": "strong",
            "confidence": 92,
            "keyIndicators": [
                "Unnaturally smooth skin texture",
                "Consistent lighting anomalies"
            ],
            "detailedReasoning": "The image shows clear signs of AI generation with unnaturally smooth textures and consistent lighting patterns not typical of real photography.",
            "visualPatterns": [
                "Uniform noise pattern typical of diffusion models"
            ],
            "recommendations": [
                "Cross-reference with original source if available",
                "Check for metadata inconsistencies",
                "Compare with known AI generation patterns"
            ]
        }
    },
    "preview_url": "https://ai-image-detector-prod.nyc3.digitaloceanspaces.com/previews/..."
}
```

#### When analysis is not available

If analysis\_results\_status is skipped, failed, or absent, or generate\_analysis\_details was false, treat core detection as final.

```json
{
    "status": "done",
    "result": 12.5,
    "result_details": {
        "analysis_results_status": "skipped",
        "analysis_results": null
    }
}
```

Analysis Results Fields

- analysis\_results\_status: pending | ready | skipped | failed | analyzing
- analysis\_results.agreement: strong | moderate | weak | disagreement
- analysis\_results.imageTags: short descriptive tags
- analysis\_results.confidence: 0–100
- analysis\_results.keyIndicators: specific cues
- analysis\_results.detailedReasoning: short explanation
- analysis\_results.visualPatterns: broader patterns
- analysis\_results.recommendations: next steps

### Bulk Upload (ZIP)

Submit multiple images in one request by uploading a ZIP. Workflow mirrors single-image: presign (ZIP name) → PUT ZIP → POST /bulk-upload → poll /query.

#### 1\. Obtain a Pre-signed Upload URL (ZIP)

Use get-presigned-url with a .zip filename (e.g. images.zip).

```bash
GET https://detect-image.truthscan.com/get-presigned-url?file_name=images.zip
```

Example Request

```bash
curl -X GET 'https://detect-image.truthscan.com/get-presigned-url?file_name=images.zip' \
--header 'apikey: YOUR API KEY GOES HERE'
```

#### 2\. Upload the ZIP

PUT the ZIP to the presigned URL with Content-Type: application/zip.

```bash
curl -X PUT '<PRESIGNED_URL_FOR_images.zip>' \
  --header 'Content-Type: application/zip' \
  --header 'x-amz-acl: private' \
  --data-binary '@images.zip'
```

ZIP Limits

- Maximum ZIP size: 100MB
- Maximum images per bulk: 50
- Per-image limits: minimum 1KB, maximum 10MB

Supported formats inside ZIP

JPG, JPEG, PNG, WebP, JFIF, HEIC, HEIF, AVIF, BMP, TIFF, TIF, GIF, SVG

PDF files inside the ZIP are not supported and will be skipped.

SVG files are converted to PNG before detection.

#### 3\. Submit ZIP for Bulk Detection

POST /bulk-upload with key and url pointing to the uploaded ZIP path.

Optional Parameters

- `generate_preview`: Set to true to generate preview URLs for images (default: false).
- `generate_analysis_details`: Set to true to generate detailed analysis (default: false).
- `generate_heatmap`: When false, skip heatmap generation entirely (default: true). Heatmaps are only produced for AI-classified images when this is true. Real images never receive a heatmap.
- `generate_heatmap_overlayed`: Same behavior as /detect (overlay vs transparent RGBA heatmap). Only applies when generate\_heatmap is true and the image is classified as AI-generated.
- `generate_heatmap_normalized`: Same behavior as /detect (default: true). Only applies when generate\_heatmap is true and the image is classified as AI-generated.
- `model`: Model domain: generic or instance\_id/model format.

Heatmap flag validation

If generate\_heatmap is false, do not explicitly set generate\_heatmap\_overlayed or generate\_heatmap\_normalized to true. The API returns 422 Unprocessable Entity with messages such as "generate\_heatmap\_overlayed cannot be true when generate\_heatmap is false." or "generate\_heatmap\_normalized cannot be true when generate\_heatmap is false."

Example Request

```bash
curl -X 'POST' \
  'https://detect-image.truthscan.com/bulk-upload' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -d '{
  "key": "YOUR-API-KEY-GOES-HERE",
  "url": "https://ai-image-detector-prod.nyc3.digitaloceanspaces.com/<FILE_PATH>",
  "generate_preview": false,
  "generate_analysis_details": false,
  "model": "generic"
}'
```

Example Response

```json
{
    "id": "77565038-9e3d-4e6a-8c80-e20785be5ee9",
    "status": "pending",
    "expected_count": 12
}
```

Returns id, status pending, and expected\_count (how many images from the ZIP will be analyzed).

HTTP responses

| Status | Body                                   | When                    |
| ------ | -------------------------------------- | ----------------------- |
| 200    | JSON: id, status, expected\_count      | Bulk job accepted       |
| 400    | {"error": "..."} (may include skipped) | ZIP validation failures |
| 403    | {"error": "..."}                       | Auth / credits          |
| 500    | {"error": "..."}                       | Server error            |

Same rule as /detect: any 2xx with id, status, and expected\_count (when present) is success.

How bulk ZIP results update

- After submit, status is pending until processing begins, then analyzing.
- results lists each image; pending entries have result and result\_details null until done.
- Optional heatmaps and analysis details may still be pending inside result\_details until ready.
- When every image in results has finished, overall status becomes done. If the batch cannot complete, status may be failed.
- You can call /query before the ZIP finishes to see partial results.

#### 4\. Query Bulk Upload Results

Use POST /query with the id from /bulk-upload. Same endpoint as single-image; response shape depends on whether the id is a single image or a ZIP batch.

```bash
curl -X 'POST' \
  'https://detect-image.truthscan.com/query' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -d '{
  "id": "77565038-9e3d-4e6a-8c80-e20785be5ee9"
}'
```

Example Response (still processing)

```json
{
  "id": "3b81fb24-dd23-40e7-ae95-82f823f44098",
  "status": "analyzing",
  "results": [
    {
      "id": "4600c7e5-00ec-469d-9117-ff20e0f1c1fa",
      "status": "done",
      "result": 44.0006,
      "result_details": {},
      "filename": "photo1.jpg",
      "preview_url": null
    },
    {
      "id": "2f770c89-352a-4d53-b6a3-a2147ca2c0ae",
      "status": "pending",
      "result": null,
      "result_details": null,
      "filename": "photo2.jpg",
      "preview_url": null
    }
  ],
  "skipped": []
}
```

Response fields (bulk ZIP)

- id — Bulk request id.
- status — pending, then analyzing, then done or failed.
- results — One entry per image being analyzed (id, status, result, result\_details, filename, preview\_url when available).
- skipped — Files not analyzed (unsupported type, size, etc.) with status failed and reason in result\_details.

Billing: Credits are used only for images successfully analyzed. Failed SVG conversions and skipped files are not billed.

### Secure heatmap and preview assets

When heatmap\_url or preview\_url in /query point to API host (not direct object storage), download the bytes with POST and your key.

POST /heatmap/{id}

POST /preview/{id}

Request body JSON: { "key": "YOUR-API-KEY-GOES-HERE" }

Heatmap responses (check HTTP status and Content-Type)

- 200 + binary (image/png, etc.) — Heatmap file available. X-Heatmap-Status may be set.
- 202 + JSON — heatmap\_status pending; poll /query and retry.
- 200 + JSON — No heatmap to serve (optional feature, failed, etc.); not a server error.
- 500 + JSON — Stored heatmap\_url exists but file could not be downloaded from storage; retry later.
- 404 + JSON — Document id not found.
- 403 + JSON — API key does not own this document.

Preview: POST /preview/{id} returns raw preview bytes. 404 with JSON if no preview was generated (generate\_preview was false).

Examples

```bash
curl -X POST 'https://detect-image.truthscan.com/heatmap/00fee5ff-a55b-42fb-b7c7-d14f05ae0769' \
  -H 'Content-Type: application/json' \
  -d '{"key":"YOUR-API-KEY-GOES-HERE"}' \
  --output heatmap.png
```

```bash
curl -X POST 'https://detect-image.truthscan.com/preview/00fee5ff-a55b-42fb-b7c7-d14f05ae0769' \
  -H 'Content-Type: application/json' \
  -d '{"key":"YOUR-API-KEY-GOES-HERE"}' \
  --output preview.png
```

### Check User Credits

This endpoint accepts the user's apikey via the header and returns credit details.

```bash
GET https://detect-image.truthscan.com/check-user-credits
```

Example Request

```bash
curl -X 'GET' \
  'https://detect-image.truthscan.com/check-user-credits' \
  -H 'apikey: YOUR API KEY GOES HERE' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json'
```

Example Response

```json
{
    "baseCredits": 10000,
    "boostCredits": 1000,
    "credits": 11000
}
```

For external integrations, only the credits field will be populated.

## Health Check

Check the health status of the API server.

```bash
GET https://detect-image.truthscan.com/health
```

Example Request

```bash
curl -X 'GET' \
  'https://detect-image.truthscan.com/health' \
  -H 'accept: application/json'
```

Example Response

```json
{
    "status": "healthy"
}
```

A "healthy" response indicates the service is operating normally.

## Errors

Most errors will be from incorrect parameters being sent to the API. Double-check each call and try the provided examples.

The generic error codes we use conform to the REST standard:

| Error Code | Meaning                                                                                                                                                                                                            |
| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| 400        | Bad Request -- Your request is invalid.                                                                                                                                                                            |
| 401        | Unauthorized -- Invalid job secret (internal usage endpoints) or similar auth failure.                                                                                                                             |
| 403        | Forbidden -- The API key is invalid, access denied, or there aren't sufficient credits for the operation.                                                                                                          |
| 404        | Not Found -- The specified resource doesn't exist.                                                                                                                                                                 |
| 405        | Method Not Allowed -- You tried to access a resource with an invalid method.                                                                                                                                       |
| 406        | Not Acceptable -- You requested a format that isn't JSON.                                                                                                                                                          |
| 410        | Gone -- The resource at this endpoint has been removed.                                                                                                                                                            |
| 422        | Invalid Request Body -- Your request body is formatted incorrectly, invalid, or has missing parameters.                                                                                                            |
| 429        | Too Many Requests -- You exceeded your per-API-key rate limit (see Rate Limits). The body is {"error":"Too many requests"}; the X-RateLimit-Retry-After header tells you how many seconds to wait before retrying. |
| 500        | Internal Server Error -- We had a problem with our server. Try again later.                                                                                                                                        |
| 503        | Service Unavailable -- We're temporarily offline for maintenance. Please try again later.                                                                                                                          |

## Common Issues and Solutions

### Authentication Issues

#### "User verification failed" (403)

**Cause:** Invalid or expired API key

**Solution:**

1. Verify your API key is correct
2. Check if your API key is active in your account
3. Try regenerating your API key

#### "Not enough credits" (403)

**Cause:** Insufficient credits for image processing

**Solution:**

1. Check your remaining credits using /check-user-credits
2. Purchase additional credits if needed

### Input Validation Issues

#### "Input URL cannot be empty" (400)

**Cause:** Empty or invalid URL submitted

**Solution:**

1. Ensure your url input is not empty
2. Remove leading/trailing whitespace in image names
3. Check URL encoding is correct

#### "Input email is empty" (400)

**Cause:** Missing email for URL processing

**Solution:**

1. Provide a valid email address when submitting URLs
2. Check email format is correct

#### "Unsupported image type" (400)

**Cause:** File format not supported

**Solution:**

1. Convert to a supported format (JPG, PNG, WebP, HEIC, HEIF, AVIF, BMP, TIFF, GIF, SVG, PDF)
2. Check file extension is correct

#### "File size is too small" (400)

**Cause:** Image file is below minimum size requirement

**Solution:**

1. Use a larger image file (minimum 1KB)
2. Check if the image was corrupted during upload

#### "File size exceeds limit" (400)

**Cause:** Image file is too large

**Solution:**

1. Compress or resize the image; the maximum size is set per deployment (the API error message states the limit in MB)
2. Use a different image format

#### "Invalid file type" (400)

**Cause:** File type validation failed

**Solution:**

1. Ensure the file is a valid image format
2. Check the file is not corrupted
3. Verify MIME type matches file extension

### Processing Issues

#### Image status "failed"

**Cause:** Processing failed for various reasons

**Solution:**

1. Verify URL is in a supported format
2. Check the image file is valid and not corrupted
3. Ensure the image meets size requirements
4. Contact support if the issue persists

#### "User not found"

**Cause:** Invalid user ID

**Solution:**

1. Verify user ID is correct
2. Ensure user account is active
3. Re-authenticate if needed

#### "File metadata could not be fetched" (500)

**Cause:** Unable to access uploaded file

**Solution:**

1. Verify file was uploaded successfully
2. Check file URL is accessible
3. Try re-uploading the file

#### Result is AI Generated but the submitter says the photo is real

Check final\_label\_confidence and analysis\_results.agreement first; a mid-range confidence or a weak agreement means the model is not certain. Check warnings for blur\_dark or screen\_recapture, which often explain a poor score on a real photo. In either case, request a live retake through TruthScan Capture rather than making a final call on the original. If the retake also flags, route to review with both results attached.

### Upload Issues

#### "Image upload failed" (403/400)

**Cause:** Invalid or expired pre-signed URL, or issues with the storage server

**Solution:**

1. Use the pre-signed URL promptly after receiving it
2. Verify Content-Type matches the file format
3. Remove spaces from the filename before upload
4. Generate a new pre-signed URL if needed

#### "Invalid pre-signed URL" (400)

**Cause:** Filename with spaces or expired/corrupted pre-signed URL

**Solution:**

1. Remove spaces from the filename before requesting a pre-signed URL
2. Use alphanumeric characters, hyphens, and underscores
3. Generate a new pre-signed URL if needed

### Bulk Upload Issues

#### "URL must point to a ZIP file" (400)

**Cause:** The URL provided to /bulk-upload does not point to a ZIP file

**Solution:**

1. Use get-presigned-url?file\_name=images.zip (or another .zip filename)
2. Upload a valid ZIP to the presigned URL
3. Ensure the bulk-upload request url points to that uploaded ZIP

#### "ZIP file too large" (400)

**Cause:** ZIP exceeds maximum size (100MB)

**Solution:**

1. Reduce the number of images or compress them
2. Split into multiple bulk uploads

#### "Too many files" (400)

**Cause:** ZIP contains more than 50 valid images

**Solution:**

1. Reduce to 50 or fewer images per ZIP
2. Split into multiple bulk uploads

#### "No valid images found in ZIP" (400)

**Cause:** All files in the ZIP were skipped (unsupported format, too small, invalid path, etc.)

**Solution:**

1. Use supported formats (JPG, PNG, WebP, HEIC, HEIF, AVIF, BMP, TIFF, TIF, GIF, SVG)
2. PDF is not supported in bulk
3. Each image must be at least 1KB and at most 10MB
4. Avoid hidden files (names starting with .) and path traversal (..)

#### "Document is not a bulk upload (image-zip) result" (400)

**Cause:** The id does not match that upload type (single image vs ZIP batch)

**Solution:**

1. Use the id from /detect for single-image submissions
2. Use the id from /bulk-upload for ZIP submissions

## API Frequently Asked Questions

Find answers to the most common questions about our AI image detection API.

### Which score should I use to show or decide a result?

Use result\_details.final\_result for the verdict and result\_details.final\_label\_confidence (0–100) for how sure the model is of it, for example “80% Real”. The top-level result is only the Stage 1 AI-generated probability: a real image has a low result, and for Digitally Edited or AI Edited images it can differ from final\_label\_confidence. final\_label\_confidence can be absent or null on older detections; check that it is a non-null number before using it, and if it is not, do not substitute result.

### How do I get an API key?

You can get your API key in your TruthScan account (developer portal). The API key is available at the top of your account page.

### What image formats are supported?

JPG, JPEG, PNG, WebP, JFIF, HEIC, HEIF, AVIF, BMP, TIFF, TIF, GIF, SVG, and PDF. For PDF, only the first image is detected/analyzed in the single-file flow. PDF inside ZIP bulk uploads is skipped.

### What are the file size limits?

Single files: minimum 1KB, maximum 10MB. ZIP bulk: up to 100MB per archive, up to 50 images per batch, each image 1KB–10MB.

### How does the 3-step process work?

1) Get a pre-signed upload URL, 2) Upload with PUT and correct Content-Type, 3) POST /detect with key and url built from your file\_path. Use /query to poll results.

### What are generate\_preview and generate\_analysis\_details defaults?

Per the upstream API: generate\_preview defaults to true; generate\_analysis\_details defaults to true. Set them explicitly if you need different behavior.

### How do bulk ZIP uploads work?

Request a presigned URL for a .zip file, upload the ZIP, POST /bulk-upload, then poll /query with the returned id. PDFs inside the ZIP are skipped; SVGs are converted to PNG.

### How does the credits system work?

Each successful image detection consumes credits. Check /check-user-credits. Bulk billing: credits apply only to successfully analyzed images; skipped files are not billed.

### What are the detection\_step values?

1 = metadata only; 2 = metadata and ocr; 3 = metadata, ocr, and ml\_model (full pipeline).

### What are analysis\_results and how do I use them?

When generate\_analysis\_details is true, poll /query for analysis\_results\_status. When ready, analysis\_results includes agreement, imageTags, confidence, keyIndicators, detailedReasoning, visualPatterns, and recommendations.

### What should I do when a real photo is flagged?

Do not auto-deny on a single result. Route borderline scores to review, or send the submitter a TruthScan Capture link to retake the photo live. See Handling flagged results.

### Is there a rate limit for API requests?

Yes. Each API key has a per-minute request budget — 250 requests per minute by default. Write endpoints (/detect, /bulk-upload) count as weight 1; read endpoints (/get-presigned-url, /check-user-credits, /heatmap/{id}, /preview/{id}) count as weight 0.2\. /query and /health are not rate-limited. When you exceed the budget you receive HTTP 429 with X-RateLimit-Retry-After. Contact us if you need a higher limit.
