Skip to main content

A Python library for simplifying HTTP integrations with REST APIs, featuring decorators for authentication handling and request management.

Project description

🌐 Nexilum Library Documentation

Python 3.7+ License: MIT

A Python library for simplifying HTTP integrations with REST APIs, featuring decorators for authentication handling and request management.

Table of Contents

🚀 Features

  • ✨ Decorator-based HTTP integration setup
  • 🔐 Automatic authentication management
  • 🔄 Request retry mechanism for server errors (up to 3 retries)
  • 🛡️ SSL verification support
  • 📝 Flexible header and parameter management
  • ⚡ Context manager support
  • 🔍 Comprehensive error handling

📦 Installation

pip install nexilum

🔧 Components

Nexilum Class

The core class handling HTTP requests and responses:

from nexilum import Nexilum

client = Nexilum(
    base_url="https://api.example.com",
    headers={"Content-Type": "application/json"},
    timeout=30,
    verify_ssl=True
)

Key Features:

  • 🔗 Configurable base URL, headers, and parameters
  • 🛡️ SSL verification toggle
  • ⏱️ Custom timeout settings (default: 30 seconds)
  • 🔄 Automatic retry mechanism for 5xx errors
  • 📝 JSON request/response handling

Decorators

@connect_to

@connect_to(
    base_url: str,
    headers: Optional[Dict[str, str]] = None,
    params: Optional[Dict[str, Any]] = None,
    timeout: int = DEFAULT_TIMEOUT,
    verify_ssl: bool = True
)

Main decorator for connecting a class to an HTTP integration.

@login

@login
def authenticate(self, method=HTTPMethod.POST, endpoint="login", **data):
    """
    Handle authentication and token management.
    Returns the authentication response or None if already authenticated.
    """
    pass

@logout

@logout
def end_session(self, method=HTTPMethod.POST, endpoint="end_session", **data):
    """
    Manage session termination and token cleanup.
    Returns the logout response or None if already logged out.
    """
    pass

@auth

@auth
def protected_endpoint(self, endpoint="end_session", method=HTTPMethod.GET, **data):
    """
    Ensure authentication before method execution.
    Automatically handles re-authentication if needed.
    """
    pass

📘 Usage

Basic Setup

from http import HTTPMethod
from nexilum import Nexilum, connect_to

Error Handling

from nexilum.exceptions import Nexilum_error

try:
    with Nexilum(base_url="https://api.example.com") as client:
        response = client.request(
            method=HTTPMethod.GET,
            endpoint="users"
        )
except Nexilum_error as e:
    print(f"Error occurred: {e}")

💻 Example Implementation

Class-Based Implementation

from http import HTTPMethod
from nexilum import connect_to

@connect_to(
    base_url="https://jsonplaceholder.typicode.com", 
    headers={"Content-Type": "application/json"}
)
class JSONPlaceholder:
    def get_posts(self, method=HTTPMethod.GET, endpoint="posts", **data):
        pass

    def get_post(self, method=HTTPMethod.GET, endpoint="posts/{post_id}", **data):
        pass

    def get_post_comments(self, method=HTTPMethod.GET, endpoint="posts/{post_id}/comments", **data):
        pass

    def create_post(self, method=HTTPMethod.POST, endpoint="posts", **data):
        pass

    def update_post(self, method=HTTPMethod.PUT, endpoint="posts/{post_id}", **data):
        pass

    def delete_post(self, method=HTTPMethod.DELETE, endpoint="posts/{post_id}", **data):
        pass

    def get_users(self, method=HTTPMethod.GET, endpoint="users", **data):
        pass

    def get_user(self, endpoint:str, method=HTTPMethod.GET, **data):
        pass

    def get_user_posts(self, method=HTTPMethod.GET, endpoint="users/{user_id}/posts", **data):
        pass

    def get_user_todos(self, method=HTTPMethod.GET, endpoint="users/{user_id}/todos", **data):
        pass

Example usage with decorators:

# Initialize client
api = JSONPlaceholder()

# Get all posts
posts = api.get_posts()

# Get specific post
post = api.get_post(endpoint="posts/1")

# Create new post
new_post = api.create_post(data={
    "title": "foo",
    "body": "bar",
    "userId": 1
})

# Update post
updated_post = api.update_post(
    endpoint="posts/1",
    data={
        "id": 1,
        "title": "foo updated",
        "body": "bar updated",
        "userId": 1
    }
)

# Delete post
deleted = api.delete_post(endpoint="posts/1")

# Get users
users = api.get_users()

# Get specific user
user = api.get_user(endpoint="users/1")

Direct Usage

from http import HTTPMethod
from nexilum import Nexilum

