No history yet

Requests Module Basics

Talking to the Web with Python

Whenever you visit a website, your browser sends a request to a server, and the server sends back a response. This conversation happens using a set of rules called HTTP, the fundamental protocol of the web. It's like ordering from a restaurant: you (the client) make a request for a specific dish (a webpage), and the kitchen (the server) sends it out to you.

As a programmer, you often need your scripts to have these same conversations. You might want to pull data from a public service, test a web application, or automate interactions with online tools. This is where Python's requests library comes in. It's a simple, elegant tool that makes sending HTTP requests incredibly straightforward.

While Python has built-in ways to handle web requests, the requests library is the overwhelming favorite because it was designed for humans. Its syntax is clean and intuitive.

Getting Set Up

The requests library doesn't come standard with Python, so you need to install it. You can do this using pip, Python's package manager. Open your terminal or command prompt and run the following command.

pip install requests

Once the installation is complete, you're ready to start making requests from any Python script.

Your First Request

The most common type of HTTP request is a GET request, which is used to retrieve data from a specified resource. With the requests library, this is as simple as calling the get() function and passing in the URL you want to access.

Let's try fetching some sample data from JSONPlaceholder, a free public API for testing and prototyping.

import requests

# The URL of the API endpoint we want to get data from
url = 'https://jsonplaceholder.typicode.com/todos/1'

# Make the GET request
response = requests.get(url)

# Print the status code and the data
print(f"Status Code: {response.status_code}")
print(f"Data: {response.json()}")

When you run this code, you'll see two things. First, a status code. A status of 200 means everything went well and the request was successful. Second, you'll see the data returned from the server, which requests can conveniently decode into a Python dictionary for you using the .json() method.

That's it. You've successfully used Python to fetch data from a web server. This simple get() call is the foundation for interacting with countless web services and APIs.

Quiz Questions 1/5

What is the primary protocol used for communication between web browsers and servers, as described in the text?

Quiz Questions 2/5

Which command is used to install the requests library in a Python environment?