How can one use Python to access an API and retrieve data?
To call API to fetch data, you can use Python’s requests library to send HTTP requests and parse the returned data. Here is a simple example:
import requests
# 发送 GET 请求,获取 API 数据
response = requests.get('https://api.example.com/data')
# 检查请求是否成功
if response.status_code == 200:
# 解析返回的 JSON 数据
data = response.json()
# 处理数据
for item in data['items']:
print(item['name'])
else:
print('请求失败')
In the example above, we used requests.get() to send a GET request, fetch data from an API. Then we checked the status code of the request, if it is 200, it means the request was successful, and we can parse the returned JSON data and process the data.
This is just a simple example. In real-world scenarios, you may need to pass parameters, set request headers, handle authentication, and so on. The specific operations will vary depending on the requirements of the API you are calling. You can refer to the official documentation of the requests library for more information on how to use it: https://docs.python-requests.org/en/latest/