Working with APIs
Pull data from web services
The web is full of interesting data, and many websites offer a way to programmatically access it using an API. Let's learn how to interact with them.
What is an API?
API stands for Application Programming Interface. Think of it like a menu at a restaurant. The menu lists everything you can order from the kitchen. You don't need to know how to cook the food yourself; you just tell the waiter what you want.
Similarly, an API lets your program ask a web service for specific information or to perform actions. The web service (the 'kitchen') handles the hard work and sends back a response (your 'food').
Your first API call
Making an API call usually involves sending a request to a special web address, called an endpoint. We'll use the requests library in Python to do this. First, make sure you have it installed:
pip install requestsNow, let's try calling a famous placeholder API that gives us fake user data. We'll use the GET method, which is like asking for information.
import requests
response = requests.get('https://jsonplaceholder.typicode.com/users/1')
print(response)Understanding the response
When you ran the code above, print(response) likely showed something like <Response [200]>. This is the HTTP status code. 200 means 'OK' or success!
200 OK: Your request worked!404 Not Found: The resource you asked for doesn't exist.401 Unauthorized: You don't have permission to access this.500 Internal Server Error: Something went wrong on the server's side.
The actual data from the API call is usually in JSON format. It's like a Python dictionary but stored as text. The requests library has a convenient way to turn this text into a Python dictionary.
import requests
response = requests.get('https://jsonplaceholder.typicode.com/users/1')
user_data = response.json()
print(user_data)Extract what you need
Now that our API response is a Python dictionary, we can access its parts just like any other dictionary. Let's get the user's name and email.
import requests
response = requests.get('https://jsonplaceholder.typicode.com/users/1')
user_data = response.json()
name = user_data['name']
email = user_data['email']
print(f"User Name: {name}")
print(f"User Email: {email}")How it works
When you make an API call, your program sends an HTTP request to a server. This request includes a method (like GET), the URL of the resource you want, and sometimes other information like headers or a body.
The server processes your request and sends back an HTTP response. This response contains a status code (like 200 for success), headers, and often a body with the data you asked for, usually in JSON format.