An API is a collection of tools that allows different applications to interact.

与我们获取网页相似,我们对API发出请求数据的请求,然后服务器作出相应,返回我们请求的数据。这一过程在python中主要通过requests库实现
发起请求:

  • get()
  • post():post请求一般会包含数据,因为这个请求本身就是用来发送给服务器请求服务器创建一个object用的
    • post请求成功会返回一个201的状态码

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.

  • patch():我们想要修改服务器上(已有的)object的部分属性时使用
    • 请求成功的状态码为200
  • put():修改全部属性时适用
  • delete():删除某个object
    • 请求成功状态码为204
# 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)

请求返回值的几个重要属性:

  • status_code
  • headers
  • content:the content of a response

方法:

  • .json():将content of a response转化为一个python对象返回

返回的response是一个字符串,可以利用json库里的方法将其转化为python的对象:

  • json.dumps — takes in a Python object and converts it to a string
  • json.loads — takes in a JSON string and converts it to a 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())