API Documentation

drest.api

dRest core API connection library.

class drest.api.API(baseurl=None, **kw)

The API class acts as a high level ‘wrapper’ around multiple lower level handlers. Most of the meta arguments are optionally passed to one or more handlers upon instantiation. All handler classes must be passed un-instantiated.

Arguments:

baseurl
Translated to self.baseurl (for convenience).

Optional Arguments and Meta:

debug
Boolean. Toggle debug console output. Default: False.
baseurl
The base url to the API endpoint.
request_handler
The Request Handler class that performs the actual HTTP (or other) requests. Default: drest.request.RequestHandler.
resource_handler
The Resource Handler class that is used when api.add_resource is called. Default: drest.resource.ResourceHandler.
response_handler
An un-instantiated Response Handler class used to return responses to the caller. Default: drest.response.ResponseHandler.
serialization_handler
An un-instantiated Serialization Handler class used to serialize/deserialize data. Default: drest.serialization.JsonSerializationHandler.
ignore_ssl_validation
Boolean. Whether or not to ignore ssl validation errors. Default: False
serialize
Boolean. Whether or not to serialize data before sending requests. Default: False.
deserialize
Boolean. Whether or not to deserialize data before returning the Response object. Default: True.
trailing_slash
Boolean. Whether or not to append a trailing slash to the request url. Default: True.
extra_headers
A dictionary of key value pairs that are added to the HTTP headers of every request. Passed to request_handler.add_header().
extra_params
A dictionary of key value pairs that are added to the POST, or ‘payload’ data sent with every request. Passed to request_handler.add_param().
extra_url_params
A dictionary of key value pairs that are added to the GET/URL parameters of every request. Passed to request_handler.add_extra_url_param().
timeout
The amount of seconds where a request should timeout. Default: 30

Usage

import drest

# Create a generic client api object
api = drest.API('http://localhost:8000/api/v1/')

# Or something more customized:
api = drest.API(
    baseurl='http://localhost:8000/api/v1/',
    trailing_slash=False,
    ignore_ssl_validation=True,
    )

# Or even more so:
class MyAPI(drest.API):
    class Meta:
        baseurl = 'http://localhost:8000/api/v1/'
        extra_headers = dict(MyKey='Some Value For Key')
        extra_params = dict(some_param='some_value')
        request_handler = MyCustomRequestHandler
api = MyAPI()

# By default, the API support HTTP Basic Auth with username/password.
api.auth('john.doe', 'password')

# Make calls openly
response = api.make_request('GET', '/users/1/')

# Or attach a resource
api.add_resource('users')

# Get available resources
api.resources

# Get all objects of a resource
response = api.users.get()

# Get a single resource with primary key '1'
response = api.users.get(1)

# Update a resource with primary key '1'
response = api.users.get(1)
updated_data = response.data.copy()
updated_data['first_name'] = 'John'
updated_data['last_name'] = 'Doe'

response = api.users.put(data['id'], updated_data)

# Create a resource
user_data = dict(
    username='john.doe',
    password='oober-secure-password',
    first_name='John',
    last_name='Doe',
    )
response = api.users.post(user_data)

# Delete a resource with primary key '1'
response = api.users.delete(1)
add_resource(name, resource_handler=None, path=None)

Add a resource handler to the api object.

Required Arguments:

name
The name of the resource. This is generally the basic name of the resource on the API. For example ‘/api/v0/users/’ would likely be called ‘users’ and will be accessible as ‘api.users’ from which additional calls can be made. For example ‘api.users.get()’.

Optional Arguments:

resource_handler
The resource handler class to use. Defaults to self._meta.resource_handler.
path
The path to the resource on the API (after the base url). Defaults to ‘/<name>/’.

Nested Resources:

It is possible to attach resources in a ‘nested’ fashion. For example passing a name of ‘my.nested.users’ would be accessible as api.my.nested.users.get().

Usage:

api.add_resource('users')
response = api.users.get()

# Or for nested resources
api.add_resource('my.nested.users', path='/users/')
response = api.my.nested.users.get()
auth(user, password, **kw)

This authentication mechanism implements HTTP Basic Authentication.

Required Arguments:

