API Security Best Practices
Learn how to secure API keys, implement access controls, and monitor for suspicious activity.
Storing Keys Securely
Do's and Don'ts
✓ Do:
- Store in environment variables
- Use secret management tools
- Encrypt in databases
- Keep in server-side code only
- Use key vaults for production
✗ Don't:
- Commit to version control (Git)
- Embed in client-side code
- Share via email or chat
- Store in plain text files
- Include in public repositories

Environment Variables
Best Practice:
# .env file (never commit to Git!)
GRABATABLE_API_KEY=gat_live_sk_1234567890abcdef
GRABATABLE_VENUE_ID=venue-123
// Access in your code
const apiKey = process.env.GRABATABLE_API_KEY;
Add to .gitignore:
.env
.env.local
config/secrets.yml
credentials.json
Secret Management Tools
Recommended Tools:
- AWS Secrets Manager
- Azure Key Vault
- Google Cloud Secret Manager
- HashiCorp Vault
- Doppler
- 1Password CLI

Example with AWS:
const AWS = require('aws-sdk');
const secretsManager = new AWS.SecretsManager();
async function getApiKey() {
const data = await secretsManager
.getSecretValue({ SecretId: 'grabatable-api-key' })
.promise();
return JSON.parse(data.SecretString).apiKey;
}
Server-Side Only
Golden Rule
Never expose API keys in client-side code
Why:
- Anyone can view browser source code
- Keys can be stolen and misused
- Difficult to rotate compromised keys
- Your account may be abused
- Potential financial liability
Correct Architecture
Use a Server-Side Proxy:
- Client → Makes request to your server
- Your Server → Holds API key securely
- Your Server → Makes request to Grab A Table API
- Grab A Table API → Returns data
- Your Server → Forwards response to client

Example Implementation:
// Server-side (Node.js/Express)
app.post('/api/book', async (req, res) => {
try {
const response = await fetch('https://api.grabatable.app/v1/reservations', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.GRABATABLE_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(req.body)
});
const data = await response.json();
res.json(data);
} catch (error) {
res.status(500).json({ error: 'Booking failed' });
}
});
// Client-side - Never includes API key
fetch('/api/book', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
date: '2026-03-15',
time: '19:00',
party_size: 4
})
});
Access Restrictions
IP Whitelisting
Add extra security by limiting key usage to specific IP addresses:
Setup:
- Go to API key settings
- Enable IP restrictions
- Add allowed IP addresses
- Save configuration

Benefits:
- Only your servers can use key
- Blocks unauthorized locations
- Additional security layer
- Audit trail of access
Use Cases:
- Production API keys
- High-value operations
- Compliance requirements
- Known static IPs
Domain Restrictions
Limit API key to specific domains:
When to Use:
- Embedded widgets
- Third-party integrations
- Partner implementations
- Specific applications only

Configuration:
Allowed domains:
- *.yourwebsite.com
- booking.example.com
- app.yourcompany.com
Geographic Restrictions
Limit key usage by region:
- Specific countries only
- Block high-risk regions
- Comply with data laws
- Reduce abuse risk
Time-Based Restrictions
Optional time-based limits:
- Business hours only
- Maintenance windows
- Specific time zones
- Scheduled operations

Rate Limiting
Purpose
Rate limiting protects:
- Your API quota
- Against abuse
- Runaway scripts
- DDOS attacks
- Cost overruns
Configure Limits
Set per-key limits:
- Requests per second
- Requests per minute
- Requests per hour
- Daily maximum

Example Configuration:
- Standard: 100 requests/minute
- Burst: 200 requests/minute (brief)
- Daily: 10,000 requests/day
Handling Rate Limits
Implement in Your Code:
async function makeRequest(url, options) {
try {
const response = await fetch(url, options);
if (response.status === 429) {
const retryAfter = response.headers.get('Retry-After');
await sleep(retryAfter * 1000);
return makeRequest(url, options); // Retry
}
return response;
} catch (error) {
console.error('Request failed:', error);
throw error;
}
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
Monitoring for Security
Suspicious Activity Detection
Monitor for unusual patterns:
- Requests from unexpected IPs
- Unusual request volume
- High error rates
- Off-hours activity
- Geographic anomalies
- Multiple failed authentications

Alert Configuration
Set up security alerts:
Alert Triggers:
- Key used from new IP
- Multiple failed authentications
- Rate limit exceeded repeatedly
- Unusual traffic patterns
- Geographic anomaly
- Error rate spike

Notification Methods:
- Email (immediate)
- SMS (critical only)
- Push notification
- Webhook to security system
- Slack/Teams integration
Audit Logs
Maintain comprehensive logs:
- All API requests
- Authentication attempts
- Key creation/revocation
- Permission changes
- Configuration updates
- Security events

Retention:
- 90 days minimum
- Longer for compliance
- Archive for analysis
- Never delete security events
Incident Response
If Key is Compromised
Immediate Actions:
- Revoke the key immediately
- Review access logs for misuse
- Create new key with different value
- Update applications to use new key
- Investigate how compromise occurred
- Document the incident
- Review security practices

Preventing Future Incidents
After Incident:
- Conduct security review
- Update procedures
- Train team members
- Implement additional controls
- Schedule regular audits
- Review access policies
Compliance & Standards
Industry Standards
Follow security best practices:
- OWASP API Security Top 10
- PCI DSS (via Stripe for payment processing)
- GDPR (customer data protection)
- Industry-standard security controls
- Best practice security frameworks

Data Protection
Your Responsibilities:
- Secure API keys
- Protect customer data
- Encrypt in transit (HTTPS)
- Encrypt at rest
- Access control
- Data retention policies
- Privacy compliance
Regular Audits
Schedule Regular Reviews:
- Monthly: Access review
- Quarterly: Security audit
- Annually: Comprehensive review
- Ad-hoc: After incidents
Audit Checklist:
- All keys accounted for
- Unused keys revoked
- Access restrictions current
- Logs reviewed
- No keys in code repositories
- Team trained on security
- Documentation up to date
- Incident response tested
Security Checklist
Essential Security Measures
- API keys stored in environment variables
- Keys never committed to version control
- Server-side implementation only
- HTTPS used for all requests
- IP whitelisting enabled (where applicable)
- Rate limiting configured
- Monitoring and alerts active
- Regular key rotation schedule
- Team trained on security practices
- Incident response plan documented
- Audit logs regularly reviewed
- Error logging (without sensitive data)
- Access restrictions enabled
- Webhook signatures verified
- Compliance requirements met
Team Training
Security Awareness
Train Your Team On:
- Proper key handling
- Secure coding practices
- Incident reporting
- Access procedures
- Best practices
- Compliance requirements
Developer Guidelines
Provide Clear Guidelines:
- How to access keys
- Where to store keys
- How to rotate keys
- Error handling
- Logging practices
- Code review requirements

Next Steps
- Set up API key management
- Configure webhooks
- Monitor API usage
- Review API documentation
Need Help?
If you have questions about API security, contact our support team at [email protected] or via WhatsApp.
Security Concerns: Report security issues immediately to [email protected]