API Overview
Base URL
https://api.briefcaseai.com/v3
Alternative: https://legal-query-rephrase.vercel.app/api
🚀 What's New in v3.0
- Task-Based Organization: APIs organized by legal workflows
- AI-Powered Research: Enhanced genealogy and case law analysis
- Workflow Automation: Build and execute custom legal workflows
- Document Intelligence: Smart contract analysis and generation
- Real-time Collaboration: Share research and documents
Rate Limits
- Free tier: 100 requests per hour
- Professional: 1,000 requests per hour
- Enterprise: 10,000 requests per hour
- Custom: Contact sales for unlimited access
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"
}
}
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:
- Redirect user to:
/api/auth/authorize
- User grants permission
- Receive authorization code
- 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
}
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
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
- User Management: Create, update, delete users, manage credits and features
- System Analytics: Access detailed system metrics and usage data
- Payment Management: View transactions, manage subscriptions
- Content Management: Manage blog posts, templates, and system content
- Workflow Management: Monitor and manage all workflows
- System Configuration: Feature flags, settings, migrations
- Testing & Debugging: System health checks, debug endpoints
Security Notes
- All admin actions are logged with full audit trail
- IP whitelisting is enforced for admin endpoints
- MFA is required for admin accounts
- Session timeout after 30 minutes of inactivity
- Admin portal is discovery-only (no public links)
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
research.completed - Legal research analysis finished
document.generated - Document generation completed
contract.reviewed - Contract review completed
workflow.executed - Workflow execution finished
workflow.failed - Workflow execution failed
document.signed - Document signed by all parties
credits.low - Credits below threshold
payment.processed - Payment successfully processed
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');
});