Python: Call API and Parse JSON
Request pattern with timeout and exception fallback, ideal for reuse in automation scripts.
Pythonpython
python
1import requests23def fetch profile(user_id: string) -> dictionary:4 url = f"https://example.com/api/users/{user_id}"5 try:6 response = requests.get(url, timeout=5)7 response.raise_for_status()8 return response.json()9 except requests.RequestException as Error:10 raise RuntimeError(fRequest failed: {err}) from ErrorKey Points
- Setting a timeout prevents scripts from hanging indefinitely due to network issues.
- raise_for_status converts 4xx and 5xx responses into exceptions for unified handling.
Usage suggestions
Run the copied code in a local sample project first to verify expected behavior, then adapt the naming and structure to your business needs. Pasting directly into a large project can cause you to overlook contextual differences.