Registry / http-networking / restfly

restfly

JSON →
library1.5.1pypypi✓ verified 87d ago

RESTfly (pronounced restfully) is a framework for building libraries to easily interact with RESTful APIs. It aims to simplify the creation of API interaction libraries by providing a basic scaffolding with an emphasis on simplicity and readability of the resulting code. The library is currently at version 1.5.1 and receives regular updates, ensuring active development and maintenance.

pip install restfly
INSTALL
IMPORT
SIG · RESTFLY
R
restfly
http-networkingpythonv1.5.1
Install
2.7s avg
Import
702ms
Disk
32MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v1.5.1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.920 runs
installs and imports cleanly · install 0.0s · import 0.737s · 26.2MB
glibc
py 3.103.920 runs
installs and imports cleanly · install 2.7s · import 0.668s · 44MB
32MB installed
● package 32MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

APISession
from restfly.session import APISession
from restfly import APISession
APISession is located within the `session` submodule.
APIEndpoint
from restfly.endpoint import APIEndpoint
from restfly import APIEndpoint
APIEndpoint is located within the `endpoint` submodule.
APIError
from restfly.errors import APIError, BadRequestError, UnauthorizedError
Specific HTTP status code errors are provided in the `errors` submodule for granular exception handling.

This quickstart demonstrates how to set up a basic API client using `APISession` and organize API calls with `APIEndpoint`. It includes an example of handling API keys and specific HTTP status code errors.

import os from restfly.session import APISession from restfly.endpoint import APIEndpoint # Define your base API session class MyAPI(APISession): _url = 'https://httpbin.org' # Example of adding an API key, if needed def __init__(self, api_key: str = os.environ.get('MY_API_KEY', ''), **kwargs): self._api_key = api_key super().__init__(**kwargs) def _build_session(self, **kwargs): super()._build_session(**kwargs) if self._api_key: self._session.headers.update({ 'X-API-Key': self._api_key }) # Define an endpoint for a specific resource class StatusAPI(APIEndpoint): _path = 'status' def get_status_code(self, code: int) -> dict: # _req is a protected method for making requests, leveraging _path return self._req('GET', path=str(code)).json() # Instantiate and use the API my_api_client = MyAPI(api_key='your_optional_api_key_here') # Link the endpoint to the API session my_api_client.status = StatusAPI(my_api_client) try: # Call a simple GET request directly from the session response_get = my_api_client.get('get').json() print(f"GET /get Response: {response_get.get('url')}") # Use the defined endpoint status_200 = my_api_client.status.get_status_code(200) print(f"GET /status/200 Response: {status_200}") status_404 = my_api_client.status.get_status_code(404) print(f"GET /status/404 Response: {status_404}") # This will raise an APIError except Exception as e: print(f"An error occurred: {e}") # Example of handling specific errors from restfly.errors import NotFoundError, APIError try: my_api_client.status.get_status_code(404) except NotFoundError as e: print(f"Caught specific NotFoundError: {e}") except APIError as e: print(f"Caught generic APIError: {e}")
Debug
Known issues
gotchaWhen handling session-based authentication, developers commonly forget to explicitly log out or close sessions, potentially leading to lingering sessions. RESTfly offers context management hooks to facilitate proper authentication and de-authentication.
fix
Implement authentication and de-authentication using context management stubs provided by RESTfly, especially for session-based APIs. Refer to 'Context handling and authentication' in the official documentation.
affects: All versions
gotchaRESTfly wraps common HTTP status codes (e.g., 400, 401, 403, 404, 500) into specific exception classes (e.g., `BadRequestError`, `UnauthorizedError`, `NotFoundError`). Failing to catch these specific exceptions can lead to less granular error handling, potentially masking the true nature of API failures.
fix
Catch specific `restfly.errors` exceptions (e.g., `NotFoundError`, `BadRequestError`) instead of a generic `APIError` or `requests.exceptions.HTTPError` for more precise error management.
affects: All versions
breakingThe project repository was moved in version 1.5.0. While `pip install` typically handles this, direct clones or older documentation links referencing the previous repository location may be broken.
fix
Update any hardcoded repository URLs or documentation links to the new GitHub organization: `https://github.com/librestfly/restfly`.
affects: >=1.5.0
Errors
Common errors & fixes
ImportError: cannot import name 'APISession' from 'restfly'
Attempting to import `APISession` directly from the top-level `restfly` package instead of its specific submodule.
fix
Use `from restfly.session import APISession`.
AttributeError: 'Response' object has no attribute 'json'
This typically occurs when a `requests.Response` object (which `restfly` uses internally) is returned, but the content is not JSON, or the `.json()` method is called on an empty response. It can also happen if `_conv_json` is set to `False` in the `APISession` and the result is not manually parsed.
fix
Ensure the API endpoint actually returns JSON content. For non-JSON responses, access `response.text` or `response.content`. If `_conv_json` is explicitly set to `False`, handle the raw `requests.Response` object accordingly. Consider checking `response.ok` or `response.status_code` before attempting to parse.
restfly.errors.UnauthorizedError: 401 Unauthorized
The API request failed due to missing or invalid authentication credentials (e.g., incorrect API key, expired token).
fix
Verify that your API key, token, or other authentication methods are correctly configured and passed in the `APISession` initialization or request headers. Use context handling for session-based authentication to ensure proper login/logout.
Upgrade
Version history
1.5.1latest on PyPI · released Jan 17, 2025
Audit
Dependencies
pythonrequiredRequires Python 3.9 or newer.
Agent activity
12 hits · last 30 days
node
10
Resources
restfly — pip install restfly · libregistry