On this page

API Security

API security means protecting your APIs from people who shouldn't use them, and from people who try to misuse them. APIs are the front door to your data, so most real attacks today target APIs, not web pages.

The Main Layers

1Client → HTTPS → API Gateway → Service → Database
2 │ │ │ │
3 encrypt auth, rate authorize, least-privilege
4 traffic limit, CORS validate DB user

No single check is enough. Each layer stops a different attack. This idea is called defense in depth.

1. Use HTTPS Everywhere

HTTPS (TLS) encrypts data between client and server. Without it, anyone on the network can read passwords and tokens.

  • Redirect HTTP to HTTPS, or block HTTP completely.
  • Use HSTS so browsers never fall back to HTTP.
  • Use mTLS (both sides show certificates) for service-to-service calls inside the system.

2. Authentication and Authorization

  • Authenticate every request (session, JWT, API key, OAuth).
  • Authorize every request on the server, including ownership checks.

The #1 API bug is BOLA (Broken Object Level Authorization):

1Ravi calls GET /orders/502 (order 502 belongs to Priya)
2Server checks only "is Ravi logged in?" → returns Priya's order ✘
3Fix: check order.userId == Ravi's id

3. Validate All Input

Never trust anything the client sends: body, query params, headers, file uploads.

  • Validate type, length, format, and allowed values.
  • Use parameterized queries to prevent SQL injection.
  • Reject unknown fields to prevent mass assignment:
1PUT /users/101 { "name": "Ravi", "role": "ADMIN" }
2If the server blindly saves every field → Ravi becomes admin ✘
3Fix: accept only allowed fields (name, phone)
  • Limit request body size so huge payloads can't crash the server.

4. Rate Limiting and Throttling

Limit how many requests a client can make, e.g. 100 requests/min per user.

Protects against:

  • Brute-force login attempts
  • Scraping
  • DoS (flooding the API)

Return 429 Too Many Requests when the limit is hit. Apply stricter limits on sensitive endpoints like login and OTP.

5. Don't Expose Too Much Data

  • Return only the fields the client needs, not the whole database row.
  • Never return password hashes, internal IDs, or other users' data.
  • Hide internal details in errors:
BadGood
"SQL error at line 42 in users table""Something went wrong" + error ID
"Password wrong for ravi@mail.com""Invalid email or password"

6. Configure CORS Correctly

CORS tells browsers which websites may call your API.

  • Allow only your own frontend domains.
  • Never use Access-Control-Allow-Origin: * together with credentials (cookies).

CORS protects browser users only. It does not stop tools like Postman or scripts, so it's never a replacement for authentication.

7. Protect Secrets

  • Never put API keys or passwords in code or Git.
  • Store them in a secret manager (Vault, AWS Secrets Manager).
  • Rotate keys regularly, and revoke leaked ones immediately.

8. Logging and Monitoring

You can't stop what you can't see.

  • Log auth failures, 403s, and rate-limit hits.
  • Alert on spikes (e.g., 1,000 failed logins from one IP).
  • Never log passwords, tokens, or card numbers.

Where Each Check Belongs

CheckBest place
HTTPS termination, rate limiting, token validation, CORSAPI Gateway
Ownership checks, input validation, business rulesService
Least-privilege DB user, encryption at restDatabase

The gateway handles common checks once, so every service doesn't repeat them.

OWASP API Top Risks (Quick View)

The OWASP API Security Top 10 is the standard list of the most common API risks. The ones to remember for interviews:

RiskIn one line
Broken Object Level Authorization (BOLA)Accessing someone else's resource by changing an ID
Broken AuthenticationWeak login, leaked or unvalidated tokens
Broken Property Level AuthorizationExposing or editing fields you shouldn't (mass assignment)
Unrestricted Resource ConsumptionNo rate limits or size limits
Broken Function Level AuthorizationNormal user calling admin endpoints
Security MisconfigurationOpen CORS, debug mode on, default passwords

Summary

1HTTPS everywhere → authenticate + authorize every request
2→ validate all input → rate limit
3→ return minimal data, hide internal errors
4→ strict CORS, secrets in a vault
5→ log and monitor → layers together = defense in depth

Next, we'll look at Encryption, which keeps data safe both while it travels and while it's stored.

Next TopicEncryption