Skip to main content
API Security Tutorial
CHAPTER 02 Intermediate

Understanding APIs and Security Risks

Updated: May 13, 2026
15 min read

# CHAPTER 2

Understanding APIs and Security Risks

1. Introduction

Before we can secure an API, we must intimately understand how it functions and where its weak points lie. In this chapter, we will briefly review the anatomy of REST APIs and introduce the concept of the Attack Surface. We will learn how security engineers use Threat Modeling to systematically identify vulnerabilities before writing a single line of code, integrating security into the entire Software Development Life Cycle (SDLC).

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Define the "Attack Surface" of a REST API.
  • Understand the core components of an API request that hackers target.
  • Explain the concept of Threat Modeling.
  • Identify the stages of a Secure Software Development Life Cycle (SSDLC).
  • Recognize the difference between infrastructure vulnerabilities and application logic vulnerabilities.

3. Beginner-Friendly Explanation

Imagine a bank. The Attack Surface is every possible way a thief could get inside: the front door, the back door, the windows, the ventilation shafts, and even the employees.

When building an API, the attack surface includes the URL, the HTTP Headers, the Query Parameters, and the JSON Body.

Threat Modeling is the process of sitting down with the bank's blueprints *before* it is built and asking, "If I were a bank robber, how would I break in?" You look at the blueprints and realize the vault shares a wall with a public restroom. You identify the threat, and you fix the blueprint by moving the vault. This is much cheaper and safer than building the bank and waiting for it to be robbed.

4. Real-World Attack Scenarios

  • The Query Parameter Hack: An e-commerce API has an endpoint: POST /checkout?discount_code=10OFF. An attacker realizes they can manipulate the URL to POST /checkout?discount_code=100OFF or ?price=0.01. If the backend blindly trusts the URL parameters without verifying them against the database, the attacker buys a TV for a penny.
  • The Header Spoofing: An internal API trusts any request that comes with the header X-Forwarded-For: 127.0.0.1 (pretending to be the local server). An external attacker manually adds this header to their Postman request, bypassing the firewall and accessing admin data.

5. Security Examples (The Attack Surface)

Every piece of data sent by the client is part of the attack surface.
  1. 1. URL Paths: /api/users/123 (Can I change 123 to 124?)
  1. 2. Query Strings: ?role=user (Can I change it to ?role=admin?)
  1. 3. Headers: Authorization: Bearer xyz (Can I use an expired token?)
  1. 4. JSON Body: {"age": 25} (Can I send {"age": -50} or {"age": "DROP TABLE users"}?)

6. Vulnerable vs Secure Code Examples (Threat Modeling)

Threat: An attacker attempts to bypass a maximum order limit by sending a negative quantity.

Vulnerable Code:

php
123456
<?php
$quantity = $_POST[&#039;qty']; // Attacker sends -10
$price = 50;
// Total becomes -500. The store ends up owing the attacker money!
$total_cost = $quantity * $price; 
?>

Secure Code (Mitigated via Threat Modeling):

php
123456789101112
<?php
$quantity = (int) $_POST[&#039;qty'];

// Validate the input strictly
if ($quantity <= 0 || $quantity > 5) {
    http_response_code(400);
    echo json_encode(["error" => "Invalid quantity."]);
    exit;
}

$total_cost = $quantity * 50;
?>

7. HTTP Examples

A hacker will use tools like Postman or Burp Suite to intercept and modify standard HTTP requests, looking for weak points in the attack surface.
http
123456789
PUT /api/v1/profile HTTP/1.1
Host: api.example.com
Content-Type: application/json

{
  "name": "John",
  "email": "john@example.com",
  "is_admin": true 
}

*If the API updates the entire database row based on the JSON body, the attacker just granted themselves admin privileges. This is called Mass Assignment.*

8. JSON Examples

Attackers often test the limits of your JSON parser.
json
12345
{
  "username": "a",
  "password": "a",
  "bio": "<script>alert(&#039;Hacked')</script>"
}

*If the API accepts this JSON and saves it to the database, it creates a Cross-Site Scripting (XSS) vulnerability for anyone who views this user's profile.*

9. PHP Examples (The Security Lifecycle)

In a Secure SDLC, security is not an afterthought; it is integrated into the PHP architecture.
  1. 1. Design: Define strict routing and required authentication for all endpoints.
  1. 2. Develop: Use PHP's built-in filter_var() and PDO for secure database interactions.
  1. 3. Test: Write automated PHPUnit or Postman tests that specifically send *malicious* data to ensure the API rejects it.
  1. 4. Deploy: Configure the Apache/Nginx server to use HTTPS and secure headers.

10. Best Practices

  • Assume Breach / Assume Malice: Write your backend code under the assumption that the frontend has already been compromised and the user is actively trying to destroy your database.
  • Implement Threat Modeling: Use methodologies like STRIDE (Spoofing, Tampering, Repudiation, Information Disclosure, Denial of Service, Elevation of Privilege) during the planning phase.
  • Minimize the Attack Surface: Do not expose API endpoints you do not need. If an endpoint is for internal testing, delete it before pushing to production.

11. Common Mistakes

  • Testing Only the "Happy Path": QA teams often only test if the API works when used correctly. Security requires testing how the API behaves when used *incorrectly*.
  • Trusting Hidden Fields: Believing that data is safe because it comes from an invisible HTML <input type="hidden">. Hackers see all HTTP traffic.

12. Security Checklists

Threat Modeling Checklist:
  • [ ] Have we identified all endpoints exposed to the public internet?
  • [ ] What is the absolute worst thing an attacker could do with this specific endpoint?
  • [ ] How are we validating every single parameter in the Request Body, URL, and Headers?
  • [ ] Does this endpoint reveal unnecessary technical information in error messages?

13. Mini Exercises

  1. 1. List the four main parts of an HTTP request that make up the API "Attack Surface".
  1. 2. Explain how changing a single number in a URL (like an ID) could be a security risk.

14. Practice Challenges

Challenge: Look at the following endpoint: POST /api/upload_avatar. Perform a mini threat model. List three different types of malicious files or data an attacker might try to send to this endpoint to compromise the server.

15. MCQs with Answers

Question 1

What is the "Attack Surface" of an API?

Question 2

When is the best time to perform Threat Modeling in the Software Development Life Cycle?

Question 3

If a backend PHP script blindly calculates a price using a multiplier provided in the URL query string, what is the primary risk?

16. Interview Questions

  • Q: Explain the concept of an API's Attack Surface to a non-technical manager.
  • Q: What is Threat Modeling, and what is the STRIDE methodology?
  • Q: Give an example of a vulnerability that exists in the application logic layer rather than the infrastructure layer.

17. FAQs

Q: Is it enough to just install a Web Application Firewall (WAF)? A: No. A WAF is great for blocking generic attacks (like obvious SQL injections), but it does not understand your specific business logic. A WAF cannot tell the difference between User A legitimately accessing their own profile and User A maliciously accessing User B's profile. You must write secure PHP code.

18. Summary

In this chapter, we explored the anatomy of an API attack. We defined the Attack Surface as every URL, Header, and JSON payload exposed to the internet. We learned that proactive security requires Threat Modeling—anticipating how an attacker might manipulate data (like negative quantities or malicious JSON) before writing the code. A secure API is built on the philosophy of never trusting the client.

19. Next Chapter Recommendation

Before we secure the data itself, we must secure the tunnel it travels through. Proceed to Chapter 3: HTTP and HTTPS Security Basics to learn how encryption protects APIs from eavesdroppers.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·