RESTfly

1.5.1 · active · verified Thu Apr 16

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.

Common errors

Warnings

Install

Imports

Quickstart

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}")

view raw JSON →