COMPLETE API CLIENT - Full-featured HTTP client
Python
#!/usr/bin/env python3
"""COMPLETE API CLIENT - Full-featured HTTP client"""
import urllib.request
import urllib.parse
import json
class APIClient:
def __init__(self, base_url):
self.base_url = base_url
def get(self, endpoint):
url = f"{self.base_url}/{endpoint}"
with urllib.request.urlopen(url) as response:
return json.loads(response.read())
def post(self, endpoint, data):
url = f"{self.base_url}/{endpoint}"
json_data = json.dumps(data).encode('utf-8')
req = urllib.request.Request(url, data=json_data)
req.add_header('Content-Type', 'application/json')
with urllib.request.urlopen(req) as response:
return json.loads(response.read())
print("API Client Demo:")
client = APIClient("http://httpbin.org")
try:
result = client.get("get")
print(f" GET successful")
result = client.post("post", {"key": "value"})
print(f" POST successful")
except Exception as e:
print(f" Error: {e}")