API Documentation

Complete guide to using the Khoj Fact-Checking API

API Key Required

This documentation is publicly available. However, to get an API key and use the API, you need to log in with Google.

Overview

The Khoj Fact-Checking API provides third-party developers with access to our AI-powered fact-checking pipeline. This API allows you to integrate fact-checking capabilities into your own applications, websites, or services.

Features

  • AI-powered fact-checking in Bengali and English
  • Detailed reports with sources and verdicts
  • Tiered source verification system
  • Geography-aware fact-checking (Bangladesh vs International)
  • Related articles from Khoj database
  • Full CORS support for cross-origin requests
  • Rate limiting and API key authentication
  • Comprehensive error handling

Quick Start

1. Get API Access

To obtain an API key, simply log in with your Google account and visit the Get API Key page. You can request a unique API key directly from the platform without contacting support.

2. Make Your First Request

With API Key (Production):

curl -X POST https://khoj-bd.com/api/v1/factcheck \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -d '{"query": "বাংলাদেশে করোনা ভ্যাকসিনের পার্শ্বপ্রতিক্রিয়া আছে"}'

Without API Key (Development - requires API_AUTH_REQUIRED=false):

curl -X POST https://khoj-bd.com/api/v1/factcheck \
  -H "Content-Type: application/json" \
  -d '{"query": "বাংলাদেশে করোনা ভ্যাকসিনের পার্শ্বপ্রতিক্রিয়া আছে"}'

Authentication

By Default: API Key is REQUIRED

The API requires authentication by default for security. You can provide your API key using either of these methods:

Method 1: Authorization Header (Recommended)

Authorization: Bearer <your-api-key>

Method 2: X-API-Key Header

X-API-Key: <your-api-key>

✅ API Key Format & Handling

API Key Format: API keys are 11-character alphanumeric strings (e.g., K7D9PX4LQTA).

Whitespace Handling: The API automatically trims whitespace from API keys, so you don't need to worry about extra spaces when copying keys.

Getting Your API Key: Log in with Google and visit https://khoj-bd.com/get-api-key to get your unique API key.

💡 Testing Without API Key (Development Only)

For development and testing, you can disable authentication by setting API_AUTH_REQUIRED=false in your server's .env file.

⚠️ WARNING: Only use this in development/testing environments, never in production!

When authentication is disabled, you can make API calls without providing an API key. This is useful for local development and testing.

API Endpoints

Fact-Check a Claim

Verify a claim or statement and receive a detailed fact-checking report.

Endpoint: POST /api/v1/factcheck

Authentication: Required (unless API_AUTH_REQUIRED=false)

Request Body:

{
  "query": "The claim or statement to fact-check"
}

Response (200 OK):

{
  "success": true,
  "data": {
    "claim": "বাংলাদেশে করোনা ভ্যাকসিনের পার্শ্বপ্রতিক্রিয়া আছে",
    "report": "# দাবি\n\n[Detailed Bengali report in Markdown format...]",
    "verdict": "false",
    "sources": [
      {
        "id": 1,
        "title": "Source Title",
        "url": "https://example.com/article",
        "snippet": "Article snippet...",
        "language": "Bengali"
      }
    ],
    "relatedArticles": [...],
    "sourceInfo": {
      "hasBengaliSources": true,
      "hasEnglishSources": false,
      "totalSources": 12,
      "geography": "bangladesh",
      "tierBreakdown": {
        "tier1": 5,
        "tier2": 4,
        "tier3": 2,
        "tier4": 1,
        "tier5": 0,
        "general": 0
      }
    },
    "generatedAt": "2024-01-01T12:00:00.000Z"
  },
  "meta": {
    "apiVersion": "1.0",
    "generatedAt": "2024-01-01T12:00:00.000Z",
    "authenticated": true
  }
}

Request & Response Format

Verdict Values

The verdict field can have one of the following values:

  • "true": The claim is verified as true
  • "false": The claim is verified as false
  • "unverified": The claim could not be verified with available sources
  • "context_dependent": The claim's truthfulness depends on context

Response Structure

