Evaluating Response Attributes (Status, Body, Headers)

🏷️ APIs and HTTP Requests / The Requests Library

When you send a request to an API using Python's Requests library, the server sends back a response object. This response contains everything you need to understand what happened: whether the request succeeded, what data was returned, and additional metadata about the server's reply. Learning to evaluate these three core attributesβ€”status, body, and headersβ€”is essential for building reliable integrations.


πŸ•΅οΈ Why Evaluate Response Attributes?

Every time your script talks to an external service, the response tells you the story of that interaction:

  • Status tells you if the request worked or failed (and why).
  • Body contains the actual data or error message.
  • Headers provide metadata like content type, caching rules, and server info.

Without checking these, your code is flying blindβ€”it won't know if it received valid data, hit a rate limit, or encountered an authentication error.


βš™οΈ The Response Object

When you call a method like requests.get(), the library returns a Response object. This object holds all three attributes as properties you can access directly.

Example of storing a response: - response = requests.get('https://api.example.com/users') - Now response is a Response object containing status, body, and headers.


πŸ“Š Response Status Code

The status code is a three-digit number that indicates the outcome of your request. It's the first thing you should check.

How to access it: - response.status_code returns an integer (e.g., 200, 404, 500)

Common status code categories:

Code Range Meaning Example
200–299 Success 200 OK, 201 Created
300–399 Redirection 301 Moved Permanently
400–499 Client Error 404 Not Found, 401 Unauthorized
500–599 Server Error 500 Internal Server Error

Quick check methods: - response.ok returns True if status code is less than 400, False otherwise - response.raise_for_status() raises an exception if the request failed (useful for stopping execution on errors)

Example pattern for checking status: - If response.status_code == 200: proceed to process the body - Else: log the error or handle the failure


πŸ“„ Response Body

The body contains the actual content returned by the server. This is usually where your data lives.

How to access it: - response.text returns the body as a string (raw text) - response.content returns the body as bytes (useful for binary data like images) - response.json() parses the body as JSON and returns a Python dictionary or list

Most common scenario: - You expect JSON data, so you use response.json() to get a Python dictionary - If the body isn't valid JSON, response.json() will raise an error

Example of accessing body: - data = response.json() gives you a dictionary you can work with - response.text shows you the raw string if you need to debug

Important note: - response.json() can only be called once on a response object (it reads the body stream) - Always check the status code first before trying to parse the body


🏷️ Response Headers

Headers provide metadata about the response. They are stored as a dictionary-like object.

How to access them: - response.headers returns a dictionary of all headers - response.headers['Content-Type'] gets a specific header value - response.headers.get('Content-Type') safely gets a header (returns None if missing)

Common headers you'll check: - Content-Type: tells you the format of the body (e.g., application/json, text/html) - Content-Length: size of the response body in bytes - Set-Cookie: cookies the server wants you to store - RateLimit-Remaining: how many requests you have left (common in APIs) - X-Request-Id: unique identifier for debugging

Why headers matter: - They tell you how to interpret the body (JSON vs XML vs plain text) - They reveal rate limits and authentication requirements - They help with debugging when something goes wrong


πŸ› οΈ Putting It All Together: A Typical Workflow

Here's the logical flow you should follow when evaluating a response:

  1. Send the request using requests.get() or another method
  2. Check the status code using response.status_code or response.ok
  3. If successful (200–299): parse the body with response.json() or response.text
  4. If failed (400+): read the error message from the body and check headers for details
  5. Always inspect headers for rate limits, content type, and debugging info

Example decision flow: - Store response in a variable - Check response.ok β€” if True, proceed; if False, log the status and body - Use response.headers.get('Content-Type') to confirm the format - Call response.json() to get the data


βœ… Best Practices for Engineers

  • Always check the status code first β€” never assume a request succeeded
  • Use response.raise_for_status() in scripts where failures should stop execution
  • Inspect response.text when debugging unexpected behavior (it often contains error details)
  • Check Content-Type header before calling response.json() to avoid parsing errors
  • Log response headers during development to understand API behavior and limits
  • Store response objects in variables so you can inspect all three attributes without re-requesting

πŸ“Œ Quick Reference

Attribute Access Method What It Returns
Status Code response.status_code Integer (200, 404, etc.)
Success Check response.ok Boolean (True/False)
Raw Body response.text String
JSON Body response.json() Dictionary or List
All Headers response.headers Dictionary-like object
Specific Header response.headers['Key'] String value

By mastering these three response attributes, you gain full visibility into every API interaction your code makes. This is the foundation for building robust, debuggable, and reliable integrations.


This guide shows how to inspect the three key parts of an HTTP response β€” status code, body content, and headers β€” using the Python Requests library.


βœ… Example 1: Checking the status code of a successful request

This example shows how to retrieve the HTTP status code from a response object.

import requests

response = requests.get("https://httpbin.org/status/200")
status = response.status_code
print(status)

πŸ“€ Output: 200


βœ… Example 2: Reading the response body as text

This example shows how to access the body of a response as a plain text string.

import requests

response = requests.get("https://httpbin.org/get")
body_text = response.text
print(body_text[:100])

πŸ“€ Output: { "args": {}, "headers": { "Accept": "/", "Accept-Encoding": "gzip, deflate", "Host": "httpbin.org", "User-Agent": "python-requests/2.31.0", "X-Amzn-Trace-Id": "Root=1-..." }, "origin": "...", "url": "https://httpbin.org/get" }


βœ… Example 3: Parsing the response body as JSON

This example shows how to convert a JSON response body into a Python dictionary.

import requests

response = requests.get("https://httpbin.org/get")
body_json = response.json()
print(body_json["url"])

πŸ“€ Output: https://httpbin.org/get


βœ… Example 4: Inspecting a specific response header

This example shows how to retrieve a single header value from the response headers dictionary.

import requests

response = requests.get("https://httpbin.org/response-headers?Content-Type=application/json")
content_type = response.headers["Content-Type"]
print(content_type)

πŸ“€ Output: application/json


βœ… Example 5: Checking status, body length, and server header together

This example shows a practical check: verify success, count body size, and read the server header.

import requests

response = requests.get("https://httpbin.org/get")
status_ok = response.status_code == 200
body_length = len(response.text)
server_header = response.headers.get("Server", "unknown")
print(status_ok, body_length, server_header)

πŸ“€ Output: True 408 nginx


Comparison Table

Attribute How to Access Typical Use
Status Code response.status_code Check if request succeeded (200) or failed (404)
Body (text) response.text Read raw string content
Body (JSON) response.json() Parse structured data into Python dict
Headers response.headers Inspect metadata like Content-Type, Server, Date

When you send a request to an API using Python's Requests library, the server sends back a response object. This response contains everything you need to understand what happened: whether the request succeeded, what data was returned, and additional metadata about the server's reply. Learning to evaluate these three core attributesβ€”status, body, and headersβ€”is essential for building reliable integrations.


πŸ•΅οΈ Why Evaluate Response Attributes?

Every time your script talks to an external service, the response tells you the story of that interaction:

  • Status tells you if the request worked or failed (and why).
  • Body contains the actual data or error message.
  • Headers provide metadata like content type, caching rules, and server info.

Without checking these, your code is flying blindβ€”it won't know if it received valid data, hit a rate limit, or encountered an authentication error.


βš™οΈ The Response Object

When you call a method like requests.get(), the library returns a Response object. This object holds all three attributes as properties you can access directly.

Example of storing a response: - response = requests.get('https://api.example.com/users') - Now response is a Response object containing status, body, and headers.


πŸ“Š Response Status Code

The status code is a three-digit number that indicates the outcome of your request. It's the first thing you should check.

How to access it: - response.status_code returns an integer (e.g., 200, 404, 500)

Common status code categories:

Code Range Meaning Example
200–299 Success 200 OK, 201 Created
300–399 Redirection 301 Moved Permanently
400–499 Client Error 404 Not Found, 401 Unauthorized
500–599 Server Error 500 Internal Server Error

Quick check methods: - response.ok returns True if status code is less than 400, False otherwise - response.raise_for_status() raises an exception if the request failed (useful for stopping execution on errors)

Example pattern for checking status: - If response.status_code == 200: proceed to process the body - Else: log the error or handle the failure


πŸ“„ Response Body

The body contains the actual content returned by the server. This is usually where your data lives.

How to access it: - response.text returns the body as a string (raw text) - response.content returns the body as bytes (useful for binary data like images) - response.json() parses the body as JSON and returns a Python dictionary or list

Most common scenario: - You expect JSON data, so you use response.json() to get a Python dictionary - If the body isn't valid JSON, response.json() will raise an error

Example of accessing body: - data = response.json() gives you a dictionary you can work with - response.text shows you the raw string if you need to debug

Important note: - response.json() can only be called once on a response object (it reads the body stream) - Always check the status code first before trying to parse the body


