GitHub API

URL: https://developer.github.com

HTTP verbs1

Where possible, API v3 strives to use appropriate HTTP verbs for each action.

Verb Description
HEAD Can be issued against any resource to get just the HTTP header info. 仅获取HTTP响应头信息。
GET Used for retrieving resources. 检索资源
POST Used for creating resources2. 创建资源
PATCH Used for updating resources with partial JSON data. For instance, an Issue resource has title and body attributes. A PATCH request may accept one or more of the attributes to update the resource. PATCH is a relatively new and uncommon HTTP verb, so resource endpoints also accept POST requests. 用于使用部分JSON数据更新资源。
PUT Used for replacing resources or collections. For PUT requests with no body attribute, be sure to set the Content-Length header to zero. 替换资源或集合。
DELETE Used for deleting resources. 删除资源

另外:

  • OPTIONS: 查看可用请求方法

使用

requests.[method](url)
request method——GET

https://developer.github.com/v3/users/ 的用法:

import json
import requestsURL = 'https://api.github.com'def build_uri(endpoint):return '/'.join([URL, endpoint])def better_print(json_str):return json.dumps(json.loads(json_str), indent=4)def request_method():response = requests.get(build_uri('users/onefine'))print(better_print(response.text))if __name__ == '__main__':request_method()

输出:

{"login": "onefine","id": 15047276,"node_id": "MDQ6VXNlcjE1MDQ3Mjc2","avatar_url": "https://avatars1.githubusercontent.com/u/15047276?v=4","gravatar_id": "","url": "https://api.github.com/users/onefine","html_url": "https://github.com/onefine","followers_url": "https://api.github.com/users/onefine/followers","following_url": "https://api.github.com/users/onefine/following{/other_user}","gists_url": "https://api.github.com/users/onefine/gists{/gist_id}","starred_url": "https://api.github.com/users/onefine/starred{/owner}{/repo}","subscriptions_url": "https://api.github.com/users/onefine/subscriptions","organizations_url": "https://api.github.com/users/onefine/orgs","repos_url": "https://api.github.com/users/onefine/repos","events_url": "https://api.github.com/users/onefine/events{/privacy}","received_events_url": "https://api.github.com/users/onefine/received_events","type": "User","site_admin": false,"name": "onefine","company": null,"blog": "","location": null,"email": null,"hireable": null,"bio": null,"public_repos": 5,"public_gists": 0,"followers": 0,"following": 1,"created_at": "2015-10-09T09:10:16Z","updated_at": "2019-02-17T07:31:36Z"
}

更改:

def request_method():response = requests.get(build_uri('user/emails'), auth=('onefine', '******'))print(better_print(response.text))

结果:

[{"email": "188302531@qq.com","primary": true,"verified": true,"visibility": "public"}
]

带参数的请求:

1. URL Parameters: URL参数
  • https://list.tmall.com/search_product.html?cat=50514037&...
  • params: requests.get(url, params={'key1', 'value1'})
2. 表单参数提交
  • Content-Type: application/x-www-form-urlencoded
  • 内容: key1=value1&key2=value2
  • requests.post(url, data={'key1': 'value1', 'key2': 'value2'})
3. json参数提交
  • Content-Type: application/json
  • 内容:’{“key1”: “value1”, “key2”: “value2”}’
  • requests.post(url, json={'key1': 'value1', 'key2': 'value2'})
Get all users

Lists all users, in the order that they signed up on GitHub. This list includes personal user accounts and organization accounts.

Note: Pagination is powered exclusively by the since parameter. Use the Link header to get the URL for the next page of users.

GET /users

Parameters

Name Type Description
since string The integer ID of the last User that you’ve seen.

示例:

def params_request():response = requests.get(build_uri('users'), params={'since': 11})print(better_print(response.text))print(response.request.headers)print(response.url)if __name__ == '__main__':params_request()

输出:

[{"login": "vanpelt","id": 17,"node_id": "MDQ6VXNlcjE3","avatar_url": "https://avatars1.githubusercontent.com/u/17?v=4","gravatar_id": "","url": "https://api.github.com/users/vanpelt","html_url": "https://github.com/vanpelt","followers_url": "https://api.github.com/users/vanpelt/followers","following_url": "https://api.github.com/users/vanpelt/following{/other_user}","gists_url": "https://api.github.com/users/vanpelt/gists{/gist_id}","starred_url": "https://api.github.com/users/vanpelt/starred{/owner}{/repo}","subscriptions_url": "https://api.github.com/users/vanpelt/subscriptions","organizations_url": "https://api.github.com/users/vanpelt/orgs","repos_url": "https://api.github.com/users/vanpelt/repos","events_url": "https://api.github.com/users/vanpelt/events{/privacy}","received_events_url": "https://api.github.com/users/vanpelt/received_events","type": "User","site_admin": false},# ...省略{"login": "knzconnor","id": 53,"node_id": "MDQ6VXNlcjUz","avatar_url": "https://avatars3.githubusercontent.com/u/53?v=4","gravatar_id": "","url": "https://api.github.com/users/knzconnor","html_url": "https://github.com/knzconnor","followers_url": "https://api.github.com/users/knzconnor/followers","following_url": "https://api.github.com/users/knzconnor/following{/other_user}","gists_url": "https://api.github.com/users/knzconnor/gists{/gist_id}","starred_url": "https://api.github.com/users/knzconnor/starred{/owner}{/repo}","subscriptions_url": "https://api.github.com/users/knzconnor/subscriptions","organizations_url": "https://api.github.com/users/knzconnor/orgs","repos_url": "https://api.github.com/users/knzconnor/repos","events_url": "https://api.github.com/users/knzconnor/events{/privacy}","received_events_url": "https://api.github.com/users/knzconnor/received_events","type": "User","site_admin": false}
]
{'User-Agent': 'python-requests/2.21.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'}
https://api.github.com/users?since=11
Update the authenticated user
PATCH /user

Note: If your email is set to private and you send an email parameter as part of this request to update your profile, your privacy settings are still enforced: the email address will not be displayed on your public profile or via the API.

Parameters
Name Type Description
name string The new name of the user.
email string The publicly visible email address of the user.
blog string The new blog URL of the user.
company string The new company of the user.
location string The new location of the user.
hireable boolean The new hiring availability of the user.
bio string The new short biography of the user.

def json_request():response = requests.patch(build_uri('user'), auth=('onefine', '******'),json={'name': 'onefine',# 'email': 'hello-world@onefine.com','blog': 'https://blog.csdn.net/jiduochou963',})print(better_print(response.text))print(response.request.headers)print(response.request.body)print(response.status_code)if __name__ == '__main__':json_request()

输出:

{"login": "onefine","id": 15047276,"node_id": "MDQ6VXNlcjE1MDQ3Mjc2","avatar_url": "https://avatars1.githubusercontent.com/u/15047276?v=4","gravatar_id": "","url": "https://api.github.com/users/onefine","html_url": "https://github.com/onefine","followers_url": "https://api.github.com/users/onefine/followers","following_url": "https://api.github.com/users/onefine/following{/other_user}","gists_url": "https://api.github.com/users/onefine/gists{/gist_id}","starred_url": "https://api.github.com/users/onefine/starred{/owner}{/repo}","subscriptions_url": "https://api.github.com/users/onefine/subscriptions","organizations_url": "https://api.github.com/users/onefine/orgs","repos_url": "https://api.github.com/users/onefine/repos","events_url": "https://api.github.com/users/onefine/events{/privacy}","received_events_url": "https://api.github.com/users/onefine/received_events","type": "User","site_admin": false,"name": "onefine","company": null,"blog": "https://blog.csdn.net/jiduochou963","location": null,"email": "188302531@qq.com","hireable": null,"bio": null,"public_repos": 5,"public_gists": 0,"followers": 0,"following": 1,"created_at": "2015-10-09T09:10:16Z","updated_at": "2019-02-23T06:44:38Z","private_gists": 0,"total_private_repos": 0,"owned_private_repos": 0,"disk_usage": 0,"collaborators": 0,"two_factor_authentication": false,"plan": {"name": "free","space": 976562499,"collaborators": 0,"private_repos": 10000}
}
{'User-Agent': 'python-requests/2.21.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Length': '65', 'Content-Type': 'application/json', 'Authorization': 'Basic b25lZmluZTpTaWxlbnQ5NjMxMjM='}
b'{"name": "onefine", "blog": "https://blog.csdn.net/jiduochou963"}'
200

添加email:

def json_request():response = requests.post(build_uri('user/emails'), auth=('onefine', '******'),json=['hello-world@onefine.com'])print(better_print(response.text))print(response.request.headers)print(response.request.body)print(response.status_code)if __name__ == '__main__':json_request()

输出:

[{"email": "188302531@qq.com","primary": true,"verified": true,"visibility": "public"},{"email": "hello-world@onefine.com","primary": false,"verified": false,"visibility": null}
]
{'User-Agent': 'python-requests/2.21.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Length': '27', 'Content-Type': 'application/json', 'Authorization': 'Basic b25lZmluZTpTaWxlbnQ5NjMxMjM='}
b'["hello-world@onefine.com"]'
201

Requests库-请求异常处理

from requests import exceptions
  • exceptions.BaseHTTPError
  • exceptions.ChunkedEncodingError
  • exceptions.ConnectTimeout
  • exceptions.ConnectionError
  • exceptions.ContentDecodingError
  • exceptions.HTTPError
  • exceptions.InvalidHeader
  • exceptions.InvalidURL
  • exceptions.MissingSchema
  • exceptions.ProxyError
  • exceptions.ReadTimeout
  • exceptions.RequestException
  • exceptions.RetryError
  • exceptions.SSLError
  • exceptions.StreamConsumedError
  • exceptions.Timeout
  • exceptions.TooManyRedirects
  • exceptions.URLRequired

超时为例:

requests.get(url, timeout=(3, 7))requests.get(url, timeout=10)

from requests import exceptionsdef timeout_request():try:response = requests.get(build_uri('user/emails'), timeout=0.1)except exceptions.Timeout as e:print("连接超时:", e)else:print(response.text)if __name__ == '__main__':timeout_request()

输出:

连接超时: HTTPSConnectionPool(host='api.github.com', port=443): Read timed out. (read timeout=0.1)

修改为正常时间:

from requests import exceptionsdef timeout_request():try:response = requests.get(build_uri('user/emails'), timeout=10)except exceptions.Timeout as e:print("连接超时:", e)else:print(response.text)print(response.status_code)if __name__ == '__main__':timeout_request()

输出:

{"message":"Requires authentication","documentation_url":"https://developer.github.com/v3/users/emails/#list-email-addresses-for-a-user"}
401

处理异常:

from requests import exceptionsdef timeout_request():try:response = requests.get(build_uri('user/emails'), timeout=10)# 显式抛出异常:response.raise_for_status()except exceptions.Timeout as e:print("连接超时:", e)except exceptions.HTTPError as e:print("HTTPError: ", e)else:print(response.text)print(response.status_code)if __name__ == '__main__':timeout_request()

输出:

HTTPError:  401 Client Error: Unauthorized for url: https://api.github.com/user/emails

庖丁解牛——自定义Request

读源码,认清复杂事务背后简单的原理。

def hard_requests():from requests import Request, Sessions = Session()headers = {'User-agent': 'fake1.3.4'}req = Request('GET', build_uri('user/emails'), auth=('onefine', 'Silent963123'), headers=headers)prepped = req.prepare()print(prepped.body)print(prepped.headers)if __name__ == '__main__':hard_requests()

输出:

None
{'User-agent': 'fake1.3.4', 'Authorization': 'Basic b25lZmluZTpTaWxlbnQ5NjMxMjM='}

接着:

def hard_requests():from requests import Request, Sessions = Session()headers = {'User-agent': 'fake1.3.4'}req = Request('GET', build_uri('user/emails'), auth=('onefine', 'Silent963123'), headers=headers)prepped = req.prepare()print(prepped.body)print(prepped.headers)resp = s.send(prepped, timeout=5)print(resp.status_code)print(resp.request.headers)print(resp.text)if __name__ == '__main__':hard_requests()

输出:

None
{'User-agent': 'fake1.3.4', 'Authorization': 'Basic b25lZmluZTpTaWxlbnQ5NjMxMjM='}
200
{'User-agent': 'fake1.3.4', 'Authorization': 'Basic b25lZmluZTpTaWxlbnQ5NjMxMjM='}
[{"email":"188302531@qq.com","primary":true,"verified":true,"visibility":"public"},{"email":"hello-world@onefine.com","primary":false,"verified":false,"visibility":null}]

参考:
python的扩展包requests的高级用法: https://www.cnblogs.com/guhao123/p/4054177.html


  1. https://developer.github.com/v3/#http-verbs ↩︎

  2. 有时候用于修改资源,当这并不符合RESTful规范,更好的方法是PATCH。 ↩︎

转载于:https://www.cnblogs.com/onefine/p/10499338.html

Python Requests库使用2:请求方法相关推荐

  1. 接口测试 — 使用Requests库发送POST请求

    POST请求用于向服务器提交数据,比如提交一个表单新建一个用户.或修改一个用户信息等操作. 对于POST请求,我们可以通过浏览器开发者工具或者其他外部工具来进行抓包,得到请求的URL.请求头(requ ...

  2. python requests下载图片_Python使用urllib库、requests库下载图片的方法比较

    我们知道,使用Python制作一个爬虫程序,requests库是一个不错的选择,requests发送网络请求非常简单,比较使用urllib库,使用requests库可以大大减少代码量,它还可以定制请求 ...

  3. 已解决(Python爬虫requests库报错 请求异常SSL错误,证书认证失败问题)requests.exceptions.SSLError: HTTPSConnectionPool

    成功解决(Python爬虫requests库报错 请求异常,SSL错误,证书认证失败问题)requests.exceptions.SSLError: HTTPSConnectionPool(host= ...

  4. python 中文姓名库,Python Requests库上传文件中文文件名处理方法是什么

    使用Python Requests库,提交POST请求上传文件,不支持中文文件名? 使用Python Requests库,向微信服务器上传媒体问题. 当使用英文文件名称,上传时,一切OK. 当下面代码 ...

  5. 手机版python3.6.6的requests库下载_Python爬虫之Python3.6 Requests库的基本使用方法

    Python爬虫之Python3.6 Requests库的基本使用方法 未分类 在使用Python过程中,使用http处理各种请求是我们绕不过去的,在Python中开发爬虫用来抓取各种网络上的资源,就 ...

  6. unittest自动化测试-requests库实现http请求与requests库离线安装

    一.requests库离线安装 1.1 安装requests模块所需依赖包 (1)所需依赖包 chardet,idna,urllib3,certifi (2)下载地址: https://www.lfd ...

  7. Python requests库核心源码解析

    Requests is an elegant and simple HTTP library for Python, built for human beings. Python requests是最 ...

  8. python requests是什么_如何基于Python + requests实现发送HTTP请求

    这篇文章主要介绍了如何基于Python + requests实现发送HTTP请求,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 一.在接口自动化测试 ...

  9. python requests中content与text方法的区别

    python requests中content与text方法的区别 目录 python requests中content与text方法的区别 目录 requests的作用 response的常用方法: ...

  10. 重写python requests库实现自动拼接url

    重写python requests库实现自动拼接url 第一步,新建一个HttpSession类,并继承requests.Session 第二步,实现自动拼接URL 第三步,使用自动拼接的URL发送请 ...

最新文章

  1. 996 成福报?拼多多个别部门让员工在 “11-11-6” 和 996 中二选一
  2. Spring相关的API-ApplicationContext
  3. VTK:相互作用之ClientData
  4. linux命令--sysctl
  5. java反射减少servlet_利用java 反射机制来实现一个servlet处理多种请求
  6. 前端抢饭碗系列之Vue项目如何做单元测试
  7. 算法 - 堆排序(大顶堆、小顶堆)
  8. 惠普:计算机在非洲大有可为(zz)
  9. win2008删除计算机用户,Windws Srv 2008内置账户
  10. python商家入口_购物车--用户和商户入口
  11. 向量的点积与叉乘的几何解释
  12. 如何修改计算机mac,超简单的电脑mac地址查看和修改方法
  13. 微型计算机系统的层次关系图,1.2 计算机系统层次结构
  14. 高通camera模块驱动指南资料介绍
  15. Wamp的介绍和配置,解决安装时一些错误和配置上的一些需要,轻轻松松搭建以为window系统的服务器
  16. Codeforces 918D - MADMAX
  17. wireshark打开cap抓包文件不能显示中文
  18. c语言 模拟memcmp
  19. Ant Design - Authorized
  20. 基于某点评字体库的字体反爬

热门文章

  1. 关于密度函数、分布函数与生存函数的一点看法(一)
  2. Opencv项目实战:12 你这背景太假啦!
  3. python界面-用python编写简单ui界面窗口
  4. VIRTIO协议——split queue与packed queue
  5. 无人机地面站二次开发、深度开发
  6. Vitis_米联客开发板MZU07_7EG上手_1
  7. 北京软件外包公司名单排名大全
  8. Lotus Leaves
  9. 关于python输出换行与不换行
  10. 辅助治疗帕金森病机器人的可行性研究