Overview
API security protects your endpoints from unauthorized access, data leaks, abuse, and attacks. Because APIs expose business logic and data directly, the most common failures are not exotic hacks but missing checks: returning another user's data, trusting client input, exposing too many fields, or allowing unlimited requests.
A secure API layers several defenses: HTTPS everywhere, strong authentication, per-object authorization, strict input validation, rate limiting and quotas, safe error handling, secrets management, and monitoring. The OWASP API Security Top 10 is the standard checklist.
The bank checks ID at the counter (authentication), confirms the account is yours before withdrawals (authorization), limits how much cash one person can take per day (rate limits), and records every transaction on camera (audit logs). One missing control is enough for a robbery.
When to use it
- Every API, internal or external.
- Security reviews and threat modeling.
- Designing public APIs, partner integrations, and mobile backends.
- Interview follow-ups: 'how would you secure this?'.
Where it shows up in interviews
Recognize it when: interviewer asks how you would protect the system.
- Secure a payment API
- Secure a healthcare records API
Recognize it when: bots, scraping, credential stuffing, fraud.
- Design a ticketing system against bots
- Protect a login endpoint
Where it is used in real software
Lists broken object level authorization, broken authentication, excessive data exposure, lack of resource limits, and more.
AWS Secrets Manager, HashiCorp Vault, and Azure Key Vault store and rotate API keys and database passwords instead of hardcoding them.
Many large data leaks came from APIs returning full user objects or allowing sequential ID enumeration without authorization checks.
Key terms
- BOLA / IDOR
- Accessing objects that belong to others by changing IDs.
- Mass assignment
- Clients setting fields they should not (isAdmin: true) because the server binds the whole body.
- Input validation
- Reject requests that do not match the expected schema, types, and limits.
- Injection
- Untrusted input interpreted as code: SQL, NoSQL, command, template injection.
- SSRF
- Server-side request forgery: tricking the server into calling internal URLs.
Defense layers for every request
- 1Transport
HTTPS only, HSTS, modern TLS.
- 2Authenticate
Validate tokens or keys; reject missing or expired credentials.
- 3Authorize per object
Confirm this caller may perform this action on this resource.
- 4Validate input
Schema validation with allow-listed fields, types, sizes, and formats; parameterized queries.
- 5Limit resources
Rate limits, payload size limits, pagination caps, and timeouts.
- 6Minimize output
Return only needed fields; generic error messages; no stack traces.
- 7Observe
Audit logs, anomaly detection, and alerts on unusual patterns.
Common API vulnerabilities and fixes
Based on the OWASP API Security Top 10
| Vulnerability | Example | Fix |
|---|---|---|
| Broken object authorization | GET /orders/124 returns another user's order | Check ownership on every access |
| Mass assignment | PATCH /users/me { role: 'admin' } | Allow-list updatable fields |
| Excessive data exposure | Returning passwordHash in JSON | Explicit response DTOs |
| No rate limiting | Brute forcing OTP codes | Per-user and per-IP limits |
| SQL injection | Building SQL with string concatenation | Parameterized queries / ORM |
| SSRF | Import from URL fetches http://169.254.169.254 | Allow-list destinations, block internal ranges |
NOWVulnerability: Broken object authorization | Example: GET /orders/124 returns another user's order | Fix: Check ownership on every access
Most issues are missing checks in application code, which gateways and WAFs cannot fully fix. Authorization and validation must live in the service.
Implementation
import { z } from "zod"; // Allow-list exactly which fields a client may updateconst UpdateProfile = z.object({ displayName: z.string().trim().min(1).max(50), bio: z.string().max(280).optional(),}).strict(); // unknown fields (like role) are rejected app.patch("/v1/users/me", async (req, res) => { const parsed = UpdateProfile.safeParse(req.body); if (!parsed.success) return res.status(400).json({ error: { code: "invalid_request" } }); const user = await users.update(req.user.id, parsed.data); // only the caller's own record res.json({ id: user.id, displayName: user.displayName, bio: user.bio }); // explicit output}); // Parameterized query: input can never change the SQL structureconst orders = await db.query( "SELECT id, total FROM orders WHERE user_id = $1 AND status = $2 LIMIT 50", [req.user.id, req.query.status],);Complexity and performance
Schema checks are cheap.
Cached keys.
Trade-offs
Gateways handle authentication, rate limits, and WAF rules uniformly; only services understand object ownership and business rules.
Detailed errors help developers but reveal internals to attackers; return stable error codes and log details server-side.
Variants and related techniques
Services authenticate each other with certificates in a zero-trust network.
HMAC signatures on requests (like AWS SigV4 or webhooks) prove integrity and origin.
Common mistakes
- Assuming internal APIs are safe.
Fix: Apply authentication and authorization inside the network too (zero trust).
- Hardcoded secrets in code or images.
Fix: Use a secrets manager and rotate credentials.
- Logging tokens and personal data.
Fix: Redact sensitive fields in logs.
Interview questions
How would you secure a public REST API?
HTTPS only; OAuth or API keys at the gateway; per-object authorization in services; schema validation; rate limits and quotas; minimal responses; secrets in a vault; audit logging and anomaly alerts.
How do you secure webhooks you send to customers?
Sign each payload with an HMAC using a per-customer secret and include a timestamp, so receivers can verify authenticity and reject replays.
Practice problems
| Problem | Difficulty | What it trains |
|---|---|---|
| Find 5 vulnerabilities in a sample API spec | Easy | OWASP checklist. |
| Threat model a payments API | Medium | STRIDE and controls. |
| Design webhook delivery with signatures and retries | Medium | Integrity and replay. |