Exercise 2: Fetching and Manipulating Data with JSONPlaceholder API
Question:
Create a Python script that performs the following tasks using the JSONPlaceholder API:
Fetch a specific post using a GET request.
Parse the JSON response and print specific details of the post.
Modify the post data and update it using a PUT request.
Delete the modified post using a DELETE request. Include detailed comments explaining each step, including handling API responses, parsing JSON, error handling, and mentioning the API endpoints.
Sample Code:
import requests
import json
# Base URL for JSONPlaceholder API
base_url = "https://jsonplaceholder.typicode.com"
# Function to fetch a specific post using GET request
def fetch_post(post_id):
# Construct the URL for fetching the specific post
url = f"{base_url}/posts/{post_id}"
# Make a GET request to fetch the post
response = requests.get(url)
# Check if the request was successful
if response.status_code == 200:
print("Successfully fetched the post.")
# Parse and print the post data
post = response.json()
print("Post Data:", json.dumps(post, indent=4))
return post
else:
print(f"Failed to fetch post. Status code: {response.status_code}")
return None
# Function to update a post using PUT request
def update_post(post_id, updated_data):
# Construct the URL for updating the post
url = f"{base_url}/posts/{post_id}"
# Make a PUT request to update the post
response = requests.put(url, json=updated_data)
# Check if the request was successful
if response.status_code == 200:
print("Successfully updated the post.")
# Parse and print the updated post data
updated_post = response.json()
print("Updated Post Data:", json.dumps(updated_post, indent=4))
else:
print(f"Failed to update post. Status code: {response.status_code}")
# Function to delete a post using DELETE request
def delete_post(post_id):
# Construct the URL for deleting the post
url = f"{base_url}/posts/{post_id}"
# Make a DELETE request to delete the post
response = requests.delete(url)
# Check if the request was successful
if response.status_code == 200:
print("Successfully deleted the post.")
else:
print(f"Failed to delete post. Status code: {response.status_code}")
# Example usage
if __name__ == "__main__":
# Fetch a specific post
post_id = 1
post = fetch_post(post_id)
if post:
# Modify the post data
post["title"] = "Modified Post Title"
post["body"] = "This is the modified body of the post."
# Update the post
update_post(post_id, post)
# Delete the modified post
delete_post(post_id)