Reference

APIs

class cosmic.api.BaseAPI(spec)

This class represents the common interface for the server-side and the client-side API objects. It contains the API spec as well as a collection of functions for each API endpoint. On the server side, these functions are user-defined. On the client side, they are created automatically to execute HTTP calls.

spec

The API spec, in its native form (see APISpec)

actions

This stores the action functions as properties of a plain object:

>>> spelling.actions.correct('simpl')
"simple"
models

Through this property you can access the model functions get_by_id(), get_list(), create(), update() and delete(). They are accessed as attributes:

>>> quotes.models.Quote.get_by_id("1")
{"text": "Know thyself.", "author": "Socrates"}
class cosmic.api.API(name, homepage=None)

Bases: cosmic.api.BaseAPI

Parameters:
  • name – The API name is required, and should be unique
  • homepage – If you like, the API spec may include a link to your homepage
run(port=5000, debug=False, **kwargs)

Simple way to run the API in development. The debug parameter gets passed into a Server instance, all other parameters - into Werkzeug’s run_simple(). For more serving options, see Serving.

action(accepts=None, returns=None)

A decorator for registering actions with API.

The accepts parameter is a schema that describes the input of the function, returns is a schema that describes the output of the function. The name of the function becomes the name of the action and the docstring serves as the action’s documentation.

Once registered, an action will become accessible as an attribute of the actions object.

>>> random = API("random")
>>> @random.action(returns=Integer)
... def generate():
...     "Random enough"
...     return 9
>>> random.actions.generate()
9
model(model_cls)

A decorator for registering a model with an API. The name of the model class is used as the name of the resulting model. A subclass of BaseModel is used to supply the necessary metadata and functions to the API.

>>> dictionary = API("dictionary")
>>> @dictionary.model
... class Word(BaseModel):
...    properties = [
...        required("text", String)
...    ]
...

Once registered, a model will become accessible as an attribute of the models object.

Models

class cosmic.models.BaseModel

Subclasses of this class are fed into the model() decorator to attach models to an API. The API object doesn’t care about how you implement this class, it just copies the necessary properties and leaves the class alone.

properties

A list of properties which, along with links below, will be used for the model’s representation and patch, defined in the same way Teleport Struct fields are defined:

properties = [
    required('name', String),
    optional('age', Integer),
]

See Representation and Patch.

Similar to properties, but encodes a relationship between this model and another. In database terms this would be a foreign key. Use required_link() and optional_link() to specify them.

methods

A list of methods that this model supports. Possible values are 'get_by_id', 'create', 'update', 'delete' and 'get_list'.

query_fields

A list of properties for the get_list() handler. They are defined in the same way as properties above.

list_metadata

A list of properties that can be returned along with the usual response for get_list(). These can be used for things like pagination.

classmethod get_by_id(id)
Parameters:id
Returns:Model representation
Raises cosmic.exceptions.NotFound:
 
classmethod get_list(**kwargs)
Parameters:kwargs – Defined by query_fields
Returns:If model does not define list_metadata, returns a list of tuples of models ids and representations. Otherwise returns a tuple where the first element is the above list, and the second is a dict as specified by list_metadata.
classmethod create(**valid_patch)
Parameters:validated_patch – The model patch.
Returns:A tuple of model id and model representation.
classmethod update(id, **valid_patch)
Parameters:
  • id
  • validated_patch
Returns:

The model representation after patch has been applied.

Raises cosmic.exceptions.NotFound:
 

classmethod delete(id)
Parameters:id
Raises cosmic.exceptions.NotFound:
 
classmethod validate_patch(patch)
Parameters:patch – The model patch
Raises cosmic.exceptions.ValidationError:
 

Run before any create() or update() call to validate the patch. All fields are made optional for the patch, so this method is a chance to ensure that the expected values were indeed passed in.

Types

class cosmic.types.Model(full_name)

Bases: cosmic.legacy_teleport.BasicWrapper

