Getting Started with requests: A Beginner-Friendly Python Tutorial

If you’re working with Python and want an easy way to interact with web APIs, download content, or automate online tasks, you’ll likely run into the requests library. Known for its simplicity and readability, requests makes sending HTTP requests in Python both intuitive and powerful.

In this tutorial, we’ll walk through the basics of using requests, including installation, making your first request, working with JSON data, handling errors, and sending data with POST requests. By the end, you’ll be able to build simple API-powered scripts of your own.


What Is the requests Library?

requests is a popular Python library used for sending HTTP requests such as GET, POST, PUT, DELETE, and more. It abstracts away the complexity of working with urllib and provides a human-friendly API that developers love.


Installing the Library

Install requests using pip:

pip install requests

To verify:

import requests
print(requests.__version__)

Making Your First GET Request

Let’s start by fetching data from a public API. We’ll use the JSONPlaceholder API, which is perfect for testing.

import requests

url = "https://jsonplaceholder.typicode.com/posts/1"
response = requests.get(url)

print(response.status_code)   # Should print 200
print(response.text)          # Raw response text

If you know the server will return JSON, requests gives you a convenient method:

data = response.json()
print(data)

Handling Query Parameters

Sometimes APIs require URL parameters. requests lets you pass them cleanly using a dictionary.

params = {"userId": 1}
response = requests.get("https://jsonplaceholder.typicode.com/posts", params=params)

print(response.url)  # Shows the full URL with parameters
print(response.json())

Sending Data with a POST Request

To create data on a server, you typically send a POST request. Again, requests makes this straightforward:

import requests

payload = {
    "title": "My New Post",
    "body": "This is a tutorial on the Python requests library.",
    "userId": 1
}

response = requests.post("https://jsonplaceholder.typicode.com/posts", json=payload)

print(response.status_code)   # Should be 201
print(response.json())

Passing the data using the json= parameter automatically converts your dictionary to JSON and sets the correct headers.


Working with Headers

Some APIs require special headers such as API keys or content types.

headers = {
    "Authorization": "Bearer YOUR_TOKEN_HERE",
    "Accept": "application/json"
}

response = requests.get("https://api.example.com/data", headers=headers)

Handling Errors Gracefully

Network issues, invalid responses, and API limits can result in errors. Here’s how you handle them:

import requests

try:
    response = requests.get("https://jsonplaceholder.typicode.com/posts/1", timeout=5)
    response.raise_for_status()  # Raises an HTTPError for bad responses
    data = response.json()
    print(data)

except requests.exceptions.Timeout:
    print("The request timed out.")
except requests.exceptions.HTTPError as err:
    print(f"HTTP error: {err}")
except requests.exceptions.RequestException as err:
    print(f"Error: {err}")

Downloading Files (Images, PDFs, etc.)

You can also download files easily:

import requests

url = "https://via.placeholder.com/300"
response = requests.get(url)

with open("image.png", "wb") as file:
    file.write(response.content)

print("Image downloaded!")

Conclusion

The requests library is one of the most powerful yet beginner-friendly tools in the Python ecosystem. Whether you’re building a simple automation script or integrating with a full-scale web service, requests gives you clean, readable, and reliable tools to work with APIs.

If you want a follow-up tutorial—such as working with authentication, file uploads, or integrating requests into larger applications—just let me know!

References

fathibensari
fathibensari
Articles: 3

Leave a Reply

Your email address will not be published. Required fields are marked *