docs: add comprehensive documentation and licensing

- Add detailed README with usage examples and API reference
- Add CLAUDE.md for Claude Code development guidance
- Add MIT License file
- Add GitHub configuration files
This commit is contained in:
Björn Benouarets
2025-12-01 14:08:32 +01:00
parent 09f1d02e38
commit 2830d4ff25
4 changed files with 513 additions and 0 deletions

38
.github/workflows/pypi.yaml vendored Normal file
View File

@@ -0,0 +1,38 @@
# This workflow will upload a Python Package using Twine when a release is created
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python#publishing-to-package-registries
# This workflow uses actions that are not certified by GitHub.
# They are provided by a third-party and are governed by
# separate terms of service, privacy policy, and support
# documentation.
name: Upload ZeroHTTP to PyPI
on:
release:
types: [published]
permissions:
contents: read
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v3
with:
python-version: "3.12"
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install build
- name: Build package
run: python -m build
- name: Publish package
uses: pypa/gh-action-pypi-publish@release/v1.13
with:
user: __token__
# PYPI_API_TOKEN must be set as a repository secret
password: ${{ secrets.PYPI_API_TOKEN }}

133
CLAUDE.md Normal file
View File

@@ -0,0 +1,133 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project Overview
ZeroHTTP is a lightweight HTTP client library for Python that provides a simple interface for making HTTP requests with various authentication methods. The library is built using Python's standard urllib modules and supports both Basic and Bearer authentication, along with OAuth2 interactive flows for Microsoft Entra (Azure AD).
## Development Commands
### Installation and Setup
```bash
# Install the package in development mode
pip install -e .
# Install dependencies
pip install -r requirements.txt
```
### Build and Package
```bash
# Build the package
python -m build
# Install build dependencies if needed
pip install --upgrade build
```
## Architecture Overview
The library follows a modular architecture with the following key components:
### Core HTTP Client (`src/zerohttp/http.py`)
- **HTTPClient**: Main client class that handles HTTP requests (GET, POST)
- **Response**: Wrapper for HTTP responses with JSON parsing capability
- **Param**: Helper class for URL parameter handling
- Uses Python's built-in `urllib.request` for HTTP operations
- Supports automatic authentication header injection
- Handles both JSON and form-encoded request bodies
### Authentication System (`src/zerohttp/auth/`)
- **BasicAuthentication**: Handles username/password authentication using base64 encoding
- **BearerAuthentication**: Manages token-based Bearer authentication
- **InteractiveProvider**: OAuth2 flow implementation for interactive authentication
- All authentication classes implement `__str__` method for proper header formatting
### Provider Integration (`src/zerohttp/providers/`)
- **Entra**: Microsoft Entra ID OAuth2 provider for user authentication flows
- **EntraApp**: Microsoft Entra ID application authentication using client credentials
- Includes local HTTP server for OAuth2 callback handling
- Automatic browser launching for interactive authentication
## Key Design Patterns
### Authentication Integration
The HTTPClient accepts an `auth` parameter that can be any authentication object. When making requests, it automatically adds the appropriate Authorization header:
```python
# Authentication objects expose their type and token
auth.type # "Basic" or "Bearer"
auth.token # The actual credentials
```
### OAuth2 Interactive Flow
The interactive authentication flow:
1. Starts a local HTTP server on localhost:8000
2. Opens browser for user authentication
3. Waits for callback with authorization code
4. Exchanges code for access token
5. Returns BearerAuthentication object
### URL Building
- Supports `base_url` for common endpoint prefixes
- Automatic parameter encoding and URL construction
- `link()` method for URL generation without making requests
- `webbrowser()` method for direct browser opening
## Development Notes
### Package Structure
- Uses `src/` layout with proper package configuration
- `pyproject.toml` defines build metadata using setuptools
- Package exports configured in `src/zerohttp/__init__.py`
### Dependencies
- Minimal external dependencies (only `setuptools` for building)
- Relies on Python standard library for HTTP operations
- Compatible with Python 3.12+
### Error Handling
- HTTP errors are re-raised after printing response content
- OAuth2 flows raise RuntimeError for authentication failures
- Server startup/shutdown handled in separate threads
## Common Usage Patterns
### Basic HTTP Requests
```python
from zerohttp import HTTPClient
client = HTTPClient(base_url="https://api.example.com")
response = client.get("/users", params=[("page", "1"), ("limit", "10")])
data = response.json()
```
### Authentication
```python
from zerohttp import HTTPClient
from zerohttp.auth import BasicAuthentication, BearerAuthentication
# Basic auth
auth = BasicAuthentication("username", "password")
client = HTTPClient(auth=auth)
# Bearer token auth
auth = BearerAuthentication("your-token-here")
client = HTTPClient(auth=auth)
```
### Microsoft Entra Integration
```python
from zerohttp.providers import Entra, EntraApp
# Interactive user authentication
entra = Entra(tenant="your-tenant-id", client=("client-id", "client-secret"), scope="https://graph.microsoft.com/.default")
auth = entra.authenticate()
client = HTTPClient(auth=auth)
# Application authentication
app = EntraApp(tenant="your-tenant-id", client=("client-id", "client-secret"))
auth = app.authenticate()
client = HTTPClient(auth=auth)
```

