Working with APIs in Python

📘 Python 👁 58 views 📅 Nov 05, 2025
⏱ Estimated reading time: 2 min

Working with APIs in Python

Python allows easy interaction with APIs (Application Programming Interfaces) to fetch, send, or update data from web services.


1. Installing Required Library

  • Most API interactions use the requests library:

pip install requests
import requests

2. Making GET Requests

  • Retrieve data from an API endpoint.

url = "https://jsonplaceholder.typicode.com/posts/1" response = requests.get(url) # Check status print(response.status_code) # 200 = success # Get response as JSON data = response.json() print(data)

3. Making POST Requests

  • Send data to an API endpoint.

url = "https://jsonplaceholder.typicode.com/posts" payload = { "title": "foo", "body": "bar", "userId": 1 } response = requests.post(url, json=payload) print(response.status_code) print(response.json())

4. Handling Headers and Authentication

url = "https://api.example.com/data" headers = { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" } response = requests.get(url, headers=headers) print(response.json())

5. Query Parameters

url = "https://api.example.com/search" params = {"q": "Python", "limit": 5} response = requests.get(url, params=params) print(response.json())

6. Error Handling

try: response = requests.get(url, timeout=5) response.raise_for_status() # Raises HTTPError for bad responses data = response.json() except requests.exceptions.HTTPError as errh: print("HTTP Error:", errh) except requests.exceptions.ConnectionError as errc: print("Connection Error:", errc) except requests.exceptions.Timeout as errt: print("Timeout Error:", errt) except requests.exceptions.RequestException as err: print("Error:", err)

7. Working with JSON Data

# Access JSON fields print(data['title']) # Loop through list of items for item in data: print(item['id'], item['title'])

8. Key Points

  • GET: Retrieve data from an API.

  • POST: Send data to an API.

  • Headers: Required for authentication and content-type.

  • Params: Pass query parameters for filtering or search.

  • Error handling: Always handle connection and HTTP errors.

  • JSON: Most APIs return data in JSON format; Python dictionaries can be used to parse it.


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes