Search⌘ K
AI Features

HTTP Requests and JSON Handling

Explore how to programmatically send HTTP requests and handle JSON responses using Python. This lesson teaches you to retrieve, parse, and send structured data via web APIs using the requests library and built-in JSON tools. You will gain skills in managing request parameters, headers, and converting between JSON and Python data structures for practical API consumption and data handling.

The web operates through the exchange of text-based messages. HTTP requests and responses are transmitted as structured text messages. However, Python programs usually operate on structured objects rather than raw text. Developers typically work with dictionaries, lists, and classes.

In the previous lesson, we explored the theory of HTTP: methods, headers, and status codes. Now, we will implement that theory using Python. We will move from simply viewing the web to programmatically controlling it, enabling our applications to retrieve live data, automate interactions, and communicate with servers across the globe.

Fetching data with GET

The most common action we perform on the web is retrieving data. In Python, the third-party requests library handles the complexity of opening network connections, sending HTTP headers, and receiving responses. We use requests.get() to simulate exactly what a browser does when we visit a URL. When we make a request, the function returns a Response object. This object contains the server’s response, including the status code, headers, and body (the raw content). Before processing the data, the program should verify that the request completed successfully. This is typically done by checking the status_code attribute. A value of 200 indicates that the request succeeded.

For example, executing a GET request for a resource such as a post with ID 1 asks the server to return that specific resource. The server responds with the requested data, which the Python program can parse and process.

Look at the code below:

Python
import requests
# We define the URL for a public testing API
url = "https://jsonplaceholder.typicode.com/posts/1"
# We send a GET request to the server
response = requests.get(url)
# We check if the request was successful (Status Code 200)
if response.status_code == 200:
print(f"Success! Status Code: {response.status_code}")
# accessing .text gives us the raw string content
print("Raw Body Snippet:", response.text[:60])
else:
print(f"Failed. Status Code: {response.status_code}")
  • Line 1: We import requests to abstract away the low-level socket connections required for HTTP. This library allows us to work with high-level actions like GET or POST rather than managing raw bytes and TCP handshakes.

  • Line 7: This single function call handles the entire request lifecycle: it opens a connection, sends the ...