02 Rate Limiting & Throttling
APIs are prone to abuse, whether malicious (DDoS) or accidental (a loop in a client script). Implement rate limiting to protect your resources.
Token Bucket Algorithm
Allows for bursts of traffic but enforces a steady average rate.
User-Based Limits
Set limits per user ID or API key, rather than just IP address, to prevent one user from monopolizing resources.
Return 429
Use the HTTP 429 Too Many Requests status code and include a `Retry-After` header.
03 Input Validation & Sanitization
Treat all input from the API as untrusted.
Use schemas (like JSON Schema or Zod for TypeScript) to strictly define expected payloads. Reject any request that contains unexpected fields or incorrect data types.
Sanitize output as well to prevent Stored XSS if API data is rendered in a browser.
04 Encryption in Transit
APIs often transmit sensitive data (PII, tokens). HTTPS (TLS) is non-negotiable.
Enforce TLS 1.2 or 1.3 and use HSTS to prevent downgrade attacks. Disable insecure cipher suites.
05 Frequently Asked Questions
Is Basic Auth secure for APIs?
Only if used over HTTPS, but it's generally recommended to use token-based authentication (like OAuth 2.0 or JWT) for better security and flexibility.
How do I secure a GraphQL API?
GraphQL requires specific defenses like query depth limiting, complexity analysis, and disabling introspection in production to prevent resource exhaustion and schema leakage.
What is the difference between specific API keys and user tokens?
API keys identify the client application (machine), while user tokens (like JWTs) identify the specific user and their permissions.
Should I expose my API documentation publicly?
Yes, for public APIs. However, ensure that sensitive internal endpoints are not documented or accessible without proper authorization.