Working with APIs in Python – A Complete Guide
1. Introduction to APIs
What is an API?
An API (Application Programming Interface) allows applications to communicate with each other. It enables developers to access web services, databases, and third-party applications programmatically.
Types of APIs
- Web APIs – Communicate over the internet (e.g., REST, SOAP).
- Library APIs – Provided by programming languages (e.g., NumPy, Pandas).
- Operating System APIs – Interact with system resources (e.g., Windows API).
- Hardware APIs – Control devices like printers or cameras.
Common Web API Formats
- REST (Representational State Transfer) – Uses HTTP methods (GET, POST, PUT, DELETE).
- SOAP (Simple Object Access Protocol) – Uses XML-based messaging.
- GraphQL – Fetches specific data using queries.
2. Setting Up Python for API Requests
Python provides built-in and third-party libraries to interact with APIs.
Install requests
Library
The requests
library is the most commonly used package for making HTTP requests.
pip install requests
Importing Required Modules
import requests
import json
3. Making HTTP Requests with Python
APIs communicate over HTTP using request methods:
HTTP Method | Description |
---|---|
GET | Fetches data from a server |
POST | Sends data to a server |
PUT | Updates existing data |
DELETE | Removes data |
3.1 Making a GET
Request
The GET
request is used to fetch data from an API.
import requests
url = "https://jsonplaceholder.typicode.com/posts/1" # Example API
response = requests.get(url)
print(response.status_code) # 200 means success
print(response.json()) # Convert response to JSON
Output:
{
"userId": 1,
"id": 1,
"title": "API Example",
"body": "This is an example response."
}
3.2 Making a POST
Request
The POST
request is used to send new data to an API.
url = "https://jsonplaceholder.typicode.com/posts"
data = {
"title": "New Post",
"body": "This is a sample post.",
"userId": 1
}
response = requests.post(url, json=data)
print(response.status_code)
print(response.json())
Output:
{
"title": "New Post",
"body": "This is a sample post.",
"userId": 1,
"id": 101
}
3.3 Making a PUT
Request
The PUT
request is used to update an existing record.
url = "https://jsonplaceholder.typicode.com/posts/1"
data = {
"title": "Updated Post",
"body": "This post has been updated.",
"userId": 1
}
response = requests.put(url, json=data)
print(response.status_code)
print(response.json())
3.4 Making a DELETE
Request
The DELETE
request removes a resource.
url = "https://jsonplaceholder.typicode.com/posts/1"
response = requests.delete(url)
print(response.status_code) # 200 means success
4. Handling API Responses
API responses usually return data in JSON format.
Parsing JSON Data
response = requests.get("https://jsonplaceholder.typicode.com/posts/1")
data = response.json() # Convert response to dictionary
print(data["title"]) # Access specific fields
5. Handling API Errors and Exceptions
APIs may return errors due to invalid requests, missing parameters, or server issues.
Common HTTP Status Codes
Status Code | Meaning |
---|---|
200 OK | Request successful |
201 Created | Resource successfully created |
400 Bad Request | Invalid request |
401 Unauthorized | Authentication required |
403 Forbidden | Permission denied |
404 Not Found | Resource not found |
500 Internal Server Error | Server error |
Handling API Errors in Python
url = "https://jsonplaceholder.typicode.com/posts/1000" # Invalid ID
response = requests.get(url)
if response.status_code == 200:
print(response.json())
else:
print(f"Error: {response.status_code}")
6. Using API Headers and Authentication
6.1 API Headers
Some APIs require custom headers (e.g., authentication, content type).
headers = {"User-Agent": "MyApp"}
response = requests.get(url, headers=headers)
6.2 API Authentication Methods
Authentication Type | Description |
---|---|
API Key | A unique key to access the API |
OAuth | Token-based authentication |
Basic Authentication | Username and password-based |
Example: API Key Authentication
api_key = "your_api_key_here"
url = "https://api.example.com/data"
headers = {"Authorization": f"Bearer {api_key}"}
response = requests.get(url, headers=headers)
7. Working with Pagination in APIs
Some APIs return data in pages.
url = "https://jsonplaceholder.typicode.com/posts"
page = 1
while url:
response = requests.get(url, params={"_page": page, "_limit": 10})
data = response.json()
if not data:
break
print(f"Page {page}: {data}")
page += 1
8. Consuming a Real-World API Example
Example: Fetching Weather Data
api_key = "your_openweathermap_api_key"
city = "London"
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}"
response = requests.get(url)
data = response.json()
print(f"Weather in {city}: {data['weather'][0]['description']}")
9. Using the json
Module for Handling API Data
The json
module helps with reading and writing JSON data.
Converting JSON to a Python Dictionary
import json
json_data = '{"name": "Alice", "age": 25}'
python_dict = json.loads(json_data)
print(python_dict["name"])
Converting a Python Dictionary to JSON
python_dict = {"name": "Alice", "age": 25}
json_data = json.dumps(python_dict, indent=4)
print(json_data)
10. Best Practices for Working with APIs
✔ Use API keys securely – Store them in environment variables.
✔ Handle errors gracefully – Use try-except blocks.
✔ Respect API rate limits – Avoid making too many requests.
✔ Use pagination – Fetch large datasets efficiently.
✔ Read API documentation – Understand request parameters and responses.