๐Ÿ“ API

The requests Library: HTTP Requests from Python

P
Author
PyLand Team
๐Ÿ“…
Published
08.05.2026
โฑ๏ธ
Reading time
2 min
๐Ÿ‘๏ธ
Views
342
๐ŸŒฟ
Level
Medium

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", timeout=10)
response.raise_for_status()

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"},
    timeout=10,
)
# 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, timeout=10)

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, timeout=10)
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

import os

headers = {"Authorization": f"Bearer {os.environ['GITHUB_TOKEN']}"}
response = requests.post(
    "https://api.github.com/user/repos",
    headers=headers,
    json={"name": "my-repo", "private": False},  # request body
    timeout=10,
)
response.raise_for_status()

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"}, timeout=10)
requests.delete(url, headers=headers, timeout=10)
requests.put(url, headers=headers, json={...}, timeout=10)

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

Headers

import os

headers = {
    "Authorization": f"Bearer {os.environ['API_TOKEN']}",
    "Accept": "application/json",
}
response = requests.get(url, headers=headers, timeout=10)

Additional Features

Error Handling

def fetch_json(url):
    try:
        response = requests.get(url, timeout=10)
        response.raise_for_status()
        return response.json()
    except requests.exceptions.ConnectionError:
        print("Could not connect to the server")
    except requests.exceptions.Timeout:
        print("Server did not respond in time")
    except requests.exceptions.HTTPError as exc:
        print(f"HTTP error: {exc.response.status_code}")
    return None

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

๐Ÿ“

REST API Design Principles

Covered topics: Resources and URLs, HTTP methods, Nested resources, Response codes.

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 273
๐Ÿ“

API Keys: What They Are and How to Use Them

Most public APIs require an API key โ€” a unique string that identifies you as...

๐Ÿ“… 08.05.2026 ๐Ÿ‘๏ธ 374
๐Ÿ“

How to Read API Documentation

API documentation is a developer's primary tool. Knowing how to read it matters more than...

๐Ÿ“… 08.05.2026 ๐Ÿ‘๏ธ 357
๐ŸŽ“ Continue learning

Courses that cover this material

Visit the course to apply this material in practice.

API in Practice: Interact with Any Service Open course curriculum