API Security How APIs Work Request Response
Before you can secure an API, you need to understand exactly how it communicates. Every API interaction follows the same basic pattern: a client sends a request, and a server sends back a response. The rules governing that conversation are defined by a protocol called HTTP.
This topic breaks down the request-response cycle in detail, explains the HTTP methods and status codes that every API uses, and shows you exactly where security problems can appear in each part of the communication.
The Request-Response Model
All HTTP-based APIs operate on a simple request-response model. The client (your app, a browser, or a program) asks for something. The server processes that request and sends back an answer.
Nothing happens unless the client asks first. Servers do not push data to clients on their own in a standard REST API — they only respond when called.
The Basic Request-Response Cycle
CLIENT SERVER
| |
| --- HTTP Request ----------> |
| Method: GET |
| URL: /api/users/101 |
| Headers: Authorization: ... |
| |
| <-- HTTP Response ---------- |
| Status: 200 OK |
| Body: { "name": "Priya" } |
| |
Every API call follows this diagram. The client always initiates. The server always responds. Your job as a security professional is to protect both sides of this conversation.
Anatomy of an HTTP Request
An HTTP request has four parts. Understanding each one tells you where attackers can inject malicious content.
Part 1: The Method
The HTTP method tells the server what action the client wants to perform. The most common methods in APIs are:
GET → Retrieve data. Does not change anything.
Example: GET /api/products/5
(Get information about product number 5)
POST → Send new data to create something.
Example: POST /api/orders
Body: { "product_id": 5, "quantity": 2 }
(Place a new order)
PUT → Replace existing data entirely.
Example: PUT /api/users/101
Body: { "name": "Priya Sharma", "email": "priya@example.com" }
(Replace all user 101 data)
PATCH → Update part of existing data.
Example: PATCH /api/users/101
Body: { "email": "new@example.com" }
(Only update the email, leave everything else)
DELETE → Remove data.
Example: DELETE /api/orders/887
(Cancel order 887)
Security note: APIs that allow DELETE or PUT requests without proper authorization checks are extremely dangerous. An attacker who figures out the URL pattern can delete or overwrite other users' data.
Part 2: The URL and Query Parameters
The URL tells the server which resource the client is asking about. It often contains parameters that specify exactly what data is needed.
Full URL example: https://api.shop.com/v1/orders?user_id=101&status=pending&limit=10 Breaking it down: - https:// → Protocol (encrypted communication) - api.shop.com → Domain (the server) - /v1/orders → Path (the specific API endpoint) - ? → Start of query parameters - user_id=101 → Query parameter 1 (filter by user ID) - &status=pending → Query parameter 2 (filter by order status) - &limit=10 → Query parameter 3 (return max 10 results)
Security risk: If the API uses user_id=101 to return that user's orders, what happens if an attacker changes it to user_id=102? If the API does not verify that the requesting user actually owns account 102, the attacker sees someone else's orders. This is a Broken Object Level Authorization vulnerability — one of the most common API flaws in the world.
Part 3: Request Headers
Headers carry metadata — extra information about the request that is not part of the actual data being sent. They travel invisibly alongside the request.
Common Security-Relevant Headers: Authorization: Bearer eyJhbGciOiJIUzI1NiJ9... → Carries the access token that proves who you are. Content-Type: application/json → Tells the server what format the request body is in. Accept: application/json → Tells the server what format the client wants the response in. User-Agent: Mozilla/5.0 ... → Identifies the software making the request. X-API-Key: sk_live_abc123xyz → Some APIs use this header for API key authentication. Cookie: session_id=abc123 → Carries session cookies for web-based authentication.
Security risk: The Authorization header is the most security-sensitive header. If an attacker intercepts it (through a man-in-the-middle attack on unencrypted connections) or steals it from a client (through XSS or insecure storage), they can make requests impersonating the victim.
Part 4: The Request Body
POST, PUT, and PATCH requests carry a body — the actual data being sent to the server. Most modern APIs use JSON format for the body.
Example POST request body (creating a new user):
POST /api/users HTTP/1.1
Host: api.example.com
Content-Type: application/json
Authorization: Bearer sk_admin_token_here
{
"name": "Rajan Mehta",
"email": "rajan@example.com",
"role": "viewer",
"plan": "free"
}
Security risk: What if an attacker adds extra fields to this body, like "role": "admin"? If the server accepts and processes all fields without filtering them, the attacker just promoted themselves to admin. This is called a mass assignment attack, covered in detail in a later topic.
Anatomy of an HTTP Response
After the server processes the request, it sends back a response. The response also has multiple parts, each with security implications.
Part 1: Status Codes
Status codes are three-digit numbers that tell the client what happened with the request. They are organized into categories.
2xx = SUCCESS 200 OK → Request worked. Here is the data you asked for. 201 Created → New resource was created successfully. 204 No Content → Request worked but there is no data to return. 3xx = REDIRECTION 301 Moved Permanently → Resource moved to a new URL. 302 Found → Temporary redirect. 4xx = CLIENT ERRORS (the request had a problem) 400 Bad Request → Request was malformed or invalid. 401 Unauthorized → No valid authentication provided. 403 Forbidden → Authenticated but not allowed to do this. 404 Not Found → Resource does not exist. 429 Too Many Requests → Rate limit exceeded. 5xx = SERVER ERRORS (the server had a problem) 500 Internal Server Error → Something broke on the server. 503 Service Unavailable → Server is down or overloaded.
Security importance: The difference between 401 and 403 is significant. A 401 means the user is not logged in. A 403 means they are logged in but not permitted. APIs that return the wrong code confuse clients and make security logic harder to implement correctly.
Another risk: APIs that return 200 OK even on failures — hiding error details inside the body — make it hard to detect attacks. Consistent, correct status codes are a security requirement, not just a style preference.
Part 2: Response Headers
Response headers carry information from the server about how the client should handle the response. Several security headers belong here.
Security-Critical Response Headers: Content-Type: application/json → Tells the client what format the response is in. Content-Security-Policy: default-src 'self' → Restricts what resources a web page can load (XSS defense). Strict-Transport-Security: max-age=31536000 → Forces HTTPS connections for one year (HSTS). X-Content-Type-Options: nosniff → Prevents browsers from guessing the content type. X-Frame-Options: DENY → Prevents the page from being embedded in iframes (clickjacking defense). Cache-Control: no-store → Tells caches not to store this response (important for sensitive data).
Many APIs are deployed without these security headers. A missing Strict-Transport-Security header means a browser might accept an HTTP connection instead of HTTPS, opening the door for interception attacks.
Part 3: Response Body
This is the actual data the server sends back. For most APIs, it is JSON.
Example response to GET /api/users/101:
HTTP/1.1 200 OK
Content-Type: application/json
{
"id": 101,
"name": "Priya Sharma",
"email": "priya@example.com",
"plan": "premium",
"created_at": "2024-01-15T10:30:00Z"
}
Security risk: What if the response also included fields like "password_hash", "internal_notes", or "credit_card_last4"? If the server pulls a full database row and dumps it directly into the response without filtering, sensitive data leaks to anyone who calls the API. This is called Excessive Data Exposure and is one of the OWASP Top 10 API vulnerabilities.
HTTP Versions and Their Security Implications
HTTP has gone through versions over the years, and each version has different security characteristics.
HTTP/1.1 → The traditional version. Still widely used. → Plain text over HTTP is completely readable by anyone intercepting traffic. → Must be upgraded to HTTPS (HTTP + TLS encryption) for any sensitive data. HTTP/2 → Faster than HTTP/1.1. Uses binary instead of text. → Supports multiplexing (multiple requests over one connection). → Still requires TLS for use with browsers. → Introduced new attack surfaces: header compression attacks (HPACK). HTTP/3 → Uses QUIC protocol instead of TCP. → Faster connection setup, better performance on lossy networks. → TLS 1.3 is built in — you cannot use HTTP/3 without encryption.
The key point: no version of HTTP is automatically secure. You must always use TLS encryption (HTTPS) to protect API traffic from interception.
The Role of DNS in API Security
Before a request even reaches an API, the client must translate the domain name (like api.example.com) into an IP address using DNS. This lookup is a potential attack point.
Normal DNS Lookup: Client asks: "What is the IP for api.example.com?" DNS responds: "It is 203.0.113.45" Client connects to 203.0.113.45 DNS Attack (DNS Spoofing): Attacker intercepts DNS query Attacker responds: "It is 198.51.100.99" (their server) Client connects to attacker's server thinking it is the real API
Even with HTTPS, a spoofed IP can trick a client into connecting to the wrong server — unless certificate validation is enforced. This is why certificate validation is not optional.
Cookies vs Tokens in API Communication
Web browsers use cookies to maintain sessions. APIs typically use tokens. Both have different security profiles.
COOKIES (traditional web sessions): Sent automatically by browser with every request to the same domain. Vulnerable to CSRF attacks if not protected with SameSite attributes. Example header: Cookie: session_id=abc123 TOKENS (modern API auth): Must be explicitly included in request headers or body. Not automatically sent by browsers — reduces CSRF risk. Vulnerable to theft through XSS if stored in JavaScript-accessible memory. Example header: Authorization: Bearer eyJhbGciOiJIUzI1NiJ9...
Most modern APIs prefer token-based authentication because it works cleanly across mobile apps, servers, and browsers without relying on browser cookie mechanics.
What Happens When You Make an API Call: End to End
Seeing the full journey of a single API call helps you understand where every security layer fits.
Step 1: DNS Resolution
Your app asks: "Where is api.bank.com?"
DNS returns: 203.0.113.10
Step 2: TCP Connection
Your app connects to 203.0.113.10 on port 443 (HTTPS)
Step 3: TLS Handshake
Server presents its certificate.
Your app verifies: "Is this certificate valid? Is it signed by a trusted authority?"
A shared encryption key is established.
Step 4: HTTP Request Sent (Encrypted)
GET /api/v1/account/balance
Authorization: Bearer eyJhbGciOiJIUzI1NiJ9...
Step 5: Server Processes Request
Authentication check: Is the token valid?
Authorization check: Is this user allowed to see this account?
Business logic: Look up balance in database.
Step 6: HTTP Response Sent (Encrypted)
200 OK
{ "account": "XXXX1234", "balance": 25000, "currency": "INR" }
Step 7: Client Processes Response
App displays balance on screen.
Security controls exist at steps 3 (TLS), 5 (auth checks), and in how step 6 filters what data to include. A failure at any step compromises the entire transaction.
Tools That Expose API Traffic
Security professionals use specific tools to inspect API traffic. Understanding these tools helps both defenders and testers.
Browser Developer Tools
The Network tab in Chrome, Firefox, or Edge shows every HTTP request a web application makes. You can see the method, URL, headers, request body, response status, and response body. This is how security researchers often discover API endpoints that the developer did not intend to be visible.
Burp Suite
A professional security tool that sits between the client and server as a proxy. It captures and allows modification of every request and response. Security testers use Burp Suite to manipulate API requests — changing parameter values, adding extra fields, or replaying requests with different tokens — to test for vulnerabilities.
Postman
Primarily a developer tool for building and testing APIs, Postman also helps security testers manually construct and send custom API requests without needing to write code.
Wireshark
A network packet analyzer. On unencrypted HTTP connections, Wireshark shows the raw content of every request and response. This is exactly the same capability that an attacker on a shared network has. Using Wireshark on your own API is a simple way to verify that TLS is working correctly — if you can see readable content in Wireshark, the connection is not encrypted.
Key Points
- Every API call follows a request-response cycle. The client asks, the server answers.
- HTTP requests have four parts: method, URL, headers, and body. Each one is a potential attack surface.
- HTTP responses include status codes, headers, and body. Correct status codes and security headers are not optional extras.
- The 401 (not authenticated) vs 403 (not authorized) distinction matters for correct security logic.
- URL parameters like
user_id=101can be changed by attackers — servers must always validate ownership, not just existence. - Response bodies should never dump full database rows — only send what the client actually needs.
- All API traffic must travel over HTTPS to protect credentials and data from interception.
