PyActiveResource

2.2.2 · active · verified Mon Apr 13

PyActiveResource is a Python port of Ruby's ActiveResource project, providing an object-relational mapping (ORM) for RESTful web services. It aims to simplify interaction with REST APIs by mapping remote resources to local Python objects, following a 'convention over configuration' philosophy. The current version is 2.2.2, with its last release in February 2021, suggesting a stable but slow release cadence.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a resource class by inheriting from `pyactiveresource.activeresource.ActiveResource` and setting its `_site` attribute to your REST API's base URL. It then shows how to use class methods like `find()` to retrieve resources and instance methods like `save()` to create new ones, encapsulating typical REST interactions. It also includes basic error handling for common `pyactiveresource` exceptions.

import os
from pyactiveresource import activeresource as ar

# Configure your API base URL (e.g., from environment variables)
API_BASE_URL = os.environ.get('PYACTIVERESOURCE_API_URL', 'http://api.example.com/v1')

# Define a resource class that maps to your REST endpoint
class Person(ar.ActiveResource):
    _site = API_BASE_URL
    # Optionally set headers for authentication, e.g., Bearer token
    # _headers = {'Authorization': f'Bearer {os.environ.get("API_TOKEN", "")}'}

# Example usage:
try:
    # Find all people
    all_people = Person.find()
    print(f"Found {len(all_people)} people.")
    for p in all_people:
        print(f"ID: {p.id}, Name: {p.name if hasattr(p, 'name') else 'N/A'}")

    # Find a specific person by ID
    if all_people:
        first_person_id = all_people[0].id
        person = Person.find(first_person_id)
        print(f"\nFound person: {person.name if hasattr(person, 'name') else 'N/A'} (ID: {person.id})")

        # Create a new person
        new_person = Person(name='Alice', age=30)
        if new_person.save():
            print(f"\nCreated new person: {new_person.name} (ID: {new_person.id})")
        else:
            print(f"Failed to create person. Errors: {new_person.errors}")

except ar.ResourceNotFound:
    print(f"Resource not found at {API_BASE_URL}.")
except ar.ConnectionError as e:
    print(f"Connection error: {e}")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →