Authentication
Authentication
LightningPDF uses API key authentication with Bearer tokens. All API requests must include a valid API key in the Authorization header.
API Keys
API keys are prefixed with lpdf_ and provide full access to your account's API endpoints.
Creating API Keys
- Log in to your LightningPDF dashboard
- Navigate to Settings → API Keys
- Click Create API Key
- Give your key a descriptive name (e.g., "Production Server", "Testing")
- Copy the key immediately — it won't be shown again
⚠️ Security: Never commit API keys to version control or expose them in client-side code.
Using API Keys
Include your API key in the Authorization header with the Bearer scheme:
curl https://lightningpdf.dev/api/v1/pdf/generate \
-H "Authorization: Bearer lpdf_your_api_key_here" \
-H "Content-Type: application/json" \
-d '{"html": "<h1>Test</h1>"}'
Multiple API Keys
Create multiple API keys for different environments or applications:
- Production:
lpdf_prod_abc123(production server) - Staging:
lpdf_staging_xyz789(staging environment) - Development:
lpdf_dev_def456(local development)
This allows you to:
- Rotate keys without downtime
- Revoke compromised keys immediately
- Track usage by environment
- Test without affecting production quotas
Revoking API Keys
If a key is compromised:
- Go to Settings → API Keys
- Find the compromised key
- Click Revoke
- Create a new key and update your application
Revoked keys are immediately invalidated.
Authentication Headers
Required Headers
Authorization: Bearer lpdf_your_api_key
Content-Type: application/json
Response Headers
Every API response includes rate limit and credit information:
X-Credits-Remaining: 1847
X-Credits-Limit: 2000
X-Credits-Reset: 1705334400
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1705330800
Credit System
LightningPDF uses a credit-based billing model. Each PDF operation consumes credits based on complexity.
Credit Limits by Plan
| Plan | Credits/Month | Price |
|---|---|---|
| Free | 100 | $0 |
| Starter | 2,000 | $19/mo |
| Pro | 10,000 | $49/mo |
| Business | 50,000 | $149/mo |
| Enterprise | 150,000 | $399/mo |
Credit Consumption
| Operation | Credits |
|---|---|
| Generate PDF (simple HTML) | 1 |
| Generate PDF (complex/Chromium) | 1 |
| Template generation | 1 |
| Batch item (per PDF) | 1 |
| Merge PDFs | 1 |
| Split PDF (per output) | 1 |
| Compress PDF | 1 |
| Password protection | 1 |
| PDF/A conversion | 1 |
| PDF info extraction | 0 (free) |
Credit Reset
Credits reset on the 1st of each month at 00:00 UTC. Unused credits do not roll over.
Checking Remaining Credits
Via Response Headers
response = requests.post(url, headers=headers, json=data)
credits_remaining = int(response.headers.get('X-Credits-Remaining', 0))
print(f"Credits remaining: {credits_remaining}")
Via API Endpoint
GET /v1/account/credits
curl https://lightningpdf.dev/api/v1/account/credits \
-H "Authorization: Bearer lpdf_your_api_key"
Response:
{
"success": true,
"data": {
"credits_remaining": 1847,
"credits_limit": 2000,
"reset_at": "2024-02-01T00:00:00Z",
"plan": "starter"
}
}
Overage Billing
When you exceed your monthly credit limit:
- Free & Starter: API requests are rejected with
insufficient_creditserror - Pro & Business: Overage credits billed at $0.01 per credit
- Enterprise: Custom overage rates (contact sales)
Overage Example
Pro plan (10,000 credits) used 10,500 credits:
- Base: $49/mo
- Overage: 500 × $0.01 = $5.00
- Total: $54.00
Preventing Overage
Set up credit alerts in your dashboard:
- Go to Settings → Billing
- Enable Credit Alerts
- Set thresholds (e.g., 80%, 90%, 100%)
- Receive email notifications
Rate Limits
Rate limits prevent abuse and ensure fair usage.
Limits by Plan
| Plan | Requests/Minute | Burst |
|---|---|---|
| Free | 10 | 15 |
| Starter | 30 | 50 |
| Pro | 100 | 150 |
| Business | 300 | 500 |
| Enterprise | Custom | Custom |
Rate Limit Headers
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1705330800
Handling Rate Limits
When you exceed rate limits, the API returns:
{
"success": false,
"error": {
"code": "rate_limit_exceeded",
"message": "Rate limit exceeded. Retry after 45 seconds.",
"retry_after": 45
}
}
Response Code: 429 Too Many Requests
Exponential Backoff Example
import time
import requests
def generate_pdf_with_retry(url, headers, data, max_retries=3):
for attempt in range(max_retries):
response = requests.post(url, headers=headers, json=data)
if response.status_code == 200:
return response.json()
if response.status_code == 429:
retry_after = int(response.headers.get('Retry-After', 60))
print(f"Rate limited. Retrying after {retry_after}s...")
time.sleep(retry_after)
continue
# Other error
response.raise_for_status()
raise Exception("Max retries exceeded")
Error Codes
Authentication Errors
| Code | HTTP Status | Description |
|---|---|---|
missing_api_key |
401 | No Authorization header |
invalid_api_key |
401 | API key is invalid or revoked |
api_key_expired |
401 | API key has expired |
insufficient_credits |
402 | Not enough credits remaining |
rate_limit_exceeded |
429 | Too many requests |
Example Error Response
{
"success": false,
"error": {
"code": "insufficient_credits",
"message": "You have 0 credits remaining. Upgrade your plan or wait for reset on 2024-02-01.",
"details": {
"credits_remaining": 0,
"credits_limit": 100,
"reset_at": "2024-02-01T00:00:00Z"
}
}
}
Best Practices
1. Secure Storage
Store API keys securely:
# Environment variables
export LIGHTNINGPDF_API_KEY="lpdf_your_api_key"
import os
API_KEY = os.environ.get("LIGHTNINGPDF_API_KEY")
if not API_KEY:
raise Exception("LIGHTNINGPDF_API_KEY not set")
Never hardcode keys in source code.
2. Key Rotation
Rotate API keys regularly (every 90 days):
- Create new key
- Update production systems
- Test thoroughly
- Revoke old key
3. Monitor Usage
Track credit consumption:
def track_credit_usage(response):
credits_remaining = int(response.headers.get('X-Credits-Remaining', 0))
credits_limit = int(response.headers.get('X-Credits-Limit', 0))
usage_percent = ((credits_limit - credits_remaining) / credits_limit) * 100
if usage_percent > 80:
print(f"⚠️ Warning: {usage_percent:.1f}% credits used")
# Log to monitoring service
log_metric("pdf_credits_remaining", credits_remaining)
4. Error Handling
Always handle authentication and rate limit errors:
try:
response = requests.post(url, headers=headers, json=data)
response.raise_for_status()
result = response.json()
except requests.exceptions.HTTPError as e:
if e.response.status_code == 401:
print("Invalid API key. Check your credentials.")
elif e.response.status_code == 402:
print("Insufficient credits. Upgrade your plan.")
elif e.response.status_code == 429:
retry_after = e.response.headers.get('Retry-After', 60)
print(f"Rate limited. Retry after {retry_after}s")
else:
print(f"API error: {e}")
5. Use Service Accounts
For production applications, create dedicated service accounts:
- Separate account for each application
- Unique API keys per environment
- Isolated credit pools
- Independent rate limits
Webhook Authentication
For webhook endpoints (batch completion, etc.), verify signatures:
import hmac
import hashlib
def verify_webhook(payload, signature, secret):
"""Verify webhook signature"""
expected = hmac.new(
secret.encode(),
payload.encode(),
hashlib.sha256
).hexdigest()
return hmac.compare_digest(signature, expected)
# Usage
@app.route('/webhooks/pdf-batch', methods=['POST'])
def handle_webhook():
signature = request.headers.get('X-LightningPDF-Signature')
payload = request.data.decode()
if not verify_webhook(payload, signature, WEBHOOK_SECRET):
return {'error': 'Invalid signature'}, 401
# Process webhook
data = request.json
print(f"Batch {data['job_id']} completed")
return {'success': True}, 200
Support
For authentication issues:
- Email: support@lightningpdf.dev
- Status Page: status.lightningpdf.dev
- Documentation: lightningpdf.dev/docs
- API Status: Check
X-LightningPDF-Statusheader in responses
Enterprise Features
Enterprise plans include:
- Custom rate limits: Tailored to your needs
- Dedicated IP: Optional dedicated IP addresses
- SSO/SAML: Single sign-on integration
- Priority support: 24/7 support with SLA
- Custom contracts: Annual billing, custom terms
- Audit logs: Detailed API usage logs
Contact sales@lightningpdf.dev for enterprise pricing.