Skip to main content

Fetching Data with requests.get()

The standard tool for interacting with HTTP APIs in Python is the popular third-party library requests ("HTTP for Humans").


1. Installation

Install the library using pip or modern uv:

# Using standard pip
pip install requests

# Or using high-speed uv
uv add requests

2. Making Your First GET Request

Let's call the free public GitHub API to fetch details about a public repository:

import requests

# 1. Send the GET request
response = requests.get("https://api.github.com/users/octocat")

# 2. Check the Status Code
print("Status Code:", response.status_code) # Output: Status Code: 200

# 3. Parse the JSON response body directly into a Python Dictionary
if response.status_code == 200:
user_data = response.json()
print("User Name:", user_data.get("name"))
print("Public Repos:", user_data.get("public_repos"))
print("Bio:", user_data.get("bio"))

3. Passing Query Parameters (params={...})

When searching or filtering API data (e.g., https://api.site.com/search?city=Hyderabad&limit=5), never build URLs manually using string concatenation.

Always pass query parameters cleanly using a Python dictionary:

import requests

url = "https://jsonplaceholder.typicode.com/posts"

# Define filtering parameters
query_params = {
"userId": 1,
"_limit": 3
}

# requests automatically formats: .../posts?userId=1&_limit=3
response = requests.get(url, params=query_params)
posts = response.json()

for post in posts:
print(f"📌 [Post {post['id']}]: {post['title']}")

4. Inspecting Response Properties

A Response object returned by requests.get() provides several helpful properties:

PropertyTypeUsage
response.status_codeint200, 404, 500 status verification
response.json()dict / listParses JSON body into Python native types
response.textstrRaw response content as a text string
response.headersdictResponse headers (e.g. content-type, rate-limit)
response.okboolReturns True if status_code < 400

Quick Summary

  • requests.get(url, params=dict): Sends an HTTP GET request and automatically encodes query string parameters.
  • response.json(): Deserializes JSON response text directly into Python dictionaries or lists.
  • Core Response Inspection: response.status_code (HTTP code), response.ok (boolean truthiness check), and response.headers.

What's Next?

Let's explore how to create new records and submit form/JSON payloads using Sending Data with POST Requests!