user
The API username.
password
The password of that user.
class drest.api.TastyPieAPI(*args, **kw)

This class implements an API client, specifically tailored for interfacing with TastyPie.

Optional / Meta Arguments:

auth_mech
The auth mechanism to use. One of [‘basic’, ‘api_key’]. Default: ‘api_key’.
auto_detect_resources
Boolean. Whether or not to auto detect, and add resource objects to the api. Default: True.

Authentication Mechanisms

Currently the only supported authentication mechanism are:

  • ApiKeyAuthentication
  • BasicAuthentication

Usage

Please note that the following example use ficticious resource data. What is returned, and sent to the API is unique to the API itself. Please do not copy and paste any of the following directly without modifying the request parameters per your use case.

Create the client object, and authenticate with a user/api_key pair by default:

import drest
api = drest.api.TastyPieAPI('http://localhost:8000/api/v0/')
api.auth('john.doe', '34547a497326dde80bcaf8bcee43e3d1b5f24cc9')

OR authenticate against HTTP Basic Auth:

import drest
api = drest.api.TastyPieAPI('http://localhost:8000/api/v0/',
                            auth_mech='basic')
api.auth('john.doe', 'my_password')

As drest auto-detects TastyPie resources, you can view those at:

api.resources

And access their schema:

api.users.schema

As well as make the usual calls such as:

api.users.get()
api.users.get(<pk>)
api.users.put(<pk>, data_dict)
api.users.post(data_dict)
api.users.delete(<pk>)

What about filtering? (these depend on how the API is configured):

api.users.get(params=dict(username='admin'))
api.users.get(params=dict(username__icontains='admin'))
...

See drest.api.API for more standard usage examples.

auth(*args, **kw)

Authenticate the request, determined by Meta.auth_mech. Arguments and Keyword arguments are just passed to the auth_mech function.

find_resources()

Find available resources, and add them via add_resource().

drest.exc

exception drest.exc.dRestAPIError(msg)

dRest API Errors.

exception drest.exc.dRestError(msg)

Generic dRest Errors.

exception drest.exc.dRestInterfaceError(msg)

dRest Interface Errors.

exception drest.exc.dRestRequestError(msg, response)

dRest Request Errors.

exception drest.exc.dRestResourceError(msg)

dRest Resource Errors.

drest.interface

class drest.interface.Attribute(description)

Defines an Interface attribute.

Usage:

from drest import interface

class MyInterface(interface.Interface):
    my_attribute = interface.Attribute("A description of my_attribute.")
class drest.interface.Interface

This is an abstract base class that all interface classes should subclass from.

drest.interface.validate(interface, obj, members, metas=[])

A wrapper to validate interfaces.

Required Arguments:

interface
The interface class to validate against
obj
The object to validate.
members
A list of object members that must exist.

Optional Arguments:

metas
A list of meta parameters that must exist.

drest.meta

dRest core meta functionality. Barrowed from http://slumber.in/.

class drest.meta.Meta(**kw)

Model that acts as a container class for a meta attributes for a larger class. It stuffs any kwarg it gets in it’s init as an attribute of itself.

class drest.meta.MetaMixin(*args, **kw)

Mixin that provides the Meta class support to add settings to instances of slumber objects. Meta settings cannot start with a _.

drest.request

class drest.request.IRequest

This class defines the Request Handler Interface. Classes that implement this handler must provide the methods and attributes defined below.

All implementations must provide sane ‘default’ functionality when instantiated with no arguments. Meaning, it can and should accept optional parameters that alter how it functions, but can not require any parameters.

Implementations do not subclass from interfaces.

add_header(key, value)

Add extra headers to pass along with every request.

Required Arguments:

key
The key of the header to add.
value
The value of the header to add.
add_param(key, value)

Add extra parameters to pass along with every request. These are passed with the request ‘payload’ (serialized if a serialization handler is enabled). With GET requests they are appended to the URL.

Required Arguments:

key
The key of the parameter to add.
value
The value of the parameter to add.
add_url_param(key, value)

Similar to ‘add_params’, however this function adds extra parameters to the url for every request. These are not passed with the request ‘payload’ (serialized if a serialization handler is enabled) except for GET requests.

Required Arguments:

key
The key of the parameter to add.
value
The value of the parameter to add.
handle_response(response_object)

Called after the request is made. This is a convenient place for developers to handle what happens during every request per their application needs.

Required Arguments:

response_object
The response object created by the request.
make_request(method, path, params=None, headers=None)

Make a request with the upstream API.

Required Arguments:

method
The HTTP method to request as. I.e. [‘GET’, ‘POST’, ‘PUT’, ‘DELETE’, ‘...’].
path
The of the request url after the baseurl.

Optional Arguments:

params
Dictionary of parameters to pass with the request. These will be serialized if configured to serialize.
headers
Dictionary of headers to pass to the request.
class drest.request.RequestHandler(**kw)

Generic class that handles HTTP requests. Uses the Json Serialization handler by default, but only ‘deserializes’ response content.

Optional Arguments / Meta:

debug
Boolean. Toggle debug console output. Default: False.
ignore_ssl_validation
Boolean. Whether or not to ignore ssl validation errors. Default: False
response_handler
An un-instantiated Response Handler class used to return responses to the caller. Default: drest.response.ResponseHandler.
serialization_handler
An un-instantiated Serialization Handler class used to serialize/deserialize data. Default: drest.serialization.JsonSerializationHandler.
serialize
Boolean. Whether or not to serialize data before sending requests. Default: False.
deserialize
Boolean. Whether or not to deserialize data before returning the Response object. Default: True.
trailing_slash
Boolean. Whether or not to append a trailing slash to the request url. Default: True.
timeout
The amount of seconds where a request should timeout. Default: None
add_header(key, value)

Adds a key/value to self._extra_headers, which is sent with every request.

Required Arguments:

key
The key of the parameter.
value
The value of ‘key’.
add_param(key, value)

Adds a key/value to self._extra_params, which is sent with every request.

Required Arguments:

key
The key of the parameter.
value
The value of ‘key’.
add_url_param(key, value)

Adds a key/value to self._extra_url_params, which is sent with every request (in the URL).

Required Arguments:

key
The key of the parameter.
value
The value of ‘key’.
handle_response(response_object)

A simple wrapper to handle the response. By default raises exc.dRestRequestError if the response code is within 400-499, or 500. Must return the original, or modified, response object.

Required Arguments:

response_object
The response object created by the request.
make_request(method, url, params=None, headers=None)

Make a call to a resource based on path, and parameters.

Required Arguments:

method
One of HEAD, GET, POST, PUT, PATCH, DELETE, etc.
url
The full url of the request (without any parameters). Any params (with GET method) and self.extra_url_params will be added to this url.

Optional Arguments:

params
Dictionary of additional (one-time) keyword arguments for the request.
headers
Dictionary of additional (one-time) headers of the request.
set_auth_credentials(user, password)

Set the authentication user and password that will be used for HTTP Basic and Digest Authentication.

Required Arguments:

user
The authentication username.
password
That user’s password.
class drest.request.TastyPieRequestHandler(**kw)

This class implements the IRequest interface, specifically tailored for interfacing with TastyPie.

See drest.request.RequestHandler for Meta options and usage.

drest.request.validate(obj)

Validates a handler implementation against the IRequest interface.

drest.response

class drest.response.IResponse

This class defines the Response Handler Interface. Classes that implement this handler must provide the methods and attributes defined below.

All implementations must provide sane ‘default’ functionality when instantiated with no arguments. Meaning, it can and should accept optional parameters that alter how it functions, but can not require any parameters.

Implementations do not subclass from interfaces.

drest.response.validate(obj)

Validates a handler implementation against the IResponse interface.

drest.resource

class drest.resource.IResource

This class defines the Resource Handler Interface. Classes that implement this handler must provide the methods and attributes defined below.

All implementations must provide sane ‘default’ functionality when instantiated with no arguments. Meaning, it can and should accept optional parameters that alter how it functions, but can not require any parameters.

Implementations do not subclass from interfaces.

class drest.resource.RESTResourceHandler(api_obj, name, path, **kw)

This class implements the IResource interface, specifically for interacting with REST-like resources. It provides convenient functions that wrap around the typical GET, PUT, POST, DELETE actions.

