API & BACKEND ARCHITECTURE / SYSTEM CONCEPT BRIEF

API security

API security protects your endpoints from unauthorized access, data leaks, abuse, and attacks.

IntermediatePhase 02 / Topic 12 of 20RequirementsTrade-offsFailure modes
01

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.

A bank branch

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.

02

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?'.
03

Where it shows up in interviews

Securing a design

Recognize it when: interviewer asks how you would protect the system.

  • Secure a payment API
  • Secure a healthcare records API
Abuse prevention

Recognize it when: bots, scraping, credential stuffing, fraud.

  • Design a ticketing system against bots
  • Protect a login endpoint
04

Where it is used in real software

OWASP API Security Top 10

Lists broken object level authorization, broken authentication, excessive data exposure, lack of resource limits, and more.

Secrets managers

AWS Secrets Manager, HashiCorp Vault, and Azure Key Vault store and rotate API keys and database passwords instead of hardcoding them.

Real incidents

Many large data leaks came from APIs returning full user objects or allowing sequential ID enumeration without authorization checks.

05

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.
06

Defense layers for every request

  1. 1
    Transport

    HTTPS only, HSTS, modern TLS.

  2. 2
    Authenticate

    Validate tokens or keys; reject missing or expired credentials.

  3. 3
    Authorize per object

    Confirm this caller may perform this action on this resource.

  4. 4
    Validate input

    Schema validation with allow-listed fields, types, sizes, and formats; parameterized queries.

  5. 5
    Limit resources

    Rate limits, payload size limits, pagination caps, and timeouts.

  6. 6
    Minimize output

    Return only needed fields; generic error messages; no stack traces.

  7. 7
    Observe

    Audit logs, anomaly detection, and alerts on unusual patterns.

07

Common API vulnerabilities and fixes

Based on the OWASP API Security Top 10

Step 1 / 6
VulnerabilityExampleFix
Broken object authorizationGET /orders/124 returns another user's orderCheck ownership on every access
Mass assignmentPATCH /users/me { role: 'admin' }Allow-list updatable fields
Excessive data exposureReturning passwordHash in JSONExplicit response DTOs
No rate limitingBrute forcing OTP codesPer-user and per-IP limits
SQL injectionBuilding SQL with string concatenationParameterized queries / ORM
SSRFImport from URL fetches http://169.254.169.254Allow-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.

08

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],);
09

Complexity and performance

Validation overhead< 1 ms

Schema checks are cheap.

Token verification< 1 ms

Cached keys.

10

Trade-offs

Gateway vs service controls

Gateways handle authentication, rate limits, and WAF rules uniformly; only services understand object ownership and business rules.

Detailed vs generic errors

Detailed errors help developers but reveal internals to attackers; return stable error codes and log details server-side.

11

Variants and related techniques

mTLS for internal APIs

Services authenticate each other with certificates in a zero-trust network.

Request signing

HMAC signatures on requests (like AWS SigV4 or webhooks) prove integrity and origin.

12

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.

13

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.

14

Practice problems

ProblemDifficultyWhat it trains
Find 5 vulnerabilities in a sample API specEasyOWASP checklist.
Threat model a payments APIMediumSTRIDE and controls.
Design webhook delivery with signatures and retriesMediumIntegrity and replay.