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. |
# Create the data we'll pass into the API endpoint. While this endpoint only requires the "name" key, there are other optional keys. |
payload = {"description": "Learning about requests!", "name": "learning-about-apis"} |
请求返回值的几个重要属性:
- 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. |