APIs and Data Retrieval
Overview
APIs (Application Programming Interfaces) allow your Python programs to communicate with online services and databases. You'll practice using APIs to send requests, read JSON responses, and process external data for your own applications, connecting your code to the web.
What You Will Learn in This Lesson
By the end of this lesson, you will know:
- What an API is: Application Programming Interfaces and how they work.
- HTTP requests: How to send requests to APIs.
- JSON responses: How to parse data returned from APIs.
- Using requests library: Making API calls in Python.
- Error handling: Handling API errors and status codes.
What Is an API?
An API (Application Programming Interface) is a way for programs to communicate with each other. APIs allow your Python program to request data from online services.
Real-World Analogy
Think of an API like a restaurant menu. You (your program) look at the menu (API documentation), order what you want (send a request), and the kitchen (API server) prepares and serves your food (returns data).
import requests
# Send a GET request to an API
response = requests.get('https://api.example.com/data')
# Check if request was successful
if response.status_code == 200:
data = response.json()
print(data)
else:
print(f"Error: {response.status_code}")
How APIs Work
The process of using an API:
Send Request
Your program sends an HTTP request to the API endpoint (URL).
API Processes
The API server processes your request and gathers the data.
Receive Response
The API sends back data (usually in JSON format) with a status code.
Use Data
Your program parses the JSON response and uses the data.
Using the requests Library
The requests library is the most popular way to make HTTP requests in Python. First, you need to install it:
# In your terminal:
pip install requests
# Or for Python 3:
pip3 install requests
import requests
# Make a GET request to an API
response = requests.get('https://api.github.com/users/octocat')
# Check if request was successful
if response.status_code == 200:
# Parse JSON response
data = response.json()
print(f"Username: {data['login']}")
print(f"Name: {data['name']}")
else:
print(f"Error: {response.status_code}")
Response Object
The requests.get() function returns a Response object with:
status_code: HTTP status code (200, 404, etc.)json(): Method to parse JSON responsetext: Raw response as textheaders: Response headers
HTTP Status Codes
APIs return status codes to indicate success or failure. Understanding these codes helps you handle errors properly:
| Status Code | Meaning | When It Occurs |
|---|---|---|
200 |
OK - Success | Request completed successfully |
201 |
Created | Resource was successfully created |
400 |
Bad Request | Your request was invalid or malformed |
401 |
Unauthorized | Authentication required or failed |
404 |
Not Found | The requested resource doesn't exist |
500 |
Server Error | Something went wrong on the server |
import requests
response = requests.get('https://api.example.com/data')
if response.status_code == 200:
data = response.json()
print("Success:", data)
elif response.status_code == 404:
print("Resource not found!")
elif response.status_code == 500:
print("Server error occurred!")
else:
print(f"Unexpected status code: {response.status_code}")
Error Handling with APIs
APIs can fail for many reasons. Always handle errors gracefully:
import requests
try:
response = requests.get('https://api.example.com/data', timeout=5)
response.raise_for_status() # Raises exception for bad status codes
data = response.json()
print("Data retrieved:", data)
except requests.exceptions.Timeout:
print("Request timed out!")
except requests.exceptions.ConnectionError:
print("Could not connect to the API!")
except requests.exceptions.HTTPError:
print(f"HTTP error occurred: {response.status_code}")
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
Best Practices
- Always check
status_codeor useraise_for_status() - Use
try/exceptblocks to handle errors - Set a
timeoutto avoid hanging requests - Handle network errors separately from API errors
Practice: API Requests
Try It YourselfTry making a simple API request (simulated):
Note: This is a simulation. In a real program, you would use requests.get() to fetch data from an actual API endpoint.
Summary
In this lesson, you learned:
- APIs: Allow programs to communicate and exchange data
- HTTP requests: Send requests using the requests library
- JSON responses: Parse JSON data returned from APIs
- Status codes: Check if requests succeeded or failed
- Error handling: Handle API errors gracefully
Remember
APIs open up a world of data! You can access weather data, news, social media, and much more. Always check API documentation to understand how to use each API properly.
End-of-Lesson Exercises
Think about these questions to reinforce what you've learned:
Exercise 1: APIs
What is an API and how does it work? What are the basic steps to retrieve data from an API?
Exercise 2: HTTP Requests
What does a GET request do? What status code indicates success?