dRest core API connection library.
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 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()
This authentication mechanism implements HTTP Basic Authentication.
Required Arguments:
- user
- The API username.
- password
- The password of that user.
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.
Authenticate the request, determined by Meta.auth_mech. Arguments and Keyword arguments are just passed to the auth_mech function.
Find available resources, and add them via add_resource().
dRest API Errors.
Generic dRest Errors.
dRest Interface Errors.
dRest Request Errors.
dRest Resource Errors.
Defines an Interface attribute.
Usage:
from drest import interface
class MyInterface(interface.Interface):
my_attribute = interface.Attribute("A description of my_attribute.")
This is an abstract base class that all interface classes should subclass from.
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 core meta functionality. Barrowed from http://slumber.in/.
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.
Mixin that provides the Meta class support to add settings to instances of slumber objects. Meta settings cannot start with a _.
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 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 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.
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.
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 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.
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
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’.
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’.
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’.
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 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 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.
This class implements the IRequest interface, specifically tailored for interfacing with TastyPie.
See drest.request.RequestHandler for Meta options and usage.
Validates a handler implementation against the IRequest interface.
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.
Validates a handler implementation against the IResponse interface.
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.
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
...
A synonym for self.post().
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 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.
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).
Create a new resource.
Required Arguments:
- params
- A dictionary of parameters (different for every resource).
Update an existing resource.
Required Arguments:
- resource_id
- The id of the resource to update.
- params
- A dictionary of parameters (different for every resource).
A synonym for self.put().
This class acts as a base class that other resource handler should subclass from.
Give the ability to alter params before sending the request.
Required Arguments:
- params
- The list of params that will be passed to the endpoint.
This class implements the IResource interface, specifically tailored for interfacing with TastyPie.
Handler meta-data (can be passed as keyword arguments to the parent class).
The name of the collection. Default: objects
The request handler used to make requests. Default: TastyPieRequestHandler.
alias of TastyPieRequestHandler
A wrapper around self.get() that accepts a TastyPie ‘resource_uri’ rather than a ‘pk’ (primary key).
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/')
Tastypie resources have a patch_list method that allows you to create and delete bulk collections of objects. This uses HTTP PATCH.
Parameters: |
|
---|
Returns the resources schema.
Validates a handler implementation against the IResource interface.
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.
Load a serialized string and return a dictionary of key/value pairs.
Required Arguments:
- serialized_data
- A string of serialzed data.
Returns: dict
Return a dictionary of additional headers to include in requests.
Dump a dictionary of values from a serialized string.
Required Arguments:
- data_dict
- A data dictionary to serialize.
Returns: string
This handler implements the ISerialization interface using the standard json library.
Generic Serialization Handler. Should be used to subclass from.
Validates a handler implementation against the ISerialize interface.