Simple REST Client
Simple REST client for Python 3.8+ that aims to make interacting with REST APIs straightforward. It provides a clean API for defining resources and actions, handles HTTP requests, and parses responses. Currently at version 1.2.1, it follows a stable release cadence with updates addressing bug fixes and minor improvements, focusing on simplicity and ease of use.
Common errors
-
simple_rest_client.exceptions.ClientError: 404 Client Error: Not Found for url: ...
cause The requested endpoint or resource path does not exist on the API server, or the base URL (`api_root_url`) is incorrect.fixDouble-check the `api_root_url` and the resource/action paths being used. Verify the API documentation for correct endpoints and ensure no typos. -
requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(104, 'Connection reset by peer'))cause A network connectivity issue, incorrect `api_root_url` (e.g., wrong port or hostname), or the API server is unavailable or actively refusing the connection.fixVerify your network connection and the correctness of the `api_root_url`. Check if the API server is running, accessible from your environment, and correctly configured to accept connections. -
AttributeError: 'SimpleRestClient' object has no attribute 'my_resource'
cause You attempted to access a resource (e.g., `client.my_resource`) that has not been registered with the `SimpleRestClient` instance using `add_resource` or `add_action`.fixEnsure you have called `client.add_resource("my_resource", MyResourceClass)` or `client.add_action("my_action", MyActionClass)` *before* trying to access `client.my_resource` or `client.my_action`.
Warnings
- breaking Prior to version 1.0.0, the primary method for defining API interactions was `client.get_action()`. Version 1.0.0 introduced `client.add_resource()` and the `Resource` class, which are now the recommended and more powerful approach for CRUD operations and custom endpoints.
- gotcha The `ssl_verify=False` parameter, often seen in examples or used during development, disables SSL certificate verification. Using this in a production environment makes connections vulnerable to man-in-the-middle attacks.
- gotcha By default, `simple-rest-client` raises exceptions (e.g., `simple_rest_client.exceptions.ClientError`, `BadRequestError`, `UnauthorizedError`) for non-2xx HTTP responses. Users unfamiliar with this might not implement proper error handling, leading to unhandled exceptions.
Install
-
pip install simple-rest-client
Imports
- SimpleRestClient
from simple_rest_client.client import SimpleRestClient
- Resource
from simple_rest_client.resource import Resource
- ClientError
from simple_rest_client.exceptions import ClientError
Quickstart
import os
from simple_rest_client.client import SimpleRestClient
from simple_rest_client.resource import Resource
# Define a resource for users. Basic CRUD actions (list, get, create, update, delete) are
# automatically available if not overridden or custom actions defined.
class UserResource(Resource):
pass
# Initialize the client for a public API (e.g., JSONPlaceholder).
# In a production environment, ensure ssl_verify is True and handle authentication.
client = SimpleRestClient(
api_root_url="https://jsonplaceholder.typicode.com/",
ssl_verify=True, # Always prefer True in production. Set to False only for testing untrusted SSL.
headers={
"Authorization": f"Bearer {os.environ.get('API_KEY', '')}"
} # Example for authentication token
)
# Add the user resource to the client, making it accessible via client.users
client.add_resource(resource_name="users", resource_class=UserResource)
try:
# Example 1: Get all users
print("\nFetching all users...")
all_users = client.users.list()
print(f"First user: {all_users[0]['name']}")
# Example 2: Get a single user by ID
print("\nFetching user with ID 1...")
user_1 = client.users.get(1)
print(f"User 1 name: {user_1['name']}, email: {user_1['email']}")
# Example 3: Create a new user (NOTE: JSONPlaceholder is a fake API; this won't persist)
print("\nCreating a new user (API will return 201, but not persist on JSONPlaceholder)...")
new_user_data = {
"name": "Jane Doe",
"username": "janedoe",
"email": "jane.doe@example.com",
"address": {"street": "123 Main St"}
}
created_user = client.users.create(new_user_data)
print(f"Created user ID: {created_user.get('id', 'N/A')}, Name: {created_user['name']}")
except Exception as e:
print(f"An error occurred: {e}")