本篇来举例一个json字符串作为一个参数传入接口的例子。通过github上API文档,github上大部分接口(除了GET方法之外)都是采用json作为参数传入的。所以,这个是学习重点,实际工作中,页是前面一篇的parmas参数和json参数两种传参用得比较多。不多说,开始我们的举例。
1.之前前面获取自己用户账号信息的请求,我的账号得到信息如下
上面可以看出,我的账号下name 和email两个字段是没有值的。下面我们举例来修改这两个字段的值。
2.找到github上patch方法
我们找到patch请求方法的描述,知道patch方法是改变值,这个和PUT是替换值是有区别的。
3. patch方法举例
import json
import requests
URL = 'https://api.github.com'
def build_uri(endpoint):
return '/'.join([URL, endpoint]) # 主要作用是拼接接口请求地址
def better_output(json_str):
return json.dumps(json.loads(json_str), indent=4) # 采用json里面提供方法打印出来,格式更好看
def request_method():
response = requests.get(build_uri('users/Anthonyliu86')) # 调用get方法,注意用户名这个地方写法,没有图片中冒号
print(better_output(response.text)) # 调用json更好格式输出
def params_method():
response = requests.get(build_uri('users'), params = {'since': 11} )
print(better_output(response.text))
print(response.headers)
print(response.url)
def json_method():
response = requests.patch(build_uri('user'), auth=('your_account', 'your_password'),json ={'email':
'abc@msn.com','name':'Anthony_tester'})
print(better_output(response.text))
print(response.headers)
print(response.url)
if __name__ == '__main__':
json_method()
输出内容
{
"login": "Anthonyliu86",
"id": 24694636,
"avatar_url": "https://avatars3.githubusercontent.com/u/24694636?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/Anthonyliu86",
"html_url": "https://github.com/Anthonyliu86",
"followers_url": "https://api.github.com/users/Anthonyliu86/followers",
"following_url": "https://api.github.com/users/Anthonyliu86/following{/other_user}",
"gists_url": "https://api.github.com/users/Anthonyliu86/gists{/gist_id}",
"starred_url": "https://api.github.com/users/Anthonyliu86/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/Anthonyliu86/subscriptions",
"organizations_url": "https://api.github.com/users/Anthonyliu86/orgs",
"repos_url": "https://api.github.com/users/Anthonyliu86/repos",
"events_url": "https://api.github.com/users/Anthonyliu86/events{/privacy}",
"received_events_url": "https://api.github.com/users/Anthonyliu86/received_events",
"type": "User",
"site_admin": false,
"name": "Anthony_tester",
"company": null,
"blog": "",
"location": null,
"email": "abc@msn.com",
"hireable": null,
"bio": null,
"public_repos": 1,
"public_gists": 0,
"followers": 1,
"following": 0,
"created_at": "2016-12-21T09:20:51Z",
通过上面的输出,我们看到了name和email两个位置发生了修改。