Api Security Testing

Production-grade guide to api security testing covering architecture patterns, implementation strategies, testing approaches, and operational best practices for enterprise engineering teams.

Api Security Testing is the practice of validating the security posture of RESTful and GraphQL APIs through automated and manual techniques, applied at every stage of the development lifecycle. It matters when APIs serve as the primary integration layer between services, third-party clients, or public-facing microservices — especially when those APIs handle sensitive data, authentication, or transactional workflows. The testing ensures that APIs are resilient against common threats: broken authentication, injection flaws, excessive data exposure, rate limiting bypasses, and misconfigured access controls.

Validating Authentication and Authorization

Authentication and authorization are the first lines of defense in API security. Testing must verify that:

To validate authentication, begin with a curl script that exercises the /auth/login endpoint with malformed and valid payloads:

curl -X POST https://api.example.com/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "username": "alice",
    "password": "secret123"
  }' \
  -v

A successful response includes a Set-Cookie header with a secure, HTTP-only session cookie, and a Bearer token in the Authorization header:

HTTP/1.1 200 OK
Content-Type: application/json
Set-Cookie: session=abc123; Path=/; Secure; HttpOnly; SameSite=Lax
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJh bGljZSIsIm5hbWUiOiJBbGljZSBNb3V0aCIsImlhdCI6MTYyMzQwMTIzNH0.x2vK9bT8XrK9uZ9iBtG4YqTcTtEw0RZqjKb4KcVnBkI

Failures appear when the API returns 401 Unauthorized with a JSON body that includes error, message, and code fields:

{
  "error": "invalid_token",
  "message": "The provided JWT token is expired or invalid.",
  "code": "token_expired",
  "details": {
    "exp": 1623401234,
    "iat": 1623400934
  }
}

To validate authorization, test a user with a role: "editor" accessing a /posts/{id} endpoint. The API should return 403 Forbidden when a role: "viewer" attempts to update a post:

curl -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJh bGljZSIsInJvbGUiOiJ2aWV3ZXIi..." \
  https://api.example.com/posts/42 \
  -X PUT \
  -d '{"title": "Updated Title"}'

A well-structured API should return:

{
  "error": "forbidden",
  "message": "User does not have permission to update posts.",
  "code": "user_not_editor",
  "required_roles": ["editor", "admin"]
}

Common Pitfalls

Testing for Injection and Data Validation

APIs accept data from multiple sources: JSON bodies, query parameters, headers, and form data. Injection testing must uncover vulnerabilities in input handling.

SQL Injection

Test endpoints that accept user-provided identifiers in the path or query:

curl 'https://api.example.com/users?name=john%27%20OR%201%3D1%20--'

If the backend uses raw SQL, a successful injection returns all users, including a forged user with id = 0, name = 'john', and role = 'admin'. The database logs should show the full query:

SELECT * FROM users WHERE name = 'john'' OR 1=1 --';

Use psql to verify that the query is not prepared:

SELECT * FROM users WHERE name = 'john'' OR 1=1 --';
-- Expected: 100+ rows, one with id = 0, name = 'john', role = 'admin'

JSON Injection and Schema Validation

A /api/v1/orders endpoint expects a JSON body with items as an array of objects. Test with malformed and deeply nested data:

{
  "customer_id": 123,
  "items": [
    {
      "product_id": 456,
      "quantity": 2,
      "metadata": {
        "price": 29.99,
        "tags": ["premium", "on-sale"],
        "config": {
          "color": "blue",
          "size": "large"
        }
      }
    },
    {
      "product_id": 789,
      "quantity": 1,
      "metadata": {
        "price": 19.99,
        "tags": ["new"],
        "config": {
          "color": "red",
          "size": "small",
          "custom_fields": {
            "gift_wrapping": true,
            "note": "Please wrap carefully"
          }
        }
      }
    }
  ],
  "notes": "Special delivery request",
  "extra": {
    "debug": true,
    "version": 1.2,
    "config": {
      "retry": 3,
      "timeout": 30000
    }
  }
}

The API must validate:

Failures appear when:

Validation Failure Modes

{
  "error": "validation_failed",
  "message": "The request body failed validation.",
  "details": [
    {
      "field": "items",
      "error": "required",
      "message": "The items array is required."
    },
    {
      "field": "customer_id",
      "error": "type_mismatch",
      "expected": "integer",
      "actual": "string",
      "message": "Expected customer_id to be an integer."
    }
  ]
}

Validating Rate Limiting and Throttling

Rate limiting protects APIs from abuse and denial-of-service attacks. Test the following:

Use a loop in bash or curl to simulate 100 requests over 60 seconds:

for i in {1..100}; do
  curl -H "Authorization: Bearer $TOKEN" \
    https://api.example.com/users/1 \
    -s -o /dev/null -w "\nStatus: %{http_code}, Rate-Limit: %{x-http-rate-limit}\n"
  sleep 0.6
done

Expected response headers:

HTTP/1.1 200 OK
Content-Type: application/json
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 99
X-RateLimit-Reset: 1623401234

After 100 requests, the API returns 429 Too Many Requests:

{
  "error": "rate_limit_exceeded",
  "message": "The rate limit has been exceeded.",
  "retry_after": 30,
  "limit": 100,
  "remaining": 0,
  "reset_at": 1623401234
}

Failure Modes

Testing for Excessive Data Exposure and Response Consistency

APIs often return more data than needed. Test for:

Test /api/v1/users/1 with a fields query parameter:

curl 'https://api.example.com/users/1?fields=id,name,email,posts.title,posts.status'

The API should return a consistent structure:

{
  "id": 1,
  "name": "Alice",
  "email": "[email protected]",
  "posts": [
    {
      "id": 101,
      "title": "Building APIs",
      "status": "published",
      "created_at": "2021-05-15T10:00:00Z"
    },
    {
      "id": 102,
      "title": "Security Testing",
      "status": "draft",
      "created_at": "2021-06-20T14:30:00Z"
    }
  ]
}

But testing reveals:

Response Consistency Checks

{
  "results": [...],
  "pagination": {
    "page": 2,
    "limit": 10,
    "total": 157,
    "pages": 16
  },
  "meta": {
    "timestamp": "2021-06-21T08:00:00Z",
    "request_id": "req-abc123"
  }
}

A failure occurs when meta.request_id is present but pagination.total is missing, or when pagination.page is a string instead of integer.

Testing for Security Headers and Response Hardening

Ensure the API sends security-relevant headers in every response:

Content-Type: application/json
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-Permitted-Cross-Domain-Policies: none
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
Referrer-Policy: strict-origin-when-cross-origin
Feature-Policy: geolocation 'self'; camera 'self'; microphone 'self'

Use curl to verify the headers:

curl -I https://api.example.com/users/1

A common failure: the API sends Content-Type: application/json, but the client expects application/json; charset=utf-8 — the charset is missing, causing encoding issues for non-ASCII characters.

Automating API Security Testing in CI

Integrate testing into CI using curl, jq, and bash scripts. A typical .gitlab-ci.yml job:

api-security-tests:
  image: curlimages/curl:latest
  script:
    - |
      # Test authentication
      curl -s -o auth.json -w "Status: %{http_code}" \
        -X POST https://api.example.com/auth/login \
        -H "Content-Type: application/json" \
        -d '{"username":"admin","password":"admin"}'
      jq -e '.error == null and .data.token' auth.json || exit 1

    - |
      # Test rate limiting
      for i in {1..10}; do
        curl -s -H "Authorization: Bearer $(cat auth.json | jq -r .data.token)" \
          https://api.example.com/users/1 -o /dev/null -w "%{http_code}\n"
        sleep 1
      done

    - |
      # Test injection
      curl -s 'https://api.example.com/users?name=john%27%20OR%201%3D1%20--' \
        -H "Accept: application/json" \
        -o users-inj.json
      jq -e '.[0].id == 0 and .[0].name == "john"' users-inj.json || exit 1

This pipeline fails when:

Final Checklist

This page was rewritten on 12 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.