Skip to main content
RESTful Principles
CHAPTER 08 Beginner

Request and Response Structure

Updated: May 13, 2026
5 min read

# CHAPTER 8

Request and Response Structure

1. Introduction

We have talked about HTTP headers briefly, comparing them to the metadata on a postal envelope. In an API, headers are absolutely critical because they dictate *how* the data should be interpreted by both the client and the server. In Chapter 8, we will explore the anatomy of request and response structures, focusing heavily on Content-Type, Accept headers, and how clients negotiate data formats with the server.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Identify common Request headers sent by clients.
  • Identify common Response headers sent by servers.
  • Understand the critical role of the Content-Type header.
  • Explain "Content Negotiation" using the Accept header.
  • Build a PHP script that reads and sets headers programmatically.

3. Beginner-Friendly Explanation

Imagine going to a bilingual restaurant.
  • If you hand the waiter a menu order written in Spanish, you should tell them, "Hey, this is written in Spanish." (This is the Content-Type header).
  • Before you order, you might tell the waiter, "I only understand English, so please reply to me in English." (This is the Accept header).

Headers are simply invisible metadata instructions that travel along with your data, ensuring that the machine on the other end knows exactly how to read and respond to your request.

4. Real-World Examples

  • File Uploads: When you upload an image via an API, your client sets Content-Type: multipart/form-data. This tells the server, "Hey, I am not sending you a simple text string; I am sending a heavy binary file."
  • API Versioning: Some companies put their API version in a header instead of the URL, sending Accept-Version: v2 to ask the server for the newest format of the data.

5. Detailed Code Examples

Let's see how a PHP API endpoint handles content negotiation. The script will check what format the client *Accepts*, and respond accordingly.
php
1234567891011121314151617
<?php
// A simple API that can speak both JSON and XML
$headers = getallheaders();
$accept = isset($headers[&#039;Accept']) ? $headers['Accept'] : 'application/json';

$data = ["id" => 1, "name" => "John"];

if (strpos($accept, &#039;application/xml') !== false) {
    // Client requested XML
    header("Content-Type: application/xml");
    echo "<?xml version=\"1.0\"?><user><id>1</id><name>John</name></user>";
} else {
    // Default to JSON
    header("Content-Type: application/json");
    echo json_encode($data);
}
?>

6. Request/Response Examples

Let's look at the full headers of a typical REST transaction.

Request Structure:

http
12345678
POST /api/products HTTP/1.1
Host: api.store.com
Authorization: Bearer mySecretToken123
Accept: application/json
Content-Type: application/json
User-Agent: PostmanRuntime/7.28.0

{"name": "Laptop", "price": 1200}

Response Structure:

http
12345678
HTTP/1.1 201 Created
Date: Wed, 12 Oct 2026 10:00:00 GMT
Server: Nginx/1.18.0
Content-Type: application/json
X-RateLimit-Remaining: 99
Content-Length: 42

{"success": true, "product_id": 405}

7. HTTP Examples

The Content-Type header is the most important header in REST. Common values include:
  • application/json (Standard REST API data)
  • application/xml (Older APIs, SOAP)
  • application/x-www-form-urlencoded (Standard HTML forms)
  • multipart/form-data (File uploads)

8. JSON Examples

You can pass custom headers in your API response to provide metadata that doesn't belong in the JSON body itself. For example, pagination data.
http
123456789
HTTP/1.1 200 OK
Content-Type: application/json
X-Total-Count: 1500
X-Total-Pages: 15

[
  {"id": 1, "name": "Item 1"},
  {"id": 2, "name": "Item 2"}
]

*Note: We put the total count in the header (X-Total-Count) so the JSON body can just be a clean array.*

9. Best Practices

  • Always Validate Content-Type: If your API expects JSON, verify that the request's Content-Type is application/json. If it's not, return a 415 Unsupported Media Type status code.
  • Set the Response Content-Type: If you are echoing JSON in PHP, you *must* include header('Content-Type: application/json');. If you forget, the browser might assume it's just raw HTML or plain text, causing parsing errors on the client side.

10. Common Mistakes

  • Relying on $POST for JSON: In PHP, the $POST superglobal *only* works automatically if the client sends application/x-www-form-urlencoded or multipart/form-data. If the client sends application/json, $POST will be completely empty! You must read JSON manually using filegetcontents('php://input').

11. Mini Exercises

  1. 1. In Postman, make a request to an API but set the Accept header to text/html. Observe if the API ignores your request, breaks, or returns HTML.
  1. 2. Review the PHP phpinfo() function in a test script and look for the HTTPACCEPT and CONTENTTYPE server variables.

12. Coding Challenges

Challenge 1: Write a PHP script that checks if the request Content-Type is exactly application/json. If it is not, return a 415 status code and a JSON error message explaining that only JSON is accepted.

13. MCQs with Answers

Question 1

What header does the CLIENT send to tell the server what format the data in the body is in?

Question 2

What header does the CLIENT send to tell the server what format it wants to RECEIVE?

Question 3

If a PHP API receives a POST request with Content-Type: application/json, how do you read the data?

14. Interview Questions

  • Q: Explain "Content Negotiation" and the headers involved in the process.
  • Q: Why is $POST empty in PHP when a client sends a standard JSON API payload? How do you fix it?
  • Q: What is the purpose of custom headers (like X-RateLimit-Remaining), and when should you use them instead of putting the data in the JSON body?

15. FAQs

Q: Do I have to support XML if I am building a REST API? A: Not at all. Today, 99% of modern REST APIs are exclusively JSON. Supporting XML is usually only necessary for enterprise legacy systems or very specific financial integrations.

Q: What does the User-Agent header do? A: It tells the server what software the client is using (e.g., Chrome, Safari, Postman, or a custom Python script). Servers often log this for analytics or debugging.

16. Summary

In Chapter 8, we explored the hidden metadata of APIs: Headers. We learned that Content-Type describes the data currently being sent, while the Accept header negotiates what format should be returned. We also discovered a critical PHP gotcha regarding JSON payloads and the $_POST array, ensuring we handle incoming data securely and correctly.

17. Next Chapter Recommendation

We have referenced JSON constantly throughout these chapters. Now it's time to master it. Proceed to Chapter 9: Working with JSON Data to learn the syntax rules of JSON and how to encode and decode it flawlessly in PHP.

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: ·