API相關(guān)基礎(chǔ)

request返回列表

  • 200 一切正常,返回為一個(gè)標(biāo)準(zhǔn)結(jié)果
  • 301 重定向到一個(gè)已經(jīng)修改了的域名結(jié)果去
  • 401 服務(wù)認(rèn)為你沒(méi)有被授權(quán),沒(méi)有拿到一個(gè)正確的credentials (證書(shū))來(lái)訪(fǎng)問(wèn)這個(gè)API
  • 400 服務(wù)器認(rèn)為是一個(gè)bad request,沒(méi)有傳送接口需要的request形式
  • 403 你傳送的信息是被禁止的 ,或者你沒(méi)有權(quán)限查看
  • 404 你訪(fǎng)問(wèn)的資源服務(wù)器沒(méi)有查找到,資源被刪除

import requests
requests.get會(huì)返回request類(lèi)型的變量:
屬性status_code表示request返回標(biāo)簽值

request = requests.get("http://api.open-notify.org/iss-now.json:)
status = request.status_code
print(status)

Output
404

在請(qǐng)求中增加參數(shù),使用params 來(lái)賦值一個(gè)字典

dic = {"lat": 37.78,"lon":-122.41}
response = requests.get("http://api.open-notify.org/iss-pass.json",params = dic)
content = response.content
print(content)

import json
json庫(kù)包含兩個(gè)轉(zhuǎn)換方法

  • dumps 把python類(lèi)型數(shù)據(jù)轉(zhuǎn)換承string
  • loads 把string類(lèi)型數(shù)據(jù)轉(zhuǎn)換成python類(lèi)型
conan = ["xiaolan","huiyuan","guangyan"]
conan_string = json.dumps(conan)
print(type(conan_string))
conan_origin = json.loads(conan_string)
print(type(conan_origin))

output
<class 'str'>
<class 'list'>

.json()可以將取到的response轉(zhuǎn)化為Python object,用例將mock_requests.Response型轉(zhuǎn)化為了dict型

parameters = {"lat": 37.78, "lon": -122.41}
response = requests.get("http://api.open-notify.org/iss-pass.json", params=parameters)
json_data = response.json()
print(type(json_data))
print(json_data)
first_pass_duration = json_data["response"][0]["duration"]
print(first_pass_duration)

output
<class 'dict'>
{'message': 'success', 'response': [{'duration': 369, 'risetime': 1441456672}, {'duration': 626, 'risetime': 1441462284}, {'duration': 581, 'risetime': 1441468104}, {'duration': 482, 'risetime': 1441474000}, {'duration': 509, 'risetime': 1441479853}], 'request': {'latitude': 37.78, 'longitude': -122.41, 'datetime': 1441417753, 'altitude': 100, 'passes': 5}}
369

部分response中包含status code和data各種部分,這些信息可以通過(guò).headers提取

print(response.headers)
print(type(response.headers))
content_type = response.headers["content-type"]
print(content_type)

output
{'date': 'Sat, 05 Sep 2015 01:49:13 GMT', 'connection': 'keep-alive', 'via': '1.1 vegur', 'server': 'gunicorn/19.3.0', 'content-type': 'application/json', 'content-length': '520'}
<class 'dict'>
application/json

一個(gè)從astros.json取值的例子


image.png
response = requests.get("http://api.open-notify.org/astros.json")
res = response.json()
in_space_count = res["number"]
print(in_space_count)

output
9

大部分requests是需要Authorization的,在請(qǐng)求中通常添加headers參數(shù)來(lái)傳遞授權(quán)信息
headers的格式通常為:

{"Authorization": "token 1f36137fbbe1602f779300dad26e4c1b7fbab631"}

headers = {"Authorization": "token 1f36137fbbe1602f779300dad26e4c1b7fbab631"}
response = requests.get("https://api.github.com/users/VikParuchuri/orgs",headers = headers)
orgs = response.json()
print(orgs)

Pagination
params中需要包含兩個(gè)參數(shù),page和per_page,page標(biāo)注要顯示第幾頁(yè),per_page標(biāo)注一頁(yè)顯示多少條內(nèi)容,傳送參數(shù)無(wú)論任何內(nèi)容都需要參數(shù)params,無(wú)論是這次的pagination,或者是以后的time,具體代碼如下

params = {"per_page": 50, "page": 2}
response = requests.get("https://api.github.com/users/VikParuchuri/starred", headers=headers, params=params)
page2_repos = response.json()
print(page2_repos)

output
[{'hooks_url': 'https://api.github.com/repos/snowplow/snowplow/hooks', 'git_url': 'git://github.com/snowplow/snowplow.git', 'watchers_count': 2183, 'homepage': 
...

POST

post請(qǐng)求中攜帶json變量,創(chuàng)建一個(gè)名為test的庫(kù)在repos目錄下如下

payload = {"name": "test"}
requests.post("https://api.github.com/user/repos", json=payload)

返回的response的參數(shù)status_code可以表示返回類(lèi)型,其中header依舊是上文中的授權(quán)用戶(hù)
下面創(chuàng)建名為learning-about-apis的庫(kù)

payload = {"name":"learning-about-apis"}
response = requests.post("https://api.github.com/user/repos",json = payload,headers = headers)
status = response.status_code
print(status)

output
201

PATCH

給庫(kù)打補(bǔ)丁,使用patch命令,這里需要注意的是post的url是一個(gè)上層目錄,post之后將新建name:test即test的庫(kù)目錄,如post代碼中內(nèi)容就是新建了repos/learning-about-apis這個(gè)目錄,而patch目錄的操作url就是
https://api.github.com/repos/VikParuchuri/learning-about-apis,來(lái)修改learning-about-apis的描述,故patch的使用針對(duì)于已經(jīng)存在的目錄,目錄位置一般都是url的最后文件名(basename),代碼如下

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(status)

output
200

DELETE

刪除一個(gè)目錄不需要再帶json參數(shù)傳payload,只需直接刪除想要?jiǎng)h除的repos即可,下面代碼就是刪除learning-about-apis庫(kù),代碼如下

response = requests.delete("https://api.github.com/repos/VikParuchuri/learning-about-apis",headers = headers)
status = response.status_code
print(status)

output
204
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容