Skip to main content
REST API Design Tutorial
CHAPTER 07 Beginner

Request and Response Handling

Updated: May 14, 2026
30 min read

# CHAPTER 7

Request and Response Handling

1. Introduction

When a Client and a Server communicate via a REST API, they exchange a highly structured package of text called an HTTP Message. To be an effective API architect, you must understand the anatomical components of this package. If a Client sends an image file instead of JSON, how does the Server know? If the Server wants to tell the Client to cache the response, where does it put that instruction? In this chapter, we will dissect HTTP Requests and Responses, focusing heavily on the critical role of Headers and the concept of Content Negotiation.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Identify the four structural components of an HTTP Request.
  • Identify the structural components of an HTTP Response.
  • Understand the purpose of HTTP Headers (Metadata).
  • Explain the function of the Content-Type and Accept headers.
  • Standardize your API's JSON response wrapper.

3. Beginner-Friendly Explanation

Imagine an HTTP Message as an Amazon shipping box.
  • The Body: The actual item inside the box (e.g., A toaster). This is the JSON data.
  • The URL/Method: The shipping address written on the box.
  • The Headers: The various stickers slapped on the outside of the box: "Fragile", "Weight: 5lbs", "Contains Batteries", "Return to Sender".

Headers provide crucial *metadata* (data about the data). They tell the recipient how to safely open and process the box before they actually look inside it.

4. The Anatomy of an HTTP Request

When your browser or mobile app hits an API, it sends raw text that looks exactly like this:
http
12345678910
POST /api/users HTTP/1.1
Host: api.mywebsite.com
Authorization: Bearer xyz123
Content-Type: application/json
Accept: application/json

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

The 4 Components:

  1. 1. The Request Line: Defines the Verb (POST), the Path (/api/users), and the Protocol.
  1. 2. The Headers: Key-value pairs providing instructions.
  1. 3. The Blank Line: A strict requirement indicating headers are finished.
  1. 4. The Body: The actual data payload (Only present in POST, PUT, PATCH).

5. Critical Headers: Content Negotiation

Because a REST API can theoretically send data as JSON, XML, or plain text, the Client and Server must negotiate the language.
  • Content-Type: application/json
  • Used by the sender. It tells the receiver: "The Body I am sending you right now is formatted as JSON. Parse it accordingly."
  • If a Client uploads a profile picture, the header changes to Content-Type: image/jpeg.
  • Accept: application/json
  • Used by the Client. It tells the Server: "I am expecting your response to be formatted as JSON. Please do not send me XML or HTML."

*If you do not include Content-Type: application/json when making a POST request from a React app, your Express API will not parse the body, and req.body will be completely empty!*

6. The Anatomy of an HTTP Response

When the server finishes processing, it replies with a similar text package:
http
12345678910111213
HTTP/1.1 201 Created
Date: Mon, 12 Aug 2024 10:00:00 GMT
Content-Type: application/json
Cache-Control: no-cache
X-RateLimit-Remaining: 99

{
  "status": "success",
  "data": {
    "id": 1,
    "name": "John Doe"
  }
}

The 3 Components:

  1. 1. The Status Line: Protocol and the critical 3-digit Status Code (201 Created).
  1. 2. The Headers: Instructions back to the client (e.g., Cache-Control tells the browser not to save this response). Note the custom X-RateLimit header, a common REST pattern to tell the client how many API calls they have left.
  1. 3. The Body: The JSON payload.

7. Enforcing a Standard Response Wrapper (JSend)

If /api/users returns an Array [{}, {}], but /api/users/1 returns an Object {}, and errors return a string "Failed", the frontend developers will hate you. You must standardize the structural "wrapper" of your Response Body. A popular industry standard is JSend.

Standard Success Wrapper:

json
123456
{
  "status": "success",
  "data": {
    "user": { "id": 1, "name": "John" }
  }
}

Standard Fail Wrapper (Client Error - 400s):

json
123456
{
  "status": "fail",
  "data": {
    "email": "A valid email address is required"
  }
}

Standard Error Wrapper (Server Crash - 500s):

json
1234
{
  "status": "error",
  "message": "Unable to connect to the database."
}

*By utilizing this standard, frontend developers can always confidently check if (response.data.status === 'success').*

8. Backend Workflow: Reading Headers in Code

How do you access these headers in your backend logic?
Express.js
123456789
app.get('/api/protected-data', (req, res) => {
    // Reading an incoming header
    const authHeader = req.headers['authorization'];
    
    // Setting an outgoing header
    res.setHeader('X-Custom-Message', 'Hello from the API!');
    
    res.json({ data: "Secret Info" });
});

9. Best Practices

  • Custom Headers (X- Prefix): If your API needs to return metadata that doesn't belong in the JSON body (like Rate Limits, or custom trace IDs for debugging), use custom HTTP headers. By convention, custom headers should be prefixed with X- (e.g., X-API-Version: 2.0).

10. Common Mistakes

  • Ignoring CORS Headers: When a React app on localhost:3000 attempts to call an API on localhost:4000, the browser will violently block the request with a "CORS Error." To fix this, your API Server must attach specific headers to its response (Access-Control-Allow-Origin: *) explicitly telling the browser, "I permit other domains to read my data."

11. Exercises

  1. 1. What is the fundamental difference between the Content-Type header and the Accept header in an HTTP Request?
  1. 2. Why is standardizing the JSON response structure (like JSend) critical for frontend development teams?

12. Coding Challenges

  • Challenge: You are building a frontend Fetch request to send login credentials to your API. Write the conceptual Javascript fetch() call. Ensure you include the correct HTTP Method, the JSON body, and crucially, the two HTTP Headers required to ensure the server parses the JSON correctly.

13. MCQs with Answers

Question 1

When an API client submits a POST request containing a JSON payload, which HTTP Header MUST be included to instruct the backend server to parse the body as JSON rather than plain text or form data?

Question 2

What is the primary architectural purpose of wrapping all API JSON responses in a standardized structural envelope (e.g., always returning { "status": "success", "data": ... })?

14. Interview Questions

  • Q: Break down the structural anatomy of an HTTP Request. Explain the specific roles of the Request Line, the Headers, and the Body.
  • Q: Explain the concept of Content Negotiation in REST APIs. Which specific headers are involved, and how do they allow a single API endpoint to serve both JSON and XML depending on the client's needs?

15. FAQs

Q: Should I put error messages in the HTTP Header or the JSON Body? A: Error messages intended for the user (e.g., "Password too short") belong in the JSON Body so the frontend application can easily extract them and display them on the screen. Headers are for machine-to-machine metadata.

16. Summary

In Chapter 7, we looked under the hood of network communication. We dissected the HTTP message into its core components: The Action Line, the Metadata Headers, and the Data Body. We emphasized the absolute necessity of the Content-Type header for ensuring the Server parses JSON correctly. Finally, we explored the concept of standardizing the API's JSON output wrapper (JSend), ensuring our API behaves predictably for the frontend engineering teams consuming our data.

17. Next Chapter Recommendation

We have repeatedly mentioned JSON, but what exactly is it, and how does the server convert database objects into it? Proceed to Chapter 8: JSON and Data Serialization.

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