在Python中,可以使用类和函数来封装API接口。下面是两种常见的封装方式:
使用类封装API接口:import requestsclass MyAPI:def __init__(self, base_url):self.base_url = base_urldef get_data(self, path):url = self.base_url + pathresponse = requests.get(url)return response.json()# 使用示例api = MyAPI("https://api.example.com")data = api.get_data("/users")print(data)使用函数封装API接口:import requestsdef get_data(base_url, path):url = base_url + pathresponse = requests.get(url)return response.json()# 使用示例base_url = "https://api.example.com"data = get_data(base_url, "/users")print(data)无论使用类还是函数来封装API接口,都可以根据实际需求进行进一步封装,添加参数验证、错误处理、身份认证等功能。

