📝 API

The requests Library: HTTP Requests from Python

0
Author
04e5cc8b-58ac-4bdc-bdee-661bbb
📅
Published
08.05.2026
⏱️
Reading time
2 min
👁️
Views
44
🌱
Level
Beginner

requests is the most downloaded Python library in the world — over 300 million downloads per month. It makes HTTP requests simple and readable.

Installation

pip install requests

On CodeHS the library is already installed.

Basic GET Request

import requests

response = requests.get("https://api.chucknorris.io/jokes/random")

print(response.status_code)  # 200
print(response.text)         # raw response text
print(response.json())       # Python dict (if the response is JSON)

Parameters and Responses

Query Parameters (params)

Pass parameters as a dictionary — requests builds the correct URL for you:

# Bad — manual URL construction:
url = f"https://api.chucknorris.io/jokes/random?category={category}"

# Good — via params=:
response = requests.get(
    "https://api.chucknorris.io/jokes/random",
    params={"category": "dev"}
)
# Resulting URL: .../jokes/random?category=dev

If a parameter value contains special characters (&, /, spaces), params= URL-encodes them automatically. Manual construction will break in those cases.

timeout — Always Set It

response = requests.get(url, timeout=10)
# If the server doesn't respond within 10 seconds — raises Timeout

Without a timeout, your program can hang forever. In production code, timeout is mandatory.

response.json() vs response.text vs response.content

response = requests.get(url)

response.status_code   # integer: 200, 404, 401...
response.text          # string — raw response text
response.json()        # Python dict/list (parses JSON)
response.content       # bytes — binary data (images, files)
response.headers       # dict of response headers

raise_for_status()

Automatically raises HTTPError if the status is >= 400:

response = requests.get(url)
response.raise_for_status()  # no-op on 200, raises on 4xx/5xx
data = response.json()

More convenient than if response.status_code != 200: raise ....

Sending Data

POST Request with a Body

response = requests.post(
    "https://api.github.com/user/repos",
    headers={"Authorization": "Bearer TOKEN"},
    json={"name": "my-repo", "private": False},  # request body
)

json= automatically:
- Serializes the dict to JSON
- Adds the Content-Type: application/json header

PATCH and Other Methods

requests.patch(url, headers=headers, json={"state": "closed"})
requests.delete(url, headers=headers)
requests.put(url, headers=headers, json={...})

# Or generically:
requests.request("PATCH", url, headers=headers, json={...})

Headers

headers = {
    "Authorization": "Bearer my_token",
    "Accept": "application/json",
}
response = requests.get(url, headers=headers)

Additional Features

Error Handling

try:
    response = requests.get(url, timeout=10)
    response.raise_for_status()
    return response.json()
except requests.exceptions.ConnectionError:
    print("No internet connection")
except requests.exceptions.Timeout:
    print("Server did not respond")
except requests.exceptions.HTTPError as e:
    print(f"HTTP error: {e.response.status_code}")

Downloading a File

response = requests.get(image_url, timeout=30)
response.raise_for_status()

with open("photo.jpg", "wb") as f:
    f.write(response.content)  # content is bytes, not text

Summary

Task How
GET request requests.get(url, params={}, timeout=10)
POST request requests.post(url, json={}, headers={})
Response status response.status_code
JSON data response.json()
Auto-check status response.raise_for_status()
Binary data response.content

Your reaction to the article

💬 Comments (0)

🔐 Sign in to leave a comment
🚪 Login
💭

No comments yet

Be the first to share your opinion about this article!

🔗 Similar

Similar articles

Continue learning with these materials

📝

Setting Up Your Environment: Python, pip, and VS …

Before writing code locally, you need to set up three tools: Python, pip, and VS...

📅 04.06.2026 👁️ 16
📝

The datetime Module: Working with Dates and Times

datetime is Python's standard module for working with dates and times. It's part of the...

📅 08.05.2026 👁️ 66
📝

.env Files and Environment Variables: Keeping Sec…

Imagine you wrote a program with an API key hardcoded in the source and pushed...

📅 08.05.2026 👁️ 75

Did you like the article?

Subscribe to our updates and receive new articles first. Grow with PyLand!