DEV Community

Shahrouz Nikseresht
Shahrouz Nikseresht

Posted on

Making Simple HTTP Requests in Python with requests Explained

The requests library is the easiest way to interact with web APIs and download data from the internet. It handles many details automatically.

Installing requests

First, install the library (only once):

pip install requests
Enter fullscreen mode Exit fullscreen mode

Importing the library

import requests
Enter fullscreen mode Exit fullscreen mode

Making a GET request

GET is used to retrieve data.

response = requests.get("https://api.github.com")

print(response.status_code)  # 200 means success
print(response.text)         # Raw text response
Enter fullscreen mode Exit fullscreen mode

Convert JSON responses easily:

data = response.json()
print(data["current_user_url"])
Enter fullscreen mode Exit fullscreen mode

Passing parameters

Add query parameters with params:

params = {"q": "python", "sort": "stars"}

response = requests.get("https://api.github.com/search/repositories", params=params)

repos = response.json()
print(repos["total_count"])  # Number of results
Enter fullscreen mode Exit fullscreen mode

Making a POST request

POST is used to send data (e.g., create something).

payload = {"username": "testuser", "score": 100}

response = requests.post("https://httpbin.org/post", json=payload)

print(response.json()["json"])  # Echoed back data
Enter fullscreen mode Exit fullscreen mode

Adding headers

Set custom headers (common for authentication):

headers = {"User-Agent": "my-script", "Authorization": "token abc123"}

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

Handling responses

Check status:

if response.status_code == 200:
    print("Success!")
elif response.status_code == 404:
    print("Not found.")
Enter fullscreen mode Exit fullscreen mode

Raise an exception for bad status (optional):

response.raise_for_status()  # Raises error for 4xx/5xx
Enter fullscreen mode Exit fullscreen mode

Simple examples

Fetch a random quote:

response = requests.get("https://api.quotable.io/random")
quote = response.json()

print(f'"{quote["content"]}"{quote["author"]}')
Enter fullscreen mode Exit fullscreen mode

Download an image:

img_response = requests.get("https://httpbin.org/image/png")

with open("downloaded.png", "wb") as file:
    file.write(img_response.content)
Enter fullscreen mode Exit fullscreen mode

Important notes

  • Always check response.status_code.
  • Use .json() for JSON APIs.
  • Use json= parameter to send JSON in POST.
  • Handle network errors with try/except.
  • Respect API rate limits and terms of service.

Quick summary

  • Import with import requests.
  • Use get() for retrieving data, post() for sending.
  • Pass parameters with params=, data with json= or data=.
  • Convert JSON with .json().
  • Check status_code and use raise_for_status().

Practice making requests to free APIs like quotable.io or jsonplaceholder.typicode.com. The requests library is essential for working with web services in Python programs.

Top comments (0)