An API is a collection of tools that allows different applications to interact.
与我们获取网页相似,我们对API发出请求数据的请求,然后服务器作出相应,返回我们请求的数据。这一过程在python中主要通过requests库实现 发起请求:
For example, we use POST requests to send information (instead of retrieve it), and to create objects on the API’s server. With the GitHub API, we can use POST requests to create new repositories. Different API endpoints choose what types of requests they will accept. Not all endpoints will accept a POST request, and not all will accept a GET request. You’ll have to consult the API’s documentation to figure out which endpoints accept which types of requests.
# Make a get request to get the latest position of the ISS from the OpenNotify API.
response = requests.get("http://api.open-notify.org/iss-now.json")
#如果API还要求其它的参数可以通过字典传入
#parameters = {"lat": 37.78, "lon":-122.41}
# Make a get request with the parameters.
#response = requests.get("http://api.open-notify.org/iss-pass.json", params=parameters)
status_code=response.status_code
# Create the data we'll pass into the API endpoint. While this endpoint only requires the "name" key, there are other optional keys.
payload = {"name": "learning-about-apis"}
response = requests.post("https://api.github.com/user/repos", json=payload, headers=headers)
status = response.status_code
payload = {"description": "Learning about requests!", "name": "learning-about-apis"}
response = requests.patch("https://api.github.com/repos/VikParuchuri/learning-about-apis", json=payload, headers=headers)
status=response.status_code
print(response.status_code)
请求返回值的几个重要属性:
方法:
返回的response是一个字符串,可以利用json库里的方法将其转化为python的对象:
请求头设置: 大多数api为了防止被多次请求都会设计一个身份验证(Authorization),这个时候需要我们在发起请求时设置一个请求头(token). 使用token的好处:
# Create a dictionary of headers containing our Authorization header.
#token不可以省略
headers = {"Authorization": "token 1f36137fbbe1602f779300dad26e4c1b7fbab631"}
# Make a GET request to the GitHub API with our headers.
# This API endpoint will give us details about Vik Paruchuri.
response = requests.get("https://api.github.com/users/VikParuchuri/orgs", headers=headers)
orgs=response.json()
# Print the content of the response. As you can see, this token corresponds to the account of Vik Paruchuri.
print(response.json())