A Teleport type representing an API model. Its JSON form is a dotted string, the native form is an instance of this class.

Bases: cosmic.legacy_teleport.ParametrizedWrapper

A Teleport type representing a link to an object. Its native form is simply a resource id. It takes a Model as parameter:

>>> Link(Model('places.City')).to_json("3")
"/City/3"
>>> Link(Model('places.City')).from_json("/City/3")
"3"
class cosmic.types.Representation(param)

Bases: cosmic.types.BaseRepresentation

A Teleport type representing a model representation. Its native form is a dict as defined by properties and links. Links are represented by plain string ids.

It takes a Model as parameter.

class cosmic.types.Patch(param)

Bases: cosmic.types.BaseRepresentation

A Teleport type representing a model patch. Its native form is similar to that of Representation, except all fields are optional. To make a field required, use validate_patch().

It takes a Model as parameter.

class cosmic.types.URLParams(param)

Bases: cosmic.legacy_teleport.ParametrizedWrapper

A Teleport type that behaves mostly like the Struct type, except it serializes the data into a query string:

>>> p = URLParams([
...     required("foo", Boolean),
...     required("bar", Integer)
... ])
...
>>> p.to_json({"foo": True, "bar": 3})
'foo=true&bar=3'
>>> p.from_json("foo=false&bar=0")
{'foo': False, 'bar': 0}

A string parameter or a parameter whose type is a wrapper over string will not require quotes:

>>> from cosmic.types import DateTime
>>> schema = URLParams([
...     required('birthday', DateTime)
... ])
>>> schema.from_json('birthday=1991-08-12T00%3A00%3A00')
{'birthday': datetime.datetime(1991, 8, 12, 0, 0)}
class cosmic.types.APISpec

Bases: cosmic.legacy_teleport.BasicWrapper

The teleport type that encapsulates all metadata associated with an API. This type is used to prepare the output for the /spec.json endpoint, as well as to deserialize it when building an API client.

What’s inside? Well, if you insist:

Struct([
    required("name", String),
    optional("homepage", String),
    required("actions", OrderedMap(Struct([
        optional("accepts", Schema),
        optional("returns", Schema),
        optional("doc", String)
    ]))),
    required("models", OrderedMap(Struct([
        required("properties", OrderedMap(Struct([
            required("schema", Schema),
            required("required", Boolean),
            optional("doc", String)
        ]))),
        required("links", OrderedMap(Struct([
            required("model", Model),
            required("required", Boolean),
            optional("doc", String)
        ]))),
        required("query_fields", OrderedMap(Struct([
            required("schema", Schema),
            required("required", Boolean),
            optional("doc", String)
        ]))),
        required("methods", Struct([
            required("get_by_id", Boolean),
            required("get_list", Boolean),
            required("create", Boolean),
            required("update", Boolean),
            required("delete", Boolean),
            ])),
        required("list_metadata", OrderedMap(Struct([
            required("schema", Schema),
            required("required", Boolean),
            optional("doc", String)
        ])))
    ])))
])

Globals

class cosmic.globals.ThreadLocalDict

A dictionary-like object that stores its values inside a thread-local. Useful for storing global state safely. Instantiate this once and import it everywhere to read and write global values (e.g. the currently authenticated user or database connections).

cosmic.globals.thread_local(*args, **kwds)

A context manager for safely creating and deleting the thread-local necessary for ThreadLocalDict.

g = ThreadLocalDict()

with thread_local():
    # g is only accessible within this context
    g['foo'] = 1
cosmic.globals.thread_local_middleware(app)

To put your entire application in a thread_local() context, you must put it at the entry point of your application’s thread. In the case of a threading WSGI server, this is achieved by wrapping your WSGI application in this middleware.

Note that just like the rest of this module, this middleware isn’t tied to Cosmic in any way. For example, you can use it to enable a ThreadLocalDict inside a Django application:

from django.core.wsgi import get_wsgi_application
from cosmic.globals import thread_local_middleware

application = thread_local_middleware(get_wsgi_application())
Parameters:app – WSGI application
Returns:WSGI application

HTTP Endpoints

class cosmic.http.ActionEndpoint(api_spec, action_name, func=None)
Request:
Method:POST
URL:/actions/<action> where action is the action name.
Body:The action parameters as a JSON-encoded string or empty if the action expects no parameters.
ContentType:application/json if body is not empty.
Response:
Code:200 or 204 if body is empty.
Body:The return value as a JSON-encoded string or empty if the actions has no return value.
ContentType:application/json if body is not empty.
class cosmic.http.GetByIdEndpoint(api_spec, model_name, func=None)
Request:
Method:GET
URL:/<model>/<id> where model is the model name.
Response:
Code:200 or 404 if object is not found.
Body:The object representation as a JSON-encoded string.
ContentType:application/json if body is not empty.
class cosmic.http.CreateEndpoint(api_spec, model_name, func=None)
Request:
Method:POST
URL:/<model> where model is the model name.
Body:Corresponding model patch as a JSON-encoded string.
ContentType:application/json
Response:
Code:201
Body:New model representation as a JSON-encoded string.
ContentType:application/json
class cosmic.http.UpdateEndpoint(api_spec, model_name, func=None)
Request:
Method:PUT
URL:/<model>/<id> where model is the model name.
Body:A corresponding model patch as a JSON-encoded string.
ContentType:application/json
Response:
Code:200 or 404 if object is not found.
Body:New model representation as a JSON-encoded string.
ContentType:application/json
class cosmic.http.DeleteEndpoint(api_spec, model_name, func=None)
Request:
Method:DELETE
URL:/<model>/<id> where model is the model name.
Response:
Code:204 or 404 if object is not found.
Body:Empty.
class cosmic.http.GetListEndpoint(api_spec, model_name, func=None)
Request:
Method:GET
URL:/<model> where model is the model name.
Query:Query parameters serialized by the model’s query_schema
Response:
Code:

200

ContentType:

application/json

Body:

The syntax follows JSON HAL specification.

{
    "_links": {
        "self": {"href": <self>}
    },
    "_embedded": {
        <model>: [<repr>*]
    },
    <metadata>*
}

In the above, self is the request URL, model is the name of the model that was requested and repr is a JSON-encoded representation of an object matched by the query. Metadata is defined according to list_metadata.

Exceptions

class cosmic.exceptions.SpecError
class cosmic.exceptions.NotFound

Expected to be raised by get_by_id(), update() and delete() when the resource is not found. Cosmic will convert it to a 404 response on the server, and on the client, it will interpret this response by reraising the exception.

class cosmic.exceptions.HTTPError(code, message)
class cosmic.exceptions.RemoteHTTPError(code, message)
class cosmic.exceptions.ThreadLocalMissing

Raised when trying to access a value inside cosmic.globals.ThreadLocalDict without creating a thread-local to store it on. See cosmic.globals.thread_local() and cosmic.globals.thread_local_middleware().

Tools and Helpers

cosmic.tools.get_args(func)

Given a function, returns a tuple (required, optional), tuples of non-keyword and keyword arguments respectively. If a function contains splats (* or **), a SpecError will be raised.

cosmic.tools.args_to_datum(*args, **kwargs)

Takes arbitrary args and kwargs and packs them into a dict if there are more than one. Returns None if there are no arguments. Must be called with either a single argument or multiple keyword arguments.

cosmic.tools.assert_is_compatible(schema, required_args, optional_args)

Raises a SpecError if function argument spec (as returned by get_args()) is incompatible with the given schema. By incompatible, it is meant that there exists such a piece of data that is valid according to the schema, but that could not be applied to the function by apply_to_func().

cosmic.tools.deserialize_json(schema, datum)
cosmic.tools.serialize_json(schema, datum)
cosmic.tools.string_to_json(s)
cosmic.tools.validate_underscore_identifier(id)
cosmic.tools.is_string_type(serializer)