python怎么封装api接口

   2025-02-15 5190
核心提示:在Python中,可以使用类或函数来封装API接口。使用类封装API接口:import requestsclass APIWrapper:def __init__(self, base_ur

在Python中,可以使用类或函数来封装API接口。

使用类封装API接口:
import requestsclass 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)
使用函数封装API接口:
import requestsdef 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接口的方式,具体选择哪一种取决于你的需求和项目结构。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言