Skip to content

API Security — Complete Guide to Protecting Endpoints

DodaTech Updated 2026-06-28 4 min read

In this tutorial, you will learn about API Security. We cover key concepts, practical examples, and best practices to help you master this topic.

API security protects endpoints against unauthorized access, injection attacks, data exposure, and denial of service through authentication, authorization, encryption, and input validation at every layer.

What You'll Learn

  • The top API security threats and how to mitigate them
  • Authentication and authorization best practices
  • Input validation and Rate Limiting for attack prevention

Why It Matters

APIs expose application logic and data directly to clients. A single unsecured endpoint can leak customer data, allow unauthorized actions, or bring down the entire service.

Real-World Use

Durga Antivirus Pro threat intelligence API implements multi-layered security: TLS encryption, API key authentication, OAuth 2.0 for user-facing endpoints, rate limiting per key, request validation against OpenAPI schema, and audit logging for every request.

flowchart LR
    C["Client"] --> T["TLS"]
    T --> A["Authentication"]
    A --> R["Rate Limiter"]
    R --> V["Input Validation"]
    V --> Auth["Authorization"]
    Auth --> B["Backend"]
    A --> L["Audit Log"]
    style A fill:#dbeafe,stroke:#2563eb

Code Examples

from flask import Flask, request, jsonify, abort

app = Flask(__name__)
API_KEYS = {"sk-abc123": "user_1", "sk-def456": "user_2"}

@app.before_request
def authenticate():
    if request.endpoint in ('health', 'static'):
        return
    api_key = request.headers.get('X-API-Key')
    if not api_key or api_key not in API_KEYS:
        abort(401, description="Missing or invalid API key")
    request.user_id = API_KEYS[api_key]

@app.route('/api/data')
def get_data():
    return jsonify({"user": request.user_id, "data": "sensitive"})

app.run(port=5000)

Expected output: Requests without valid API key receive 401; authenticated requests proceed with user context.

const express = require('express');
const app = express();

app.use(express.json());

function sanitize(input) {
  if (typeof input !== 'string') return input;
  return input.replace(/[<>"'&]/g, '');
}

app.post('/api/search', (req, res) => {
  const query = sanitize(req.body.query);
  if (!query || query.length > 200) {
    return res.status(422).json({ error: 'Invalid query' });
  }
  res.json({ results: [], query });
});

app.listen(3000);

Expected output: Malicious input with HTML/script tags is sanitized; oversized queries are rejected with 422.

from flask import Flask, request, jsonify
from datetime import datetime, timedelta
import threading

app = Flask(__name__)
rate_limits = {}
lock = threading.Lock()

def check_rate_limit(key, max_requests=100, window_seconds=60):
    now = datetime.now()
    with lock:
        if key not in rate_limits:
            rate_limits[key] = []
        rate_limits[key] = [t for t in rate_limits[key] if now - t < timedelta(seconds=window_seconds)]
        if len(rate_limits[key]) >= max_requests:
            return False
        rate_limits[key].append(now)
        return True

@app.route('/api/data')
def get_data():
    api_key = request.headers.get('X-API-Key', request.remote_addr)
    if not check_rate_limit(api_key):
        return jsonify({"error": "Rate limit exceeded"}), 429
    return jsonify({"data": "ok"})

Expected output: Clients exceeding 100 requests per 60-second window receive 429 rate limit response.

Common Mistakes

1. Exposing Internal IPs or Ports

Error messages that reveal internal infrastructure (database IP, stack traces) give attackers information for targeted attacks.

2. Relying Only on Security Through Obscurity

Hiding endpoints with obscure URLs is not security. Always implement proper authentication.

3. Insufficient Rate Limiting

Without rate limiting, a single attacker can brute-force credentials or exhaust server resources with DDoS.

4. Not Validating Input Types

An endpoint expecting an integer that receives an object can crash. Validate types strictly.

5. Logging Sensitive Data

Logging passwords, API keys, or credit card numbers in plaintext creates a secondary data breach risk.

Practice Questions

  1. What is the principle of defense in depth for API security?
  2. Why should you never expose stack traces in API error responses?
  3. How does rate limiting protect against denial of service?
  4. What is input validation and why is it critical for security?
  5. Why should sensitive data never be logged?

Answers:

  1. Multiple independent security layers so a single failure does not expose the API.
  2. Stack traces reveal code structure, library versions, and internal paths that help attackers craft exploits.
  3. Rate limiting caps requests per client, preventing any single client from overwhelming the server.
  4. Input validation rejects malformed or malicious data before it reaches business logic.
  5. Logged sensitive data can be exposed through log breaches, violating Compliance (GDPR, PCI-DSS) and user trust.

Challenge: Perform a security audit on a mock payment API. Identify three vulnerabilities, write exploit proofs-of-concept, and implement fixes for each.

FAQ

What is OWASP API Security Top 10?

: A list of the ten most critical API security risks published by OWASP, including broken authentication and excessive data exposure.

Should every endpoint require authentication?

: Public endpoints (health checks, docs) can be unauthenticated, but data endpoints must verify identity.

What is a JWT and why is it used for API auth?

: JSON Web Token is a self-contained token carrying user claims and a signature, eliminating server-side session storage.

How do you protect against Mass Assignment attacks?

: Use DTOs to explicitly define which fields clients can set, never directly binding request bodies to database models.

What is CORS and why does it matter for API security?

: CORS controls which web domains can call your API from browsers, preventing unauthorized cross-origin requests.

Mini Project

Implement a secure API with four layers: TLS (self-signed cert), API key authentication with rotation support, rate limiting (100 req/min), and input validation using Pydantic or Zod schemas. Include tests that verify each layer blocks invalid requests.

What's Next

Learn about API authentication methods for deeper coverage of OAuth, JWT, and API keys, or explore API gateway security features for centralized protection.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro