Creating a Reusable Python HTTP Client with Parent and Child Classes

This tutorial demonstrates how to build a reusable Python HTTP client by defining a base HttpRequest class with standard methods, extending it with a RestApiRequest subclass that adds authentication handling, and provides a complete code example showing GET and POST requests.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Creating a Reusable Python HTTP Client with Parent and Child Classes

First, a parent class HttpRequest is defined to encapsulate basic HTTP methods (GET, POST, PUT, DELETE) using the requests library.

Next, a subclass RestApiRequest inherits from HttpRequest and adds an auth_token attribute for authentication.

The subclass overrides __init__ to accept base_url and an optional auth_token, calling super().__init__(base_url) to initialize the base URL.

All request methods (get, post, put, delete) are overridden to automatically inject an Authorization header when auth_token is present, then delegate to the parent implementation via super().

Additional helper methods add_auth_token and remove_auth_token are provided to manage the token at runtime.

A complete example shows importing requests, defining both classes, and using the subclass to perform GET and POST calls, printing status codes and JSON responses.

import requests
# 父类
class HttpRequest:
    def __init__(self, base_url):
        self.base_url = base_url
    def get(self, endpoint, params=None, headers=None):
        url = f"{self.base_url}/{endpoint}"
        response = requests.get(url, params=params, headers=headers)
        return response
    def post(self, endpoint, data=None, json=None, headers=None):
        url = f"{self.base_url}/{endpoint}"
        response = requests.post(url, data=data, json=json, headers=headers)
        return response
    def put(self, endpoint, data=None, json=None, headers=None):
        url = f"{self.base_url}/{endpoint}"
        response = requests.put(url, data=data, json=json, headers=headers)
        return response
    def delete(self, endpoint, headers=None):
        url = f"{self.base_url}/{endpoint}"
        response = requests.delete(url, headers=headers)
        return response
# 子类
class RestApiRequest(HttpRequest):
    def __init__(self, base_url, auth_token=None):
        super().__init_(base_url)
        self.auth_token = auth_token
    def get(self, endpoint, params=None):
        headers = {}
        if self.auth_token:
            headers['Authorization'] = f'Bearer {self.auth_token}'
        return super().get(endpoint, params=params, headers=headers)
    def post(self, endpoint, data=None, json=None):
        headers = {}
        if self.auth_token:
            headers['Authorization'] = f'Bearer {self.auth_token}'
        return super().post(endpoint, data=data, json=json, headers=headers)
    def put(self, endpoint, data=None, json=None):
        headers = {}
        if self.auth_token:
            headers['Authorization'] = f'Bearer {self.auth_token}'
        return super().put(endpoint, data=data, json=json, headers=headers)
    def delete(self, endpoint):
        headers = {}
        if self.auth_token:
            headers['Authorization'] = f'Bearer {self.auth_token}'
        return super().delete(endpoint, headers=headers)
    def add_auth_token(self, token):
        self.auth_token = token
    def remove_auth_token(self):
        self.auth_token = None
# 使用示例
if __name__ == "__main__":
    base_url = "https://api.example.com"
    auth_token = "your_auth_token_here"
    # 创建 RestApiRequest 实例
    api = RestApiRequest(base_url, auth_token)
    # 发送 GET 请求
    response = api.get("users")
    print(response.status_code)
    print(response.json())
    # 发送 POST 请求
    data = {"name": "Alice", "age": 30}
    response = api.post("users", json=data)
    print(response.status_code)
    print(response.json())
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonHTTPREST APIOOPrequests
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.