Python26 min read

Python Working with APIs

Learn API calls with requests: GET/POST, headers, query params, timeouts, and clean error handling with real patterns.

Michael Brown
September 12, 2025
5.0k144

APIs let your program talk to other services. Most modern applications depend on APIs.

  In Python, the most common beginner-friendly library for HTTP is `requests`.
  
  ## Install requests
  
  ```bash
  pip install requests
  ```
  
  ## GET request (fetch data)
  
  ```python
  import requests
  
  response = requests.get("https://api.github.com/users/octocat", timeout=10)
  
  print("Status:", response.status_code)
  
  if response.status_code == 200:
      data = response.json()
      print("Login:", data.get("login"))
      print("Type:", data.get("type"))
  else:
      print("Request failed")
  ```
  
  Expected output example:
  
  ```
  Status: 200
  Login: octocat
  Type: User
  ```
  
  ## Query parameters
  
  ```python
  import requests
  
  params = {"q": "python", "sort": "stars"}
  response = requests.get("https://api.github.com/search/repositories", params=params, timeout=10)
  
  data = response.json()
  print("Total:", data.get("total_count"))
  ```
  
  ## POST request (send data)
  
  ```python
  import requests
  
  payload = {"name": "Tom", "email": "tom@example.com"}
  
  response = requests.post("https://httpbin.org/post", json=payload, timeout=10)
  data = response.json()
  
  print(data["json"])
  ```
  
  Expected output:
  
  ```
  {'name': 'Tom', 'email': 'tom@example.com'}
  ```
  
  ## Headers (authentication is usually here)
  
  ```python
  import requests
  
  headers = {
      "Authorization": "Bearer YOUR_TOKEN",
      "Content-Type": "application/json"
  }
  
  response = requests.get("https://api.example.com/data", headers=headers, timeout=10)
  ```
  
  ## Error handling (professional pattern)
  
  ```python
  import requests
  
  try:
      response = requests.get("https://api.github.com/users/octocat", timeout=5)
      response.raise_for_status()
      data = response.json()
      print(data.get("login"))
  except requests.exceptions.Timeout:
      print("Request timed out.")
  except requests.exceptions.HTTPError as e:
      print("HTTP error:", e)
  except requests.exceptions.RequestException as e:
      print("Request failed:", e)
  ```
  
  ## Graph: API request flow
  
  ```mermaid
  flowchart LR
    A[Client code] --> B[HTTP request]
    B --> C[Server API]
    C --> D[JSON response]
    D --> E[Parse with .json()]
    E --> F[Use data in app]
  ```
  
  In the next lesson, you will revisit list methods in a more complete way, including what each method returns and how to avoid common list bugs.
#Python#Intermediate#APIs