Brief Case AI - API Documentation

Comprehensive Legal Intelligence Platform - REST API v3.0

API Overview

Base URL

https://api.briefcaseai.com/v3

Alternative: https://legal-query-rephrase.vercel.app/api

🚀 What's New in v3.0

Rate Limits

Response Format

All API responses follow a consistent JSON structure:

{ "success": true, "data": { // Response data specific to the endpoint }, "meta": { "timestamp": "2025-01-16T10:00:00Z", "version": "3.0.0", "requestId": "req_abc123", "credits_used": 1, "credits_remaining": 99 }, "error": null }

Error Handling

Error responses include detailed information for debugging:

{ "success": false, "data": null, "error": { "code": "INSUFFICIENT_CREDITS", "message": "Not enough credits to perform this operation", "details": { "required": 5, "available": 3, "upgrade_url": "https://briefcaseai.com/pricing" } }, "meta": { "timestamp": "2025-01-16T10:00:00Z", "requestId": "req_xyz789" } }

Platform Features

🔍 Research & Analysis

Comprehensive legal research with AI assistance

  • AI Research Assistant
  • Case Law Genealogy
  • Query Enhancement
  • Keyword Analysis
Enhanced

📄 Document Work

Create, review, and manage legal documents

  • Document Generation
  • Contract Review & Analysis
  • Template Library
  • Version Control

⚙️ Workflow Automation

Automate repetitive legal tasks

  • Pre-built Legal Workflows
  • Custom Workflow Builder
  • Scheduled Executions
  • Webhook Triggers
Beta

📊 Analytics & Insights

Track usage and performance metrics

  • Usage Analytics
  • Performance Metrics
  • Cost Tracking
  • ROI Reports

👥 Collaboration

Share and collaborate on legal work

  • Shared Conversations
  • Team Workspaces
  • Document Sharing
  • Comments & Annotations
Pro

🛡️ Security & Compliance

Enterprise-grade security features

  • End-to-End Encryption
  • SOC 2 Compliance
  • Audit Logs
  • Data Residency Options

Authentication

API Key Authentication

Include your API key in the Authorization header:

Authorization: Bearer YOUR_API_KEY

NextAuth Session

For web applications, use NextAuth session cookies:

Cookie: next-auth.session-token=YOUR_SESSION_TOKEN

OAuth 2.0

For third-party integrations, use OAuth 2.0 flow:

  1. Redirect user to: /api/auth/authorize
  2. User grants permission
  3. Receive authorization code
  4. Exchange code for access token at: /api/auth/token

JWT Tokens

JWT tokens contain user information and permissions:

// Decoded token payload { "userId": "user_123", "email": "lawyer@firm.com", "name": "John Doe", "role": "professional", "credits": 500, "features": ["research", "documents", "workflows"], "iat": 1737000000, "exp": 1737086400 }

Research & Analysis APIs

POST/api/legal-research

Comprehensive AI-powered legal research

Request Body:

{ "query": "breach of contract damages California", "jurisdiction": "US-CA", "dateRange": { "start": "2020-01-01", "end": "2024-12-31" }, "includeGenealogy": true, "maxResults": 50 }

Response:

{ "success": true, "data": { "results": [...], "genealogy": { "parentCases": [...], "childCases": [...], "relatedCases": [...] }, "insights": { "trends": [...], "key_precedents": [...] } } }

POST/api/enhance-query

Enhance legal queries with AI suggestions

Request Body:

{ "query": "intellectual property", "mode": "comprehensive", "includeVariations": true, "includeSynonyms": true }

POST/api/learning/genealogical-cases

Trace case law evolution and relationships

Request Body:

{ "caseQuery": "Miranda v. Arizona", "jurisdiction": "federal", "depth": 3, "includeOverruled": true }

POST/api/analyze-keywords

Extract and analyze legal keywords from text

Request Body:

{ "text": "The defendant breached the non-disclosure agreement...", "extractEntities": true, "identifyStatutes": true }

Document Management APIs

POST/api/generate-document

Generate legal documents with AI assistance

Request Body:

{ "documentType": "service_agreement", "parties": { "provider": "Tech Solutions Inc.", "client": "StartupCo LLC" }, "terms": { "duration": "12 months", "payment": "$10,000/month", "scope": "Software development services" }, "jurisdiction": "Delaware", "format": "pdf" }

GET/api/contracts/templates

List available contract templates

Query Parameters:

  • category - Filter by category (nda, employment, service)
  • jurisdiction - Filter by jurisdiction
  • page - Page number (default: 1)
  • limit - Items per page (default: 20)

POST/api/contracts/ai-hints

Get AI suggestions for contract clauses

Request Body:

{ "contractType": "employment", "context": "remote work policy", "riskTolerance": "conservative" }

POST/api/contracts/versions

Track contract versions and changes

Request Body:

{ "contractId": "contract_123", "content": "Updated contract content...", "changeDescription": "Added termination clause", "author": "user_456" }

Workflow Automation APIs

⚡ Workflow Features (Beta)

Workflow automation is currently in beta. APIs may change as we improve the feature based on user feedback.

GET/api/workflows

List user's workflows

Query Parameters:

  • status - Filter by status (active, paused, completed)
  • category - Filter by category

POST/api/workflows

Create a new workflow

Request Body:

{ "name": "Contract Review Automation", "description": "Automatically review and flag contract risks", "category": "contracts", "steps": [ { "id": "extract", "type": "text_extraction", "config": {...} }, { "id": "analyze", "type": "ai_analysis", "config": {...} } ], "triggers": [ { "type": "manual", "enabled": true } ] }

POST/api/workflows/execute

Execute a workflow

Request Body:

{ "workflowId": "workflow_789", "inputs": { "document": "base64_encoded_document", "parameters": {...} } }

GET/api/workflows/marketplace

Browse community workflow templates

Query Parameters:

  • category - litigation, contracts, research, compliance
  • difficulty - beginner, intermediate, advanced
  • sort - popular, recent, rated

Analytics & Reporting APIs

GET/api/analytics/usage

Get usage statistics and metrics

Query Parameters:

  • period - day, week, month, year
  • startDate - Start date (ISO 8601)
  • endDate - End date (ISO 8601)
  • groupBy - feature, user, department

GET/api/analytics/summary

Get analytics summary dashboard data

Response:

{ "totalQueries": 1250, "documentsGenerated": 89, "workflowsExecuted": 34, "timeSaved": "127 hours", "costSavings": "$15,240", "topFeatures": [...], "usageTrend": [...] }

POST/api/analytics/event

Track custom analytics events

Request Body:

{ "event": "contract_reviewed", "properties": { "contractType": "nda", "reviewTime": 300, "risksFound": 2 } }

API Documentation Type

Admin API Access

⚠️ Restricted Access

Admin APIs are only available to authenticated administrators. These endpoints are not publicly accessible.

Authentication Requirements

Admin endpoints require elevated privileges:

Authorization: Bearer ADMIN_JWT_TOKEN X-Admin-Key: ADMIN_API_KEY X-Request-Source: admin-panel

Available Admin Endpoints

Security Notes

For detailed admin API documentation, please contact your system administrator.

Code Examples

JavaScript / Node.js

const axios = require('axios'); // Initialize client const client = axios.create({ baseURL: 'https://api.briefcaseai.com/v3', headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' } }); // Legal Research Example async function performLegalResearch(query) { try { const response = await client.post('/legal-research', { query: query, jurisdiction: 'US-CA', includeGenealogy: true, maxResults: 25 }); console.log('Research Results:', response.data.data.results); console.log('Case Genealogy:', response.data.data.genealogy); return response.data; } catch (error) { console.error('Error:', error.response?.data || error.message); } } // Document Generation Example async function generateContract(type, parties) { try { const response = await client.post('/generate-document', { documentType: type, parties: parties, jurisdiction: 'Delaware', format: 'pdf' }); console.log('Document ID:', response.data.data.documentId); console.log('Download URL:', response.data.data.downloadUrl); return response.data; } catch (error) { console.error('Error:', error.response?.data || error.message); } } // Execute Workflow Example async function runWorkflow(workflowId, inputs) { try { const response = await client.post('/workflows/execute', { workflowId: workflowId, inputs: inputs }); console.log('Execution ID:', response.data.data.executionId); console.log('Status:', response.data.data.status); return response.data; } catch (error) { console.error('Error:', error.response?.data || error.message); } } // Usage performLegalResearch('breach of contract damages'); generateContract('nda', { discloser: 'Company A', recipient: 'Company B' }); runWorkflow('workflow_contract_review', { document: 'base64_document_content' });

Python

import requests import json class BriefCaseAIClient: def __init__(self, api_key): self.base_url = "https://api.briefcaseai.com/v3" self.headers = { "Authorization": f"Bearer {api_key}", "Content-Type": "application/json" } def legal_research(self, query, jurisdiction="US-CA"): """Perform legal research with AI assistance""" endpoint = f"{self.base_url}/legal-research" data = { "query": query, "jurisdiction": jurisdiction, "includeGenealogy": True, "maxResults": 25 } response = requests.post(endpoint, json=data, headers=self.headers) return response.json() def enhance_query(self, query): """Enhance a legal query with AI suggestions""" endpoint = f"{self.base_url}/enhance-query" data = { "query": query, "mode": "comprehensive", "includeVariations": True } response = requests.post(endpoint, json=data, headers=self.headers) return response.json() def generate_document(self, doc_type, parties, terms): """Generate a legal document""" endpoint = f"{self.base_url}/generate-document" data = { "documentType": doc_type, "parties": parties, "terms": terms, "format": "pdf" } response = requests.post(endpoint, json=data, headers=self.headers) return response.json() def execute_workflow(self, workflow_id, inputs): """Execute a workflow""" endpoint = f"{self.base_url}/workflows/execute" data = { "workflowId": workflow_id, "inputs": inputs } response = requests.post(endpoint, json=data, headers=self.headers) return response.json() # Usage client = BriefCaseAIClient("YOUR_API_KEY") # Legal research research_result = client.legal_research("intellectual property infringement") print(f"Found {len(research_result['data']['results'])} relevant cases") # Enhance query enhanced = client.enhance_query("contract breach") print(f"Enhanced query: {enhanced['data']['enhanced']}") # Generate document doc = client.generate_document( doc_type="nda", parties={"discloser": "TechCo", "recipient": "Partner Inc"}, terms={"duration": "2 years", "jurisdiction": "California"} ) print(f"Document generated: {doc['data']['documentId']}")

cURL

# Legal Research curl -X POST https://api.briefcaseai.com/v3/legal-research \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "query": "employment discrimination California", "jurisdiction": "US-CA", "includeGenealogy": true }' # Generate Document curl -X POST https://api.briefcaseai.com/v3/generate-document \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "documentType": "service_agreement", "parties": { "provider": "Consulting LLC", "client": "Enterprise Corp" }, "format": "pdf" }' # Execute Workflow curl -X POST https://api.briefcaseai.com/v3/workflows/execute \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "workflowId": "workflow_contract_review", "inputs": { "document": "base64_encoded_content" } }'

Webhooks

Available Events

Webhook Configuration

Configure webhooks in your account settings or via API:

POST /api/webhooks { "url": "https://your-app.com/webhook", "events": ["research.completed", "document.generated"], "secret": "your_webhook_secret" }

Webhook Payload

{ "event": "research.completed", "timestamp": "2025-01-16T10:00:00Z", "data": { "researchId": "research_123", "userId": "user_456", "query": "breach of contract", "resultsCount": 25, "creditsUsed": 5 }, "signature": "sha256=abc123..." }

Webhook Security

Verify webhook signatures to ensure authenticity:

const crypto = require('crypto'); function verifyWebhookSignature(payload, signature, secret) { const expectedSignature = crypto .createHmac('sha256', secret) .update(JSON.stringify(payload)) .digest('hex'); return `sha256=${expectedSignature}` === signature; } // Express.js middleware example app.post('/webhook', (req, res) => { const signature = req.headers['x-briefcase-signature']; const isValid = verifyWebhookSignature(req.body, signature, WEBHOOK_SECRET); if (!isValid) { return res.status(401).send('Invalid signature'); } // Process webhook console.log('Webhook event:', req.body.event); res.status(200).send('OK'); });