-
Notifications
You must be signed in to change notification settings - Fork 96
Expand file tree
/
Copy pathpart2_status_codes.py
More file actions
91 lines (71 loc) · 2.62 KB
/
Copy pathpart2_status_codes.py
File metadata and controls
91 lines (71 loc) · 2.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
"""
Part 2: Status Codes and JSON Parsing
=====================================
Difficulty: Beginner+
Learn:
- Understanding HTTP status codes
- Parsing JSON data like a Python dictionary
- Accessing specific fields from API response
"""
import requests
print("=== Understanding Status Codes ===\n")
# Example 1: Successful request (200 OK)
print("--- Example 1: Valid Request ---")
url_valid = "https://jsonplaceholder.typicode.com/posts/1"
response = requests.get(url_valid)
print(f"URL: {url_valid}")
print(f"Status Code: {response.status_code}")
print(f"Success? {response.status_code == 200}")
# Example 2: Not Found (404)
print("\n--- Example 2: Invalid Request (404) ---")
url_invalid = "https://jsonplaceholder.typicode.com/posts/99999"
response_404 = requests.get(url_invalid)
print(f"URL: {url_invalid}")
print(f"Status Code: {response_404.status_code}")
print(f"Found? {response_404.status_code == 200}")
# Example 3: Parsing JSON Data
print("\n--- Example 3: Parsing JSON ---")
url = "https://jsonplaceholder.typicode.com/users/1"
response = requests.get(url)
# Convert response to Python dictionary
data = response.json()
# Access specific fields
print(f"Full Name: {data['name']}")
print(f"Username: {data['username']}")
print(f"Email: {data['email']}")
print(f"City: {data['address']['city']}")
print(f"Company: {data['company']['name']}")
# Example 4: Working with a list of items
print("\n--- Example 4: List of Items ---")
url_list = "https://jsonplaceholder.typicode.com/posts?userId=1"
response = requests.get(url_list)
posts = response.json()
print(f"User 1 has {len(posts)} posts:")
for i, post in enumerate(posts[:3], 1): # Show first 3
print(f" {i}. {post['title'][:40]}...")
# --- COMMON STATUS CODES ---
print("\n--- Common HTTP Status Codes ---")
status_codes = {
200: "OK - Request successful",
201: "Created - Resource created",
400: "Bad Request - Invalid syntax",
401: "Unauthorized - Authentication required",
403: "Forbidden - Access denied",
404: "Not Found - Resource doesn't exist",
500: "Internal Server Error - Server problem"
}
for code, meaning in status_codes.items():
print(f" {code}: {meaning}")
# --- EXERCISES ---
#
# Exercise 1: Fetch user with ID 5 and print their phone number
# URL: https://jsonplaceholder.typicode.com/users/5
#
# Exercise 2: Check if a resource exists before printing data
# if response.status_code == 200:
# print(data)
# else:
# print("Resource not found!")
#
# Exercise 3: Count how many comments are on post ID 1
# URL: https://jsonplaceholder.typicode.com/posts/1/comments