Skip to content

Security Testing for APIs — Complete Guide

DodaTech Updated 2026-06-28 3 min read

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

API security testing identifies vulnerabilities before attackers do. It covers authentication bypass, privilege escalation, injection attacks, rate limiting effectiveness, CORS Misconfiguration, and sensitive data exposure. Security tests should be part of your regular test suite.

What You'll Learn

  • Authentication and authorization testing
  • Injection attacks (SQL, NoSQL, command)
  • Rate limiting and brute force protection
  • CORS and security header testing
  • API key and token exposure checks

Why It Matters

OWASP lists API security as a top concern. Security breaches through APIs cost millions. Automated security testing catches common vulnerabilities before they reach production.

Real-World Use

GitHub runs automated security scans on API changes. Stripe has dedicated security testing for payment APIs. Financial APIs undergo regular Penetration Testing and automated security scanning.

flowchart TD
    Security[Security Tests] --> Auth[Auth Tests]
    Security --> Inject[Injection Tests]
    Security --> Rate[Rate Limit Tests]
    Security --> CORS[CORS Tests]
    Security --> Exposure[Data Exposure Tests]
    Auth --> Token[Missing Token]
    Auth --> Expired[Expired Token]
    Auth --> WrongRole[Insufficient Role]
    Inject --> SQL[SQL Injection]
    Inject --> XSS[XSS via Input]
    Rate --> Brute[Brute Force Attempts]

Teacher Mindset

Test security from an attacker's perspective. Try to bypass authentication. Try to access data you should not see. Try to crash the server with unexpected input. Document what protections exist and verify they work.

Code Examples

// Example 1: Auth bypass tests (Supertest)
describe('Authentication security', () => {
  it('rejects requests without token', async () => {
    await request(app)
      .get('/api/admin/users')
      .expect(401);
  });

  it('rejects expired tokens', async () => {
    await request(app)
      .get('/api/admin/users')
      .set('Authorization', 'Bearer ' + expiredToken)
      .expect(401);
  });

  it('rejects users without admin role', async () => {
    await request(app)
      .get('/api/admin/users')
      .set('Authorization', 'Bearer ' + userToken)
      .expect(403);
  });
});
# Example 2: Injection tests
import httpx
import pytest

injection_payloads = [
    "admin' --",
    "1; DROP TABLE users",
    "${7*7}",
    "<script>alert('xss')</script>",
    "../../../etc/passwd",
]

@pytest.mark.parametrize("payload", injection_payloads)
@pytest.mark.asyncio
async def test_sql_injection(client, payload):
    response = await client.get(f"/api/users?name={payload}")
    # Should not return 500 or expose database errors
    assert response.status_code in [400, 422, 200]
    if response.status_code == 200:
        data = response.json()
        assert isinstance(data, list)
# Example 3: Rate limiting test with curl
#!/bin/bash
# Test rate limiting by sending 100 rapid requests
for i in $(seq 1 100); do
    response=$(curl -s -o /dev/null -w "%{http_code}" \
      -H "Authorization: Bearer $TOKEN" \
      http://api.example.com/api/users)
    echo "Request $i: $response"
    if [ "$response" == "429" ]; then
        echo "Rate limit triggered at request $i"
        break
    fi
done

Common Mistakes

  • Only testing security with valid credentials and happy paths
  • Forgetting to test for information leakage in error messages
  • Not testing CORS for overly permissive configurations
  • Ignoring API key exposure in logs and error responses
  • Testing security only once instead of continuously

Practice

  1. Write a test that verifies 401 for missing auth token.
  2. Write a test that verifies 403 for unauthorized role access.
  3. Test that SQL Injection attempts return 400/422 instead of 500.
  4. Verify that rate limiting returns 429 after N rapid requests.
  5. Challenge: Write a comprehensive security test suite covering OWASP API Top 10.

FAQ

What is the OWASP API Security Top 10?

A list of the most critical API security risks including broken authentication, excessive data exposure, and injection.

Should I run security tests in CI?

Yes. Security tests should run on every pull request to catch regressions early.

What is the difference between SAST and DAST?

SAST analyzes source code. DAST tests running applications. API security tests are DAST.

Can I automate penetration testing?

Automated tools catch common vulnerabilities. Manual penetration testing is still needed for complex logic flaws.

How do I test for data exposure?

Check that sensitive fields (passwords, tokens) are not returned in responses. Verify error messages do not leak internal details.

Mini Project

Write a security test suite for your API covering: authentication bypass (missing, expired, invalid tokens), authorization (user accessing admin endpoints), injection (SQL, NoSQL, XSS payloads), rate limiting (verify 429 response), CORS (verify restrictive policy), and data exposure (no sensitive fields in responses).

What's Next

Next, you will learn about integrating API tests into CI/CD pipelines.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro