本文介绍了使用Python调用API的四种常见方式,并提供了相应的代码实例,帮助开发者快速理解和应用。
```python
import pycurl
from io import BytesIO
buffer = BytesIO()
c = pycurl.Curl()
github_url = https://api.github.com/repos/username/repo
user_pwd = username:token
data = {name: test}
c.setopt(pycurl.URL, github_url)
c.setopt(pyccurl.USERPWD, user_pwd)
c.setopt(pycurl.POST, 1)
c.setopt(pycurl.POSTFIELDS, data)
c.setopt(c.WRITEDATA, buffer)
c.perform()
c.close()
response_body = buffer.getvalue()
print(response_body.decode(utf-8))
# Alternatively using requests
import requests
import json
github_url = https://api.github.com/repos/username/repo
data = {name: test}
headers = {
Authorization: token token_value,
}
response = requests.post(github_url, headers=headers, data=json.dumps(data))
print(response.json())
```