Optional Arguments / Meta:

api_obj
The api (parent) object that this resource is being attached to.
name
The name of the resource on the API.
path
The path to the resource (after api.baseurl).

Usage:

import drest

class MyAPI(drest.api.API):
    class Meta:
        resource_handler = drest.resource.RESTResourceHandler
...
create(params=None)

A synonym for self.post().

delete(resource_id, params=None)

Delete resource record.

Required Arguments:

resource_id
The resource id

Optional Arguments:

params
Some resource might allow additional parameters. For example, the user resource has a ‘rdikwid’ (really delete I know what I’m doing) option which causes a user to really be deleted (normally deletion only sets the status to ‘Deleted’).
get(resource_id=None, params=None)

Get all records for a resource, or a single resource record.

Optional Arguments:

resource_id
The resource id (may also be a label in some environments).
params
Additional request parameters to pass along.
patch(resource_id, params=None)

Update only specific items of an existing resource.

Required Arguments:

resource_id
The id of the resource to update.
params
A dictionary of parameters (different for every resource).
post(params=None)

Create a new resource.

Required Arguments:

params
A dictionary of parameters (different for every resource).
put(resource_id, params=None)

Update an existing resource.

Required Arguments:

resource_id
The id of the resource to update.
params
A dictionary of parameters (different for every resource).
update(resource_id, params=None)

A synonym for self.put().

class drest.resource.ResourceHandler(api_obj, name, path, **kw)

This class acts as a base class that other resource handler should subclass from.

filter(params)

Give the ability to alter params before sending the request.

Required Arguments:

params
The list of params that will be passed to the endpoint.
class drest.resource.TastyPieResourceHandler(api_obj, name, path, **kw)

This class implements the IResource interface, specifically tailored for interfacing with TastyPie.

class Meta

Handler meta-data (can be passed as keyword arguments to the parent class).

collection_name = 'objects'

The name of the collection. Default: objects

request

The request handler used to make requests. Default: TastyPieRequestHandler.

alias of TastyPieRequestHandler

TastyPieResourceHandler.get_by_uri(resource_uri, params=None)

A wrapper around self.get() that accepts a TastyPie ‘resource_uri’ rather than a ‘pk’ (primary key).

Parameters:
  • resource_uri – The resource URI to GET.
  • params – Any additional keyword arguments are passed as extra request parameters.

Usage:

import drest
api = drest.api.TastyPieAPI('http://localhost:8000/api/v0/')
api.auth(user='john.doe',
         api_key='34547a497326dde80bcaf8bcee43e3d1b5f24cc9')
response = api.users.get_by_uri('/api/v1/users/234/')
TastyPieResourceHandler.patch_list(create_objects=[], delete_objects=[])

Tastypie resources have a patch_list method that allows you to create and delete bulk collections of objects. This uses HTTP PATCH.

Parameters:
  • create_objects – List of objects to create in dict form.
  • delete_objects – List of objects to delete in dict form.
TastyPieResourceHandler.schema

Returns the resources schema.

drest.resource.validate(obj)

Validates a handler implementation against the IResource interface.

drest.serialization

class drest.serialization.ISerialization

This class defines the Serialization Handler Interface. Classes that implement this handler must provide the methods and attributes defined below.

All implementations must provide sane ‘default’ functionality when instantiated with no arguments. Meaning, it can and should accept optional parameters that alter how it functions, but can not require any parameters.

Implementations do not subclass from interfaces.

deserialize()

Load a serialized string and return a dictionary of key/value pairs.

Required Arguments:

serialized_data
A string of serialzed data.

Returns: dict

get_headers()

Return a dictionary of additional headers to include in requests.

serialize()

Dump a dictionary of values from a serialized string.

Required Arguments:

data_dict
A data dictionary to serialize.

Returns: string

class drest.serialization.JsonSerializationHandler(**kw)

This handler implements the ISerialization interface using the standard json library.

class drest.serialization.SerializationHandler(**kw)

Generic Serialization Handler. Should be used to subclass from.

drest.serialization.validate(obj)

Validates a handler implementation against the ISerialize interface.

Table Of Contents

Previous topic

Contributors

Next topic

Usage Documentation

This Page