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
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, andDELETE. - 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.HTTPErrorfor 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.
-
Start the tool:
daffalib-cli
-
Enter the base URL when prompted:
Welcome to the daffalib Interactive Console! ... Enter Base URL: https://jsonplaceholder.typicode.com API client initialized for https://jsonplaceholder.typicode.com daffalib> -
Use direct commands to interact with the API:
daffalib> get /users/1 {'address': {'city': 'Gwenborough', 'geo': {'lat': '-37.3159', 'lng': '81.1496'}, 'street': 'Kulas Light', 'suite': 'Apt. 556', 'zipcode': '92998-3874'}, 'company': {'bs': 'harness real-time e-markets', 'catchPhrase': 'Multi-layered client-server neural-net', 'name': 'Romaguera-Crona'}, 'email': 'Sincere@april.biz', 'id': 1, 'name': 'Leanne Graham', 'phone': '1-770-736-8031 x56442', 'username': 'Bret', 'website': 'hildegard.org'} daffalib> post /todos '{"userId": 1, "title": "Learn daffalib", "completed": true}' {'userId': 1, 'title': 'Learn daffalib', 'completed': True, 'id': 201} daffalib> exit
License
This project is licensed under the MIT License - see the LICENSE file for details.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file daffalib-0.2.5.tar.gz.
File metadata
- Download URL: daffalib-0.2.5.tar.gz
- Upload date:
- Size: 6.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
dd639db7a7a0a5e1f9ad4dc836312cef4bc194ceb0a9602c670a46efda2ebfaa
|
|
| MD5 |
0e7ca588a8fc97e3b41d8550787f6049
|
|
| BLAKE2b-256 |
8454c03aab9a1f02283068a46416ed990f21e86bec99764b2d820d9e90809b43
|
File details
Details for the file daffalib-0.2.5-py3-none-any.whl.
File metadata
- Download URL: daffalib-0.2.5-py3-none-any.whl
- Upload date:
- Size: 7.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
c24d6458943efaf2f280e7a184babd6c8e40874306a67759e61b00e371d68b86
|
|
| MD5 |
fa21ec39671585dcc2d2fca498cc1461
|
|
| BLAKE2b-256 |
ca88aebee09cf90284a1749b42223ecc49020632bbf75aa97238fcbc17f7a1a9
|