# Initialize the Nexilum instance
api = Nexilum(
    base_url="https://jsonplaceholder.typicode.com",
    headers={"Content-Type": "application/json"}
)

# Using the context manager for safe resource handling
with api as client:
    # Get all posts
    posts = client.request(
        method=HTTPMethod.GET,
        endpoint="posts"
    )

    # Get specific post
    post = client.request(
        method=HTTPMethod.GET,
        endpoint="posts/1"
    )

    # Create new post
    new_post = client.request(
        method=HTTPMethod.POST,
        endpoint="posts",
        data={
            "title": "foo",
            "body": "bar",
            "userId": 1
        }
    )

    # Update post
    updated_post = client.request(
        method=HTTPMethod.PUT,
        endpoint="posts/1",
        data={
            "id": 1,
            "title": "foo updated",
            "body": "bar updated",
            "userId": 1
        }
    )

    # Delete post
    deleted = client.request(
        method=HTTPMethod.DELETE,
        endpoint="posts/1"
    )

    # Get users
    users = client.request(
        method=HTTPMethod.GET,
        endpoint="users"
    )

    # Get specific user
    user = client.request(
        method=HTTPMethod.GET,
        endpoint="users/1"
    )

# Example with error handling
try:
    with Nexilum(base_url="https://jsonplaceholder.typicode.com") as client:
        response = client.request(
            method=HTTPMethod.GET,
            endpoint="nonexistent"
        )
except Nexilum_error as e:
    print(f"Error occurred: {e}")

📚 API Documentation

Nexilum Class

Constructor Parameters

Parameter Type Required Default Description
base_url str Yes - Base API URL
headers Dict No None Default request headers
params Dict No None Default query parameters
timeout int No 30 Request timeout in seconds
verify_ssl bool No True SSL verification flag

Methods

request()
def request(
    self,
    method: HTTPMethod,
    endpoint: str,
    data: Optional[Dict[str, Any]] = None,
    params: Optional[Dict[str, Any]] = None,
    retry_count: int = 0
) -> Optional[Dict[str, Any]]

Parameters:

  • method: HTTP method (GET, POST, etc.)
  • endpoint: API endpoint
  • data: Request body (optional)
  • params: Query parameters (optional)
  • retry_count: Current retry attempt (internal use)

Error Handling

The Nexilum_error class provides structured error information:

class Nexilum_error(Exception):
    def __init__(self, message: str, status_code: Optional[int] = None, response: Any = None):
        self.message = message
        self.status_code = status_code
        self.response = response
        super().__init__(self.message)

⚡ Best Practices

  1. Use Type Hints

    from typing import Dict, Optional
    
  2. Context Managers

    with Nexilum(base_url="https://api.example.com") as client:
        # Your code here
    
  3. Error Handling

    try:
        response = client.request(...)
    except Nexilum_error as e:
        if e.status_code == 404:
            # Handle not found
    
  4. Security

    • Enable SSL verification in production
    • Store sensitive credentials securely
    • Use environment variables for configuration
  5. Performance

    • Configure appropriate timeout values
    • Handle rate limiting appropriately
    • Use connection pooling when available

📝 License

This project is licensed under the MIT License - see the LICENSE file for details.


Made with ❤️ by the Nexilum team.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

nexilum-0.0.6.tar.gz (9.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

nexilum-0.0.6-py3-none-any.whl (11.6 kB view details)

Uploaded Python 3

File details

Details for the file nexilum-0.0.6.tar.gz.

File metadata

  • Download URL: nexilum-0.0.6.tar.gz
  • Upload date:
  • Size: 9.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.9

File hashes

Hashes for nexilum-0.0.6.tar.gz
Algorithm Hash digest
SHA256 88f2f4d07cf8c67d264e6acbea1430b7751c5f8f30a34875df981505b03bd42a
MD5 f93fd0153dcbebd081aa816d91e3b9bf
BLAKE2b-256 93a47ac92ddcae46b6d38148573a714489c85be2a97200fbcf2751ba6d00d5c0

See more details on using hashes here.

File details

Details for the file nexilum-0.0.6-py3-none-any.whl.

File metadata

  • Download URL: nexilum-0.0.6-py3-none-any.whl
  • Upload date:
  • Size: 11.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.9

File hashes

Hashes for nexilum-0.0.6-py3-none-any.whl
Algorithm Hash digest
SHA256 bae8cc6a4e0057d2b6a02804862d4fc4080bb53abe85abf36d267bf141884e3b
MD5 c3764d26022849a104f9e694cc24ca78
BLAKE2b-256 3fa524fe3f99ced83f3fd8fab041706c054711ba7c58733a56d16fd057fa6921

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page