REST API Documentation

API Version: v1 | Base URL: https://your-domain.com/api

The Terms-inator API provides programmatic access to our AI-powered legal document analysis platform. Integrate T&C analysis directly into your applications with our RESTful API.

Key Features

  • AI-Powered Analysis: Get comprehensive analysis of legal documents
  • Real-time Progress: Track analysis progress with Server-Sent Events
  • JWT Authentication: Secure access with JSON Web Tokens
  • Credit System: Pay-per-use with transparent pricing
  • Multiple Formats: Support for text, URLs, and file uploads

Authentication

The API uses JWT (JSON Web Token) authentication. First, obtain a token by logging in with your credentials, then include the token in the Authorization header for subsequent requests.

POST /api/auth/login

Authenticate and receive a JWT token for API access.

Request Body
Parameter Type Required Description
email string Required User email address
password string Required User password
Example Request
curl -X POST "https://your-domain.com/api/auth/login" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "email=user@example.com&password=your_password"
Example Response
{
  "success": true,
  "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
  "user": {
    "id": 123,
    "email": "user@example.com",
    "name": "John Doe",
    "credits": 50
  },
  "credits": 50
}
Important: Store the token securely and include it in the Authorization header as "Bearer {token}" for all subsequent API requests.

Rate Limits

Current Limits: 100 requests per hour per API key

Rate limits are enforced per user account. When you exceed the rate limit, you'll receive a 429 status code with retry information in the response headers.

Rate Limit Headers
  • X-RateLimit-Limit: Maximum requests per hour
  • X-RateLimit-Remaining: Remaining requests in current window
  • X-RateLimit-Reset: Unix timestamp when the rate limit resets

API Endpoints

POST /api/v1/analyze

Analyse Terms & Conditions text using AI and get comprehensive insights.

Headers
Header Value Required
Authorization Bearer {token} Required
Content-Type application/json Required
Request Body
Parameter Type Required Description
text string Required The Terms & Conditions text to analyse (min 50 characters)
source_url string Optional URL where the terms were found
title string Optional Document title for reference
Example Request
curl -X POST "https://your-domain.com/api/v1/analyze" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "text": "Your terms and conditions text here...",
    "source_url": "https://example.com/terms",
    "title": "Example Terms of Service"
  }'
Response
{
  "success": true,
  "session_id": "sess_abc123def456",
  "document_id": 789,
  "progress_url": "/api/v1/progress/sess_abc123def456",
  "message": "Analysis started successfully",
  "estimated_time": "30-60 seconds"
}
{
  "success": false,
  "error": "Invalid input",
  "message": "Text must be at least 50 characters long",
  "details": {
    "field": "text",
    "received_length": 25,
    "minimum_length": 50
  }
}
GET /api/v1/progress/{sessionId}

Get real-time progress updates for an analysis session using Server-Sent Events (SSE).

Headers
Header Value Required
Authorization Bearer {token} Required
Accept text/event-stream Optional
Example Request
curl -X GET "https://your-domain.com/api/v1/progress/sess_abc123def456" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Accept: text/event-stream"
Example SSE Response
data: {"stage": "processing", "progress": 25, "message": "Analyzing document structure..."}

data: {"stage": "ai_analysis", "progress": 75, "message": "Running AI analysis..."}

data: {"stage": "complete", "progress": 100, "document_id": 789, "redirect_url": "/document/789"}
GET /api/v1/history

Retrieve the user's document analysis history with pagination support.

Query Parameters
Parameter Type Default Description
limit integer 20 Number of documents to return (max 100)
offset integer 0 Number of documents to skip
Example Response
{
  "success": true,
  "documents": [
    {
      "id": 789,
      "title": "Example Terms of Service",
      "source_url": "https://example.com/terms",
      "overall_rating": 7.2,
      "created_at": "2024-01-15T10:30:00Z",
      "summary": "Generally user-friendly terms with some concerns about data collection..."
    }
  ],
  "pagination": {
    "total": 15,
    "limit": 20,
    "offset": 0,
    "has_more": false
  }
}
GET /api/v1/document/{id}

