⬅ Previous Next ➡

File Formats and APIs

JSON Handling in Python (json module)
  • JSON is a common data format used in APIs.
  • Python module: json
  • json.loads() → JSON string to dict
  • json.dumps() → dict to JSON string
  • json.load() / json.dump() for files
import json

data = {"name": "Sourav", "age": 25}
js = json.dumps(data)
print(js)

obj = json.loads(js)
print(obj["name"])
Read and Write JSON File
  • Write JSON to file using json.dump()
  • Read JSON from file using json.load()
import json

data = {"course": "Python", "marks": [80, 90, 85]}

with open("data.json", "w") as f:
    json.dump(data, f, indent=4)

with open("data.json", "r") as f:
    obj = json.load(f)

print(obj)
CSV Handling (csv module)
  • CSV stores data in rows and columns.
  • Python module: csv
  • csv.reader reads rows
  • csv.writer writes rows
import csv

with open("students.csv", "r", newline="") as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)
Write CSV File (csv.writer)
  • Use newline="" to avoid extra blank lines (Windows).
import csv

rows = [
    ["Name", "Marks"],
    ["Sourav", 85],
    ["Amit", 90]
]

with open("out.csv", "w", newline="") as f:
    w = csv.writer(f)
    w.writerows(rows)
XML Handling (ElementTree)
  • XML is a markup format used in some APIs and configs.
  • Python module: xml.etree.ElementTree
  • Parse XML and read elements using tags.
import xml.etree.ElementTree as ET

xml_data = """
    Sourav
    85
"""

root = ET.fromstring(xml_data)
print(root.find("name").text)
print(root.find("marks").text)
API Basics (Concepts)
  • API = Application Programming Interface (communication between apps).
  • Common API type: REST
  • Common HTTP methods: GET, POST, PUT, DELETE
  • Status codes: 200 OK, 201 Created, 400 Bad Request, 401 Unauthorized, 404 Not Found, 500 Server Error
Fetching Data using requests (GET)
  • Install: pip install requests
  • Use requests.get() to fetch API data.
  • Check status_code before using response.
import requests

url = "https://jsonplaceholder.typicode.com/posts/1"
res = requests.get(url)

print(res.status_code)
print(res.text[:100])
Parsing API Response (JSON)
  • If API returns JSON, use res.json() to parse.
  • Result becomes Python dict/list.
import requests

url = "https://jsonplaceholder.typicode.com/posts/1"
res = requests.get(url)

if res.status_code == 200:
    data = res.json()
    print(data["title"])
else:
    print("Request failed")
Sending Data to API (POST)
  • Use requests.post() with JSON body.
  • Pass payload using json= parameter.
import requests

url = "https://jsonplaceholder.typicode.com/posts"
payload = {"title": "Test", "body": "Hello", "userId": 1}

res = requests.post(url, json=payload)
print(res.status_code)
print(res.json())
API Error Handling (Timeout + Exceptions)
  • Use timeout to avoid waiting forever.
  • Handle exceptions: ConnectionError, Timeout, etc.
import requests

try:
    res = requests.get("https://jsonplaceholder.typicode.com/posts", timeout=5)
    res.raise_for_status()
    print("Fetched:", len(res.json()))
except requests.exceptions.Timeout:
    print("Timeout error")
except requests.exceptions.RequestException as e:
    print("Request error:", e)
Mini Project: API Dashboard (Console)
  • Fetches posts from API and shows a small dashboard summary.
  • Displays total posts and first 5 titles.
import requests

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

def fetch_posts():
    res = requests.get(API_URL, timeout=10)
    res.raise_for_status()
    return res.json()

try:
    posts = fetch_posts()

    print("=== API DASHBOARD ===")
    print("Total Posts:", len(posts))
    print("\nFirst 5 Titles:")
    for p in posts[:5]:
        print("-", p["title"])

except requests.exceptions.RequestException as e:
    print("API Error:", e)
⬅ Previous Next ➡