除了使用 requests
库,Python 调用 API 的方式还有多种,取决于需求和场景。以下是几种常见的方式:
1. http.client
库
Python 的内置库 http.client
提供了对 HTTP 协议的底层支持,适合需要精细控制 HTTP 请求的场景。
import http.client
import json
conn = http.client.HTTPSConnection("api.example.com")
headers = {'Content-type': 'application/json'}
payload = json.dumps({'key': 'value'})
conn.request("POST", "/v1/api/resource", payload, headers)
response = conn.getresponse()
data = response.read()
print(data.decode("utf-8"))
2. urllib
库
urllib
是 Python 内置的网络处理库,支持基本的 HTTP 请求和响应处理。
import urllib.request
import json
url = "https://api.example.com/v1/resource"
headers = {'Content-Type': 'application/json'}
data = json.dumps({'key': 'value'}).encode('utf-8')
req = urllib.request.Request(url, data=data, headers=headers)
response = urllib.request.urlopen(req)
result = response.read().decode('utf-8')
print(result)
3. httpx
库
httpx
是一个支持同步和异步请求的库,功能类似于 requests
,并且具有更好的异步支持。
import httpx
response = httpx.post('https://api.example.com/v1/resource', json={'key': 'value'})
print(response.text)
4. aiohttp
库
如果需要异步请求,aiohttp
是一个非常流行的异步 HTTP 客户端。
import aiohttp
import asyncio
async def fetch_data():
async with aiohttp.ClientSession() as session:
async with session.get('https://api.example.com/v1/resource') as response:
print(await response.text())
asyncio.run(fetch_data())
5. socket
库
在非常底层的情况下,使用 socket
来实现自定义 HTTP 请求,但这种方式需要手动构建 HTTP 报文并解析响应。
import socket
host = "api.example.com"
port = 80
request = "GET /v1/resource HTTP/1.1\r\nHost: {}\r\n\r\n".format(host)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.sendall(request.encode())
response = s.recv(4096)
print(response.decode())
6. gRPC
调用
如果使用 gRPC 协议的 API,可以使用 grpcio
库与服务器通信。
import grpc
from example_pb2_grpc import ExampleStub
from example_pb2 import Request
channel = grpc.insecure_channel('localhost:50051')
stub = ExampleStub(channel)
response = stub.MethodName(Request(param='value'))
print(response)
7. 使用外部工具:curl
和 subprocess
有时可以通过调用外部工具 curl
来发送 API 请求。
import subprocess
result = subprocess.run(['curl', '-X', 'GET', 'https://api.example.com/v1/resource'], stdout=subprocess.PIPE)
print(result.stdout.decode('utf-8'))
总结:
- 简单 HTTP 调用:
requests
,urllib
,httpx
- 异步支持:
httpx
,aiohttp
- 底层控制:
http.client
,socket
- 其他协议:
grpc
for gRPC APIs
根据具体的场景和需求选择合适的方式。