Linux 拨号vps windows公众号手机端

python怎么封装api接口

lewis 8年前 (2017-10-11) 阅读数 14 #程序编程
文章标签 python

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

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

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门