🏷️ Response Headers

Headers provide metadata about the response. They are stored as a dictionary-like object.

How to access them: - response.headers returns a dictionary of all headers - response.headers['Content-Type'] gets a specific header value - response.headers.get('Content-Type') safely gets a header (returns None if missing)

Common headers you'll check: - Content-Type: tells you the format of the body (e.g., application/json, text/html) - Content-Length: size of the response body in bytes - Set-Cookie: cookies the server wants you to store - RateLimit-Remaining: how many requests you have left (common in APIs) - X-Request-Id: unique identifier for debugging

Why headers matter: - They tell you how to interpret the body (JSON vs XML vs plain text) - They reveal rate limits and authentication requirements - They help with debugging when something goes wrong


πŸ› οΈ Putting It All Together: A Typical Workflow

Here's the logical flow you should follow when evaluating a response:

  1. Send the request using requests.get() or another method
  2. Check the status code using response.status_code or response.ok
  3. If successful (200–299): parse the body with response.json() or response.text
  4. If failed (400+): read the error message from the body and check headers for details
  5. Always inspect headers for rate limits, content type, and debugging info

Example decision flow: - Store response in a variable - Check response.ok β€” if True, proceed; if False, log the status and body - Use response.headers.get('Content-Type') to confirm the format - Call response.json() to get the data


βœ… Best Practices for Engineers

  • Always check the status code first β€” never assume a request succeeded
  • Use response.raise_for_status() in scripts where failures should stop execution
  • Inspect response.text when debugging unexpected behavior (it often contains error details)
  • Check Content-Type header before calling response.json() to avoid parsing errors
  • Log response headers during development to understand API behavior and limits
  • Store response objects in variables so you can inspect all three attributes without re-requesting

πŸ“Œ Quick Reference

Attribute Access Method What It Returns
Status Code response.status_code Integer (200, 404, etc.)
Success Check response.ok Boolean (True/False)
Raw Body response.text String
JSON Body response.json() Dictionary or List
All Headers response.headers Dictionary-like object
Specific Header response.headers['Key'] String value

By mastering these three response attributes, you gain full visibility into every API interaction your code makes. This is the foundation for building robust, debuggable, and reliable integrations.

Interactive Views

You are currently in πŸ“š All-in-One mode. Use the tabs at the top to switch to πŸ“– Theory Only or πŸ’» Code Only views.

This guide shows how to inspect the three key parts of an HTTP response β€” status code, body content, and headers β€” using the Python Requests library.


βœ… Example 1: Checking the status code of a successful request

This example shows how to retrieve the HTTP status code from a response object.

import requests

response = requests.get("https://httpbin.org/status/200")
status = response.status_code
print(status)

πŸ“€ Output: 200


βœ… Example 2: Reading the response body as text

This example shows how to access the body of a response as a plain text string.

import requests

response = requests.get("https://httpbin.org/get")
body_text = response.text
print(body_text[:100])

πŸ“€ Output: { "args": {}, "headers": { "Accept": "/", "Accept-Encoding": "gzip, deflate", "Host": "httpbin.org", "User-Agent": "python-requests/2.31.0", "X-Amzn-Trace-Id": "Root=1-..." }, "origin": "...", "url": "https://httpbin.org/get" }


βœ… Example 3: Parsing the response body as JSON

This example shows how to convert a JSON response body into a Python dictionary.

import requests

response = requests.get("https://httpbin.org/get")
body_json = response.json()
print(body_json["url"])

πŸ“€ Output: https://httpbin.org/get


βœ… Example 4: Inspecting a specific response header

This example shows how to retrieve a single header value from the response headers dictionary.

import requests

response = requests.get("https://httpbin.org/response-headers?Content-Type=application/json")
content_type = response.headers["Content-Type"]
print(content_type)

πŸ“€ Output: application/json


βœ… Example 5: Checking status, body length, and server header together

This example shows a practical check: verify success, count body size, and read the server header.

import requests

response = requests.get("https://httpbin.org/get")
status_ok = response.status_code == 200
body_length = len(response.text)
server_header = response.headers.get("Server", "unknown")
print(status_ok, body_length, server_header)

πŸ“€ Output: True 408 nginx


Comparison Table

Attribute How to Access Typical Use
Status Code response.status_code Check if request succeeded (200) or failed (404)
Body (text) response.text Read raw string content
Body (JSON) response.json() Parse structured data into Python dict
Headers response.headers Inspect metadata like Content-Type, Server, Date