Get complete analysis results for a specific document.

Example Response
{
  "success": true,
  "document": {
    "id": 789,
    "title": "Example Terms of Service",
    "source_url": "https://example.com/terms",
    "overall_rating": 7.2,
    "scores": {
      "clarity": 8.0,
      "fairness": 6.5,
      "privacy": 7.0,
      "user_rights": 7.5
    },
    "concerns": [
      {
        "title": "Data Collection Practices",
        "description": "The terms allow extensive data collection...",
        "severity": "medium",
        "category": "privacy"
      }
    ],
    "recommendations": [
      "Consider reviewing the data sharing policies",
      "Be aware of the arbitration clause"
    ],
    "created_at": "2024-01-15T10:30:00Z"
  }
}

Error Handling

The API uses conventional HTTP status codes to indicate success or failure.

Status Code Meaning Description
200 OK Request successful
400 Bad Request Invalid request parameters
401 Unauthorized Invalid or missing authentication
403 Forbidden Insufficient credits or permissions
404 Not Found Resource not found
429 Too Many Requests Rate limit exceeded
500 Internal Server Error Server error occurred
Error Response Format
{
  "success": false,
  "error": "Error type",
  "message": "Human-readable error message",
  "details": {
    "additional": "context-specific information"
  }
}

Code Examples

JavaScript/Node.js

// Login and analyse a document
async function analyseDocument(text, sourceUrl) {
  // First, authenticate
  const loginResponse = await fetch('/api/auth/login', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({
      email: 'user@example.com',
      password: 'password'
    })
  });
  
  const { token } = await loginResponse.json();
  
  // Then analyze
  const analyzeResponse = await fetch('/api/v1/analyze', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ text, source_url: sourceUrl })
  });
  
  const result = await analyzeResponse.json();
  console.log('Analysis started:', result);
  
  // Listen for progress updates
  const eventSource = new EventSource(`/api/v1/progress/${result.session_id}`);
  eventSource.onmessage = (event) => {
    const progress = JSON.parse(event.data);
    console.log('Progress:', progress);
    
    if (progress.stage === 'complete') {
      eventSource.close();
      // Fetch final results
      fetchDocument(progress.document_id, token);
    }
  };
}

Python

import requests
import json

class TLDRClient:
    def __init__(self, base_url, email, password):
        self.base_url = base_url
        self.token = self._authenticate(email, password)
    
    def _authenticate(self, email, password):
        response = requests.post(f"{self.base_url}/api/auth/login", data={
            'email': email,
            'password': password
        })
        return response.json()['token']
    
    def analyse(self, text, source_url=None, title=None):
        headers = {
            'Authorization': f'Bearer {self.token}',
            'Content-Type': 'application/json'
        }
        data = {'text': text}
        if source_url:
            data['source_url'] = source_url
        if title:
            data['title'] = title
            
        response = requests.post(
            f"{self.base_url}/api/v1/analyze", 
            headers=headers, 
            json=data
        )
        return response.json()
    
    def get_document(self, document_id):
        headers = {'Authorization': f'Bearer {self.token}'}
        response = requests.get(
            f"{self.base_url}/api/v1/document/{document_id}", 
            headers=headers
        )
        return response.json()

# Usage
client = TLDRClient('https://your-domain.com', 'user@example.com', 'password')
result = client.analyse('Your terms and conditions text here...')
print(f"Analysis started: {result['session_id']}")

SDKs & Libraries

Coming Soon: Official SDKs for popular programming languages are in development.
JavaScript/Node.js SDK

Full-featured SDK with TypeScript support

In Development
Python SDK

Pythonic interface with async support

In Development
PHP SDK

PSR-4 compliant with Composer support

Planned
Go SDK

Lightweight and efficient Go client

Planned
Community Contributions

We welcome community contributions for SDKs in other programming languages. Check out our contribution guidelines to get started.