Skip to main content
Python for Beginners
CHAPTER 24 Beginner

Working with JSON and APIs

Updated: May 17, 2026
25 min read

# Working with JSON and APIs

Welcome to Chapter 24! JSON and APIs are the backbone of modern web communication. Every app you use — from weather apps to social media — communicates via APIs using JSON.

---

1. Learning Objectives

  • Parse and create JSON data.
  • Make HTTP requests with the requests library.
  • Work with REST APIs.
  • Handle API responses and errors.
  • Build a weather app using a public API.

---

2. JSON Basics

```python id="py24ex1" import json

# Python dict to JSON string data = {"name": "Alice", "age": 25, "skills": ["Python", "SQL"]} jsonstr = json.dumps(data, indent=2) print(jsonstr)

# JSON string to Python dict jsonstring = '{"name": "Bob", "age": 30}' parsed = json.loads(json_string) print(parsed["name"]) # Bob print(type(parsed)) # <class 'dict'>

# Read/Write JSON files with open("data.json", "w") as f: json.dump(data, f, indent=2)

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

12345678910111213141516
### JSON ↔ Python Type Mapping

| JSON | Python |
|------|--------|
| object | dict |
| array | list |
| string | str |
| number (int) | int |
| number (real) | float |
| true/false | True/False |
| null | None |

---

## 3. HTTP Requests with requests

bash pip install requests

1

python id="py24ex2" import requests

# GET request response = requests.get("https://jsonplaceholder.typicode.com/posts/1") print(f"Status: {response.statuscode}") print(f"Content Type: {response.headers['content-type']}")

data = response.json() # Parse JSON response print(f"Title: {data['title']}")

# GET with parameters params = {"userId": 1} response = requests.get( "https://jsonplaceholder.typicode.com/posts", params=params ) posts = response.json() print(f"Found {len(posts)} posts")

1234
---

## 4. HTTP Methods

python id="py24ex3" import requests

BASE = "https://jsonplaceholder.typicode.com"

# POST — Create newpost = {"title": "My Post", "body": "Content", "userId": 1} response = requests.post(f"{BASE}/posts", json=newpost) print(f"Created: {response.statuscode}") # 201

# PUT — Update (full replacement) updated = {"title": "Updated", "body": "New content", "userId": 1} response = requests.put(f"{BASE}/posts/1", json=updated) print(f"Updated: {response.statuscode}") # 200

# PATCH — Partial update response = requests.patch(f"{BASE}/posts/1", json={"title": "Patched"}) print(f"Patched: {response.statuscode}")

# DELETE response = requests.delete(f"{BASE}/posts/1") print(f"Deleted: {response.status_code}") # 200

1234
---

## 5. Headers and Authentication

python id="py24ex4" import requests

# Custom headers headers = { "Authorization": "Bearer YOURAPIKEY", "Content-Type": "application/json", "Accept": "application/json" }

response = requests.get( "https://api.example.com/data", headers=headers, timeout=10 # Timeout in seconds )

# Error handling try: response = requests.get("https://api.example.com/data", timeout=5) response.raisefor_status() # Raises exception for 4xx/5xx data = response.json() except requests.exceptions.HTTPError as e: print(f"HTTP Error: {e}") except requests.exceptions.ConnectionError: print("Connection failed!") except requests.exceptions.Timeout: print("Request timed out!") except requests.exceptions.RequestException as e: print(f"Error: {e}")

1234
---

## 6. Mini Project: Weather App

python id="py24project" import requests import json

def getweather(city): """Get weather using wttr.in API (no API key needed)""" try: url = f"https://wttr.in/{city}?format=j1" response = requests.get(url, timeout=10) response.raiseforstatus() data = response.json() current = data["currentcondition"][0] print(f"\n {'='*40}") print(f" 🌤️ Weather in {city.title()}") print(f" {'='*40}") print(f" 🌡️ Temperature : {current['tempC']}°C / {current['tempF']}°F") print(f" 💧 Humidity : {current['humidity']}%") print(f" 💨 Wind : {current['windspeedKmph']} km/h") print(f" ☁️ Description : {current['weatherDesc'][0]['value']}") print(f" 👁️ Visibility : {current['visibility']} km") print(f" {'='*40}") except requests.exceptions.RequestException as e: print(f" ❌ Error fetching weather: {e}")

print("=" * 40) print(" 🌤️ PYTHON WEATHER APP") print("=" * 40)

city = input("\n Enter city name: ") getweather(city)

1234
---

## 7. Working with Public APIs

python id="py24ex5" # Random joke response = requests.get("https://official-joke-api.appspot.com/randomjoke") joke = response.json() print(f"😄 {joke['setup']}") print(f" {joke['punchline']}")

# Random user response = requests.get("https://randomuser.me/api/") user = response.json()["results"][0] name = f"{user['name']['first']} {user['name']['last']}" email = user["email"] print(f"👤 {name} | 📧 {email}") ``

---

8. MCQs with Answers

Q1: json.dumps() converts: A) JSON→dict B) dict→JSON string C) File→dict D) String→file Answer: B

Q2: json.loads() converts: A) dict→JSON B) JSON string→dict C) File→JSON D) Dict→file Answer: B

Q3: HTTP 200 means: A) Error B) Not found C) Success D) Redirect Answer: C

Q4: HTTP 404 means: A) Success B) Not found C) Server error D) Unauthorized Answer: B

Q5: response.json() does: A) Creates JSON B) Parses response body as JSON C) Sends JSON D) Validates JSON Answer: B

Q6: requests.post() sends: A) GET request B) POST request C) PUT request D) DELETE request Answer: B

Q7: JSON null maps to Python: A) 0 B) "" C) None D) False Answer: C

Q8: API stands for: A) Application Programming Interface B) Advanced Python Integration C) Automated Protocol Interface D) Application Protocol Interpreter Answer: A

Q9: REST stands for: A) Representational State Transfer B) Remote Execution Standard Technology C) Request-Execute-Send-Transfer D) Runtime Environment Service Tool Answer: A

Q10: raiseforstatus() does: A) Nothing B) Raises exception for error status codes C) Prints status D) Returns status Answer: B

---

9. Interview Questions

  1. 1. What is JSON? JavaScript Object Notation — lightweight, text-based data interchange format.
  1. 2. json.dump() vs json.dumps()? dump() writes to file; dumps() returns string.
  1. 3. What is a REST API? An API that follows REST principles: stateless, resource-based, uses HTTP methods.
  1. 4. HTTP methods for CRUD? Create=POST, Read=GET, Update=PUT/PATCH, Delete=DELETE.
  1. 5. How to handle API rate limiting? Implement retries with exponential backoff, cache responses, use pagination.

---

10. Summary

  • json module: dumps/loads for strings, dump/load for files.
  • requests library: get(), post(), put(), delete() for HTTP.
  • Always handle errors with try-except and raiseforstatus()`.
  • Use headers for authentication and content type.
  • Set timeouts to prevent hanging requests.

---

11. Next Chapter Recommendation

In Chapter 25: Database Programming with Python, you'll learn SQL with SQLite and build a student management system! 🚀

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·