Skip to main content

A modern and ultra-simple Python wrapper for the requests library, designed to simplify REST API interactions with flexible configuration and REPL support.

Project description

daffalib

PyPI version

A modern and ultra-simple Python wrapper for the requests library, designed to simplify REST API interactions with flexible configuration and built-in REPL support.

Features

  • Simple Interface: Clean and intuitive methods for GET, POST, PUT, and DELETE.
  • Automatic JSON Parsing: Responses are automatically converted to Python dictionaries.
  • Graceful Fallback: If a response is not valid JSON, the raw text content is returned.
  • Automatic Error Handling: Raises requests.HTTPError for unsuccessful responses (4xx or 5xx status codes).
  • Flexible Configuration: Easily configure base URLs, default headers, and authentication for your API session.
  • Interactive REPL: A command-line tool for interacting with APIs directly from your terminal.

Installation

Install daffalib using pip:

pip install daffalib

Basic Usage

Instantiate the API class with a base URL and start making requests. The methods return a dictionary or a string directly.

from daffalib import API
from requests.exceptions import HTTPError

# Use a public test API
api = API("https://jsonplaceholder.typicode.com")

try:
    # GET request
    posts = api.get("posts")
    print(f"Found {len(posts)} posts.")

    # GET a single item
    post = api.get("posts/1")
    print(f"Title of post #1: {post['title']}")

    # POST request
    new_post_data = {
        "title": "My New Post",
        "body": "This is the content.",
        "userId": 1
    }
    created_post = api.post(new_post_data, endpoint="posts")
    print(f"Created new post with ID: {created_post['id']}")

    # PUT request
    updated_data = {"title": "Updated Title"}
    updated_post = api.put("posts/1", data=updated_data)
    print(f"Updated post #1's title to: {updated_post['title']}")

    # DELETE request
    response = api.delete("posts/1")
    print("Delete response:", response) # Often empty on success

except HTTPError as e:
    print(f"An HTTP error occurred: {e.response.status_code} {e.response.reason}")
except Exception as e:
    print(f"An error occurred: {e}")

Custom Headers and Authentication

You can configure default headers and authentication when initializing the API object.

from daffalib import API
from requests.auth import HTTPBasicAuth

# Custom headers
headers = {
    "Authorization": "Bearer YOUR_ACCESS_TOKEN",
    "X-Custom-Header": "MyValue"
}

# Basic Authentication
auth = HTTPBasicAuth('your_username', 'your_password')

# Initialize with headers and auth
secure_api = API(
    base_url="https://api.yourapi.com/v1/",
    headers=headers,
    auth=auth
)

# All requests made with `secure_api` will now include the configured headers and auth
data = secure_api.get("user/profile")
print(data)

Interactive REPL Mode

daffalib includes a command-line tool for quick API exploration. Just run daffalib-cli in your terminal.

  1. Start the tool:

    daffalib-cli
    
  2. Enter the base URL when prompted:

    Welcome to the daffalib Interactive Console!
    ...
    Enter Base URL: https://jsonplaceholder.typicode.com
    >>>
    
  3. Use the pre-configured req object to make calls:

    >>> user = req.get('users/1')
    >>> print(user['name'])
    Leanne Graham
    >>>
    >>> new_todo = {'userId': 1, 'title': 'Learn daffalib', 'completed': True}
    >>> created = req.post(new_todo, 'todos')
    >>> print(created)
    {'userId': 1, 'title': 'Learn daffalib', 'completed': True, 'id': 201}
    >>>
    

License

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

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

daffalib-0.1.0.tar.gz (5.5 kB view details)

Uploaded Source

Built Distribution

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

daffalib-0.1.0-py3-none-any.whl (7.0 kB view details)

Uploaded Python 3

File details

Details for the file daffalib-0.1.0.tar.gz.

File metadata

  • Download URL: daffalib-0.1.0.tar.gz
  • Upload date:
  • Size: 5.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.12

File hashes

Hashes for daffalib-0.1.0.tar.gz
Algorithm Hash digest
SHA256 cfe0a63140ffda1daa08c3d6ea33e6f760b2e6ce95be87540154a50353000526
MD5 1cde735fa80390f9eb3fd2e47e7043f2
BLAKE2b-256 5adf247bb95194eee3aac0845e3fa3af61b60b5b742dfa4f2bf4d2f23ef4e9d1

See more details on using hashes here.

File details

Details for the file daffalib-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: daffalib-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 7.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.12

File hashes

Hashes for daffalib-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 860ae67c3d6897165c68cff334fbba204c8602693cb328e54d8c003ee325ba57
MD5 f500814875e6004f860fb7b84c72a103
BLAKE2b-256 a037a8b6dd7ef61008576d9548a4fbcabc4d039bf168bfa3e6e813adb2395bc6

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