{
  "success": true,
  "data": {
    "claim": "string - The original claim",
    "report": "string - Detailed fact-checking report in Bengali (Markdown format)",
    "verdict": "string - One of: 'true', 'false', 'unverified', 'context_dependent'",
    "sources": [
      {
        "id": "number",
        "title": "string",
        "url": "string",
        "snippet": "string",
        "language": "string - 'Bengali' or 'English'"
      }
    ],
    "relatedArticles": "array - Related fact-check articles from Khoj database",
    "sourceInfo": {
      "hasBengaliSources": "boolean",
      "hasEnglishSources": "boolean",
      "totalSources": "number",
      "geography": "string - 'bangladesh' or 'international'",
      "tierBreakdown": "object - Breakdown of sources by tier"
    },
    "generatedAt": "string - ISO 8601 timestamp"
  },
  "meta": {
    "apiVersion": "string",
    "generatedAt": "string - ISO 8601 timestamp",
    "authenticated": "boolean"
  }
}

Cross-Origin Resource Sharing (CORS)

✅ Full CORS Support: The API fully supports Cross-Origin Resource Sharing (CORS), allowing you to make requests from any web application, including browser-based JavaScript applications.

CORS Headers

All API responses include the following CORS headers:

  • Access-Control-Allow-Origin: * - Allows requests from any origin
  • Access-Control-Allow-Methods: GET, POST, OPTIONS - Allowed HTTP methods
  • Access-Control-Allow-Headers: Content-Type, Authorization, X-API-Key - Allowed request headers

Preflight Requests

The API automatically handles CORS preflight (OPTIONS) requests. Browsers will send these automatically before making cross-origin POST requests.

Error Responses

All error responses (400, 401, 429, 500) include proper CORS headers, ensuring that error messages are accessible from cross-origin requests.

Example: Using from Browser

You can call the API directly from any web page using JavaScript:

// This works from any web page, no CORS issues
async function factCheck(query, apiKey = null) {
  const headers = { 
    'Content-Type': 'application/json' 
  };
  
  if (apiKey) {
    headers['Authorization'] = `Bearer ${apiKey.trim()}`;
  }
  
  const response = await fetch('https://khoj-bd.com/api/v1/factcheck', {
    method: 'POST',
    headers: headers,
    body: JSON.stringify({ query })
  });
  
  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.message || 'Fact-check failed');
  }
  
  return await response.json();
}

// Usage
factCheck('বাংলাদেশে করোনা ভ্যাকসিনের পার্শ্বপ্রতিক্রিয়া আছে')
  .then(result => console.log('Verdict:', result.data.verdict))
  .catch(error => console.error('Error:', error));

Code Examples

Select a programming language to see example code:

async function factCheck(query, apiKey = null) {
  const headers = {
    'Content-Type': 'application/json',
  };
  
  // Only add API key if provided (optional for development)
  if (apiKey) {
    headers['Authorization'] = `Bearer ${apiKey.trim()}`;
  }
  
  const response = await fetch('https://khoj-bd.com/api/v1/factcheck', {
    method: 'POST',
    headers: headers,
    body: JSON.stringify({ query })
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.message || 'Fact-check failed');
  }

  const data = await response.json();
  return data;
}

// Usage with API key (production)
factCheck('বাংলাদেশে করোনা ভ্যাকসিনের পার্শ্বপ্রতিক্রিয়া আছে', 'your-api-key')
  .then(result => {
    console.log('Verdict:', result.data.verdict);
    console.log('Report:', result.data.report);
    console.log('Sources:', result.data.sources.length);
  })
  .catch(error => console.error('Error:', error));

// Usage without API key (development - requires API_AUTH_REQUIRED=false)
factCheck('বাংলাদেশে করোনা ভ্যাকসিনের পার্শ্বপ্রতিক্রিয়া আছে')
  .then(result => {
    console.log('Verdict:', result.data.verdict);
  })
  .catch(error => console.error('Error:', error));

Configuration

For testing purposes, you can disable authentication by setting API_AUTH_REQUIRED=false in your environment variables.

⚠️ WARNING: Only use this in development/testing environments, never in production!

Rate Limiting

Rate limits are configured per API key. The default rate limit is 100 requests per hour.

Rate limit information is included in response headers:

  • X-RateLimit-Limit: Total requests allowed
  • X-RateLimit-Remaining: Remaining requests
  • X-RateLimit-Reset: Reset timestamp

Error Handling

Common Error Codes:

  • 400 Bad Request: Invalid or missing query parameter, or invalid JSON in request body
  • 401 Unauthorized: Invalid or missing API key. For development, set API_AUTH_REQUIRED=false in your server's .env file to test without an API key.
  • 429 Too Many Requests: Rate limit exceeded
  • 500 Internal Server Error: Server-side error occurred

Error Response Examples

400 Bad Request:

{
  "error": "Bad Request",
  "message": "Query is required and must be a non-empty string"
}

401 Unauthorized:

{
  "error": "Unauthorized",
  "message": "No API key provided. Please provide a valid API key...",
  "developmentTip": "Set API_AUTH_REQUIRED=false in your .env file..."
}

429 Too Many Requests:

{
  "error": "Rate limit exceeded",
  "message": "You have exceeded your rate limit. Please try again after 2024-01-01T13:00:00.000Z.",
  "resetAt": "2024-01-01T13:00:00.000Z"
}

Response headers also include: X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset

500 Internal Server Error:

{
  "success": false,
  "error": "Internal Server Error",
  "message": "Failed to generate fact-checking report"
}

Testing

Test with API Key (Production)

curl -X POST https://khoj-bd.com/api/v1/factcheck \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer your-api-key" \
  -d '{"query": "বাংলাদেশে করোনা ভ্যাকসিনের পার্শ্বপ্রতিক্রিয়া আছে"}'

Test Without API Key (Development)

⚠️ Requires API_AUTH_REQUIRED=false in server's .env file

curl -X POST https://khoj-bd.com/api/v1/factcheck \
  -H "Content-Type: application/json" \
  -d '{"query": "বাংলাদেশে করোনা ভ্যাকসিনের পার্শ্বপ্রতিক্রিয়া আছে"}'

Test API Info Endpoint

curl https://khoj-bd.com/api/v1/factcheck

Best Practices

1. Cache Results

Fact-checking reports are deterministic for the same query. Consider caching results to reduce API calls and improve response times.

2. Handle Rate Limits

Implement exponential backoff when you receive a 429 response. Check the X-RateLimit-Reset header to know when to retry.

3. Error Handling

Always check the response status and handle errors appropriately. Implement retry logic for transient errors.

4. Query Formatting

Provide clear, specific claims for better fact-checking results. Avoid vague or overly broad queries.

5. Store API Keys Securely

Never commit API keys to version control. Store them in environment variables and use different keys for development and production.

FAQ

How can media organizations use Khoj as an AI-powered fact-checking tool?

Media organizations can integrate Khoj API into their content management systems to automatically fact-check claims in articles before publication. Journalists can use it to verify information from sources, and newsrooms can build automated fact-checking workflows to flag potentially false information for review.

How can government departments and civic tech initiatives use this API?

Government departments can use Khoj API to monitor and verify public claims, track misinformation campaigns, and provide verified information to citizens. Civic tech initiatives can build applications that help citizens verify information they encounter online, creating more informed communities.

What is the rate limit?

Default is 100 requests per hour per API key. Contact info@khoj-bd.com for higher limits based on your needs.

How do I manage my API key?

Log in with your Google account and visit the Get API Key page to view or request your API key. Each user can have one API key assigned to them.

What languages are supported?

The API supports Bengali and English queries. Reports are generated in Bengali.

How long does a fact-check take?

Typically 10-30 seconds, depending on query complexity and source availability.

Can I cache the results?

Yes! Results are deterministic for the same query, so caching is recommended to reduce API calls and improve response times.

Support

Email: info@khoj-bd.com

Website: https://khoj-bd.com

To get an API key, log in with your Google account and visit the Get API Key page.