9
LICENSE Normal file
View File

@@ -0,0 +1,9 @@
MIT License
Copyright (c) 2026 Björn Benouarets <bjoern@benouarets.de> contribute for SecNex
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

333
README.md Normal file
View File

@@ -0,0 +1,333 @@
# ZeroHTTP
ZeroHTTP is a lightweight HTTP client library for Python that provides various authentication methods and OAuth2 flows for Microsoft Entra (Azure AD).
## Features
- Simple HTTP requests (GET, POST)
- Support for Basic and Bearer Authentication
- OAuth2 integration for Microsoft Entra ID
- Interactive authentication flows
- Client certificate authentication
- Local callback servers for OAuth2
- JSON and form data support
- Minimal dependencies
## Installation
```bash
pip install zerohttp
```
Or for development:
```bash
git clone https://github.com/SecNex/zerohttp.git
cd zerohttp
pip install -e .
```
## Quick Start
### Basic HTTP Requests
```python
from zerohttp import HTTPClient
# Create client
client = HTTPClient(base_url="https://api.example.com")
# GET request with parameters
response = client.get("/users", params=[("page", "1"), ("limit", "10")])
data = response.json()
# POST request with JSON data
response = client.post("/users", data={
"name": "John Doe",
"email": "john@example.com"
})
result = response.json()
```
### Basic Authentication
```python
from zerohttp import HTTPClient
from zerohttp.auth import BasicAuthentication
# Create Basic Authentication
auth = BasicAuthentication("username", "password")
# Client with authentication
client = HTTPClient(auth=auth, base_url="https://api.example.com")
# Request will automatically include Authorization header
response = client.get("/protected-endpoint")
```
### Bearer Token Authentication
```python
from zerohttp import HTTPClient
from zerohttp.auth import BearerAuthentication
# Create Bearer Token
auth = BearerAuthentication("your-access-token-here")
# Client with Bearer Authentication
client = HTTPClient(auth=auth, base_url="https://api.example.com")
response = client.get("/api/data")
```
## Microsoft Entra Integration
### Interactive User Authentication
```python
from zerohttp.providers import Entra
from zerohttp import HTTPClient
# Entra Provider for interactive user authentication
entra = Entra(
tenant="your-tenant-id",
client=("client-id", "client-secret"),
scope="https://graph.microsoft.com/.default"
)
# Perform authentication (opens browser)
auth = entra.authenticate()
# Create client with authenticated token
client = HTTPClient(auth=auth)
# Make requests to Microsoft Graph API
response = client.get("https://graph.microsoft.com/v1.0/me")
user_data = response.json()
```
### Application Authentication (Client Credentials)
```python
from zerohttp.providers import EntraApp
from zerohttp import HTTPClient
# Entra App for Client Credentials Flow
app = EntraApp(
tenant="your-tenant-id",
client=("client-id", "client-secret"),
scope="https://graph.microsoft.com/.default"
)
# Authentication without user interaction
auth = app.authenticate()
# Client for application requests
client = HTTPClient(auth=auth)
response = client.get("https://graph.microsoft.com/v1.0/users")
```
## Advanced Usage
### Custom Headers
```python
from zerohttp import HTTPClient
client = HTTPClient(base_url="https://api.example.com")
# Set individual header
client.set_header("User-Agent", "MyApp/1.0")
# Set multiple headers at once
client.set_headers({
"Content-Type": "application/json",
"Accept": "application/json",
"X-API-Key": "your-api-key"
})
```
### URL Parameter Handling
```python
from zerohttp import HTTPClient
client = HTTPClient(base_url="https://api.example.com")
# GET with complex parameters
response = client.get("/search", params=[
("q", "python"),
("sort", "stars"),
("order", "desc"),
("per_page", "10")
])
```
### URL Generation
```python
from zerohttp import HTTPClient
client = HTTPClient(base_url="https://api.example.com")
# Generate URL without making request
url = client.link("/users", params=[("page", "2"), ("limit", "20")])
# Result: "https://api.example.com/users?page=2&limit=20"
```
### Browser Integration
```python
from zerohttp import HTTPClient
client = HTTPClient(base_url="https://api.example.com")
# Open link in browser
client.webbrowser("/login", params=[
("redirect_uri", "http://localhost:8000/callback"),
("response_type", "code")
])
```
## API Reference
### HTTPClient
Main class for HTTP requests.
**Constructor:**
```python
HTTPClient(auth=None, proxy="", base_url="")
```
**Methods:**
- `get(url="", params=[])` - Send GET request
- `post(url="", data={}, params=[])` - Send POST request
- `set_header(key, value)` - Set individual header
- `set_headers(headers)` - Set multiple headers
- `get_header(key)` - Get header value
- `get_headers()` - Get all headers
- `link(url="", params=[])` - Generate URL
- `webbrowser(url="", params=[])` - Open URL in browser
### Response
Wrapper for HTTP responses.
**Methods:**
- `json()` - Parse response as JSON dictionary
- `text` - Response text as string
### Authentication Classes
#### BasicAuthentication
```python
BasicAuthentication(username: str, password: str)
```
#### BearerAuthentication
```python
BearerAuthentication(token: str)
```
### Entra Provider
#### Entra (Interactive User Authentication)
```python
Entra(
tenant: str,
client: tuple, # (client_id, client_secret)
scope: str,
token_url: str = "https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token",
authorization_url: str = "https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize",
open: bool = True
)
```
#### EntraApp (Application Authentication)
```python
EntraApp(
tenant: str,
client: tuple, # (client_id, client_secret)
scope: str = "https://graph.microsoft.com/.default",
token_url: str = ""
)
```
## Error Handling
ZeroHTTP propagates HTTP errors and prints response contexts:
```python
from zerohttp import HTTPClient
import urllib.error
client = HTTPClient(base_url="https://api.example.com")
try:
response = client.get("/nonexistent-endpoint")
except urllib.error.HTTPError as e:
print(f"HTTP Error: {e.code}")
# Response is automatically printed
except Exception as e:
print(f"Other error: {e}")
```
## OAuth2 Flow Details
The interactive OAuth2 flow works as follows:
1. **Local Server**: An HTTP server is started on `localhost:8000`
2. **Browser Authentication**: User is redirected to Microsoft login page
3. **Callback**: After successful login, user is redirected to local server
4. **Token Exchange**: Authorization code is exchanged for access token
5. **Server Shutdown**: Local server is automatically shutdown
## Development
### Project Structure
```
zerohttp/
├── src/zerohttp/
│ ├── __init__.py
│ ├── __main__.py
│ ├── http.py # HTTPClient and Response
│ ├── auth/ # Authentication classes
│ │ ├── __init__.py
│ │ ├── basic.py
│ │ ├── bearer.py
│ │ └── interactive.py
│ └── providers/ # Provider implementations
│ ├── __init__.py
│ └── entra.py
├── pyproject.toml
├── requirements.txt
└── README.md
```
### Build and Installation
```bash
# Build package
python -m build
# Install in development mode
pip install -e .
# Install dependencies
pip install -r requirements.txt
```
## License
This project is licensed under the MIT License - see [LICENSE](LICENSE) for details.
## Contributing
Contributions are welcome! Please open an issue or pull request.
## Support
For questions and issues, please create a [GitHub Issue](https://github.com/SecNex/zerohttp/issues).