Python VS2026
🐍 Python 2026 › Lesson 27: Working with APIs and JSON
Lesson 27 of 30

Working with APIs and JSON

HTTP requests with requests library, parsing JSON, and calling REST APIs.

Installing requests

pip install requests

Making a GET Request

import requests

response = requests.get("https://api.github.com/users/octocat")
print(response.status_code)  # 200
data = response.json()
print(data["login"])         # octocat
print(data["public_repos"]) # number of repos

Working with JSON

import json

# Python dict → JSON string
person = {"name": "Alice", "age": 30}
json_str = json.dumps(person, indent=2)
print(json_str)

# JSON string → Python dict
back = json.loads(json_str)
print(back["name"])

# Save / load JSON file
with open("data.json", "w") as f:
    json.dump(person, f, indent=2)

POST Request Example

payload = {"title": "Python 2026", "body": "Great tutorial", "userId": 1}
response = requests.post(
    "https://jsonplaceholder.typicode.com/posts",
    json=payload
)
print(response.status_code)  # 201 Created
print(response.json())
⚠️ Always Handle Errors
Wrap API calls in try/except requests.RequestException and check response.raise_for_status() to catch HTTP errors.