API security best practices are the defensive measures — authentication, authorisation, input validation, rate limiting, encryption, and monitoring — that protect your application programming interfaces from unauthorised access, data breaches, injection attacks, and abuse. With APIs now powering most modern web and mobile applications, securing them is as critical as securing your front-end and database layers.
Why Are APIs a Prime Target for Attackers?
APIs have become the most common attack vector for modern applications for several reasons:
- Direct data access: APIs often provide direct access to databases and backend systems, bypassing front-end security controls.
- Predictable structure: REST APIs follow conventions (/api/users/123) that make endpoint discovery straightforward for attackers.
- Authentication complexity: Managing tokens, keys, and sessions across multiple API consumers introduces numerous vulnerability points.
- Rapid proliferation: Organisations expose dozens or hundreds of APIs, making comprehensive security coverage difficult.
- Shadow APIs: Undocumented or forgotten APIs that still function but receive no security updates.
What Are the OWASP API Security Top 10 Risks?
The OWASP API Security Project identifies the most critical API threats:
| Risk | Description | Example |
|---|---|---|
| Broken Object Level Authorisation | User accesses objects belonging to other users | Changing /api/orders/123 to /api/orders/124 |
| Broken Authentication | Weak or missing authentication mechanisms | API keys in URLs, no token expiration |
| Broken Object Property Level Authorisation | Exposing sensitive object properties | API returns salary field to all users |
| Unrestricted Resource Consumption | No limits on API usage | No rate limiting allows brute force |
| Broken Function Level Authorisation | Users access admin-level functions | Regular user calls /api/admin/delete |
| Unrestricted Access to Sensitive Business Flows | Automated abuse of business logic | Bot buying all limited-stock items |
| Server-Side Request Forgery | API fetches attacker-controlled URLs | URL parameter triggers internal network scan |
| Security Misconfiguration | Default settings, verbose errors, open CORS | Stack traces exposed in API responses |
| Improper Inventory Management | Untracked API versions and endpoints | Deprecated v1 API still accessible |
| Unsafe Consumption of APIs | Trusting data from third-party APIs | Processing unvalidated webhook payloads |
How Should You Implement API Authentication?
Choose the right authentication mechanism for your use case:
- OAuth 2.0 with PKCE: The standard for user-facing APIs. Use short-lived access tokens (15–60 minutes) with refresh tokens. PKCE (Proof Key for Code Exchange) is mandatory for public clients (mobile apps, SPAs).
- JWT (JSON Web Tokens): Useful for stateless authentication, but validate signatures on every request, check expiration, and never store sensitive data in the payload (it is base64-encoded, not encrypted).
- API keys: Suitable for server-to-server communication. Treat them as secrets — rotate regularly, scope permissions, and never embed in client-side code.
- Mutual TLS (mTLS): Both client and server authenticate via certificates. High security, suitable for internal microservice communication.
What Input Validation Practices Should Every API Implement?
Never trust client input. Validate everything:
- Type checking: If a field expects an integer, reject strings. Use strict typing in your API framework.
- Length limits: Set maximum lengths for all string inputs. A name field should not accept 10,000 characters.
- Allowlisting over denylisting: Define what is acceptable rather than trying to block known-bad patterns.
- Parameterised queries: Always use parameterised queries or prepared statements for database operations. Never concatenate user input into SQL.
- Content-Type validation: Verify the Content-Type header matches the actual request body. Reject mismatches.
- Schema validation: Use OpenAPI/Swagger schemas to automatically validate request structure and reject non-conforming requests.
How Do You Implement Effective Rate Limiting?
Rate limiting prevents abuse, brute force attacks, and resource exhaustion:
- Implement per-user, per-IP, and per-endpoint rate limits. Different endpoints need different thresholds — a login endpoint needs stricter limits than a product listing.
- Use the token bucket or sliding window algorithm for smooth rate limiting.
- Return proper 429 (Too Many Requests) responses with Retry-After headers.
- Consider graduated rate limiting — warn before blocking, then progressively increase cooldown periods.
- For Indian applications handling payment APIs (Razorpay, Cashfree), implement idempotency keys to prevent duplicate transactions even if clients retry requests.
What Monitoring and Logging Practices Protect APIs?
Detection is as important as prevention:
- Log all authentication events: Successful logins, failed attempts, token refreshes, and logouts.
- Monitor for anomalies: Unusual traffic patterns, geographic anomalies, off-hours access, and sudden spikes in specific endpoint usage.
- Track data access: Log which users access which resources, especially bulk data exports.
- Set up alerts: Automated alerts for repeated authentication failures, rate limit violations, and error rate increases.
- Use an API gateway: Centralise security controls (authentication, rate limiting, logging) at the gateway level rather than implementing them in every microservice.
Should API keys be passed in headers or query parameters?
Always use HTTP headers (typically the Authorization header). Query parameters appear in server logs, browser history, and referrer headers, creating unnecessary exposure. If a legacy system requires query parameters, ensure logs are configured to redact them.
How often should API keys and tokens be rotated?
API keys should be rotated every 90 days at minimum, or immediately if compromise is suspected. Access tokens should expire within 15–60 minutes. Refresh tokens should have a maximum lifetime (e.g., 30 days) and be single-use where possible.
Is HTTPS sufficient for API security?
HTTPS (TLS encryption in transit) is necessary but not sufficient. It protects data in transit but does nothing against broken authentication, authorisation flaws, injection attacks, or business logic abuse. HTTPS is the baseline — not the complete security strategy.
How do you secure APIs in a microservices architecture?
Use an API gateway for external-facing security, implement mutual TLS between internal services, use service mesh (Istio, Linkerd) for internal traffic policies, apply the principle of least privilege to service-to-service communication, and maintain a centralised API inventory to prevent shadow APIs.






