JSON Placeholder API
✅ Example: Fetch Data from a Public API (JSONPlaceholder)
We'll use the free JSONPlaceholder API for demonstration.
import requests
# Define the API endpoint
url = "https://jsonplaceholder.typicode.com/posts"
# Make a GET request
response = requests.get(url)
# Check if the request was successful
if response.status_code == 200:
# Parse the JSON data
data = response.json()
# Print the first 3 posts
for post in data[:3]:
print(f"ID: {post['id']}")
print(f"Title: {post['title']}")
print(f"Body: {post['body']}\n")
else:
print(f"Failed to fetch data. Status code: {response.status_code}")
🧠 Key Points
requests.get(url)
: Sends a GET request.response.json()
: Converts JSON response to a Python dictionary/list.Always check
response.status_code
to ensure the request was successful (200 OK
).
🔁 Bonus: Fetch with Parameters (e.g., Get post with ID = 1)
response = requests.get("https://jsonplaceholder.typicode.com/posts", params={'id': 1})
print(response.json())
Last updated
Was this helpful?