在Python中,可以使用类或函数来封装API接口。
import requests
class APIWrapper:
def __init__(self, base_url):
self.base_url = base_url
def get_data(self, endpoint, params=None):
url = self.base_url + endpoint
response = requests.get(url, params=params)
return response.json()
def post_data(self, endpoint, data=None):
url = self.base_url + endpoint
response = requests.post(url, json=data)
return response.json()
# 使用示例
api = APIWrapper('https://api.example.com')
data = api.get_data('/users')
print(data)
import requests
def get_data(base_url, endpoint, params=None):
url = base_url + endpoint
response = requests.get(url, params=params)
return response.json()
def post_data(base_url, endpoint, data=None):
url = base_url + endpoint
response = requests.post(url, json=data)
return response.json()
# 使用示例
base_url = 'https://api.example.com'
data = get_data(base_url, '/users')
print(data)
以上是两种常见的封装API接口的方式,具体选择哪一种取决于你的需求和项目结构。