apiclient

1.0.4 · active · verified Fri Apr 17

apiclient is a simple, lightweight Python framework for building API clients for REST-like services, leveraging `urllib3` for HTTP requests. It provides decorators for defining API endpoints and handles the boilerplate of request building and response processing. The current version is 1.0.4, with recent minor updates indicating active maintenance.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to define a simple GitHub API client using `APIClient` and the `endpoint` decorator. It fetches public repositories for a given user, explicitly handles the response object for status checking and JSON parsing, and includes basic error handling for network and HTTP errors.

import os
from apiclient import APIClient, endpoint
import urllib3.exceptions # Import for specific error handling

class GitHubClient(APIClient):
    @endpoint
    def get_user_repos(self, username: str):
        # The 'get' method returns a apiclient._response.ResponseWrapper object
        return self.get(f'/users/{username}/repos')

# Initialize the client. For authentication, pass headers.
# Use os.environ.get for an example of token usage.
token = os.environ.get('GITHUB_TOKEN', '')
headers = {'Authorization': f'token {token}'} if token else {}
client = GitHubClient(base_url='https://api.github.com', headers=headers)

try:
    # Call the endpoint. The wrapped urllib3 response is returned.
    response = client.get_user_repos(username='shazow')

    # apiclient returns wrapped urllib3 responses directly.
    # Always check status and explicitly parse JSON.
    response.raise_for_status() # Raises an exception for HTTP error codes (e.g., 404, 500)
    repos = response.json() # Parses the JSON body

    print(f"Successfully fetched {len(repos)} repositories for shazow.")
    if repos:
        print(f"First repository: {repos[0]['name']}")

except urllib3.exceptions.HTTPError as e:
    print(f"HTTP Error: {e.status} - {e.reason}")
except urllib3.exceptions.MaxRetryError as e:
    print(f"Network Error: Could not connect to host. {e}")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →