Request and Response Structure
# 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-Typeheader.
-
Explain "Content Negotiation" using the
Acceptheader.
- 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: v2to 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.6. Request/Response Examples
Let's look at the full headers of a typical REST transaction.Request Structure:
Response Structure:
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.*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-Typeisapplication/json. If it's not, return a415 Unsupported Media Typestatus 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
$POSTsuperglobal *only* works automatically if the client sendsapplication/x-www-form-urlencodedormultipart/form-data. If the client sendsapplication/json,$POSTwill be completely empty! You must read JSON manually usingfilegetcontents('php://input').
11. Mini Exercises
-
1.
In Postman, make a request to an API but set the
Acceptheader totext/html. Observe if the API ignores your request, breaks, or returns HTML.
-
2.
Review the PHP
phpinfo()function in a test script and look for theHTTPACCEPTandCONTENTTYPEserver variables.
12. Coding Challenges
Challenge 1: Write a PHP script that checks if the requestContent-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
What header does the CLIENT send to tell the server what format the data in the body is in?
What header does the CLIENT send to tell the server what format it wants to RECEIVE?
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
$POSTempty 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 thatContent-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.