在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接口的方式,具體選擇哪一種取決于你的需求和項目結構。