Reference

APIs

class cosmic.api.API(name, homepage=None)

An instance of this class represents a Cosmic API, whether it’s your own API being served or a third-party API being consumed. In the former case, the API object is instantiated by the constructor and is bound to a database ORM and other user-defined functions. In the latter case, it is instantiated by the API.load() method and these functions are replaced by automatically generated HTTP calls.

One of the primary goals of Cosmic is to make local and remote APIs behave as similarly as possible.

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
static load(url, verify=True)

Given a URL to a Cosmic API, fetch the API spec and build an API client:

>>> planetarium = API.load("http://localhost:5000/spec.json") 
>>> planetarium.models.Sphere.get_by_id("0") 
<cosmic.models.Sphere object at 0x8f9ebcc>
Parameters:url – The API spec url, including /spec.json
Return type:API instance
get_flask_app()

Returns a Flask application for the API.

run(api_key=None, registry_url_override=None, **kwargs)

Runs the API as a Flask app. All keyword arguments are channelled into Flask.run().

action(accepts=None, returns=None)

A decorator for creating actions out of functions and registering them with the 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.

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.

>>> 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.

>>> w = dictionary.models.Word.from_json({"text": "dog"})
>>> w.text
u'dog'
cosmic.api.API.actions

In the cosmic.api.API object, the actions are stored in an OrderedDict in a private _actions property:

>>> mathy._actions
OrderedDict([(u'add', <cosmic.actions.Action object at 0x9ca18ec>)])

The standard way of accessing them, however, is through a proxy property actions. Like so:

>>> mathy.actions.add
<cosmic.actions.Action object at 0x9ca18ec>
cosmic.api.API.models

Models are stored in the _models property, but accessed through a proxy like so:

>>> mathy.models.Number
<class '__main__.Number'>
class cosmic.models.BaseModel(**kwargs)

A data type definition attached to an API.

HTTP Endpoints

class cosmic.http.SpecEndpoint(url, api)
Request:
Method:GET
URL:/spec.json
Response:
Code:200
Body:The API spec as a JSON-encoded string.
ContentType:application/json
class cosmic.http.ActionEndpoint(action, name)
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(model_cls)
Request:
Method:GET
URL:/models/<model>/<id> where model is the model name.
Response:
Code:200 or 404 if object is not found.
Body:The object as a JSON-encoded string or empty if the object with the provided id does not exist.
ContentType:application/json if body is not empty.
class cosmic.http.CreateEndpoint(model_cls)
Request:
Method:POST
URL:/models/<model> where model is the model name.
Body:New model representation 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(model_cls)
Request:
Method:PUT
URL:/models/<model>/<id> where model is the model name.
Body:New model representation as a JSON-encoded string.
ContentType:application/json
Response:
Code:200
Body:New model representation as a JSON-encoded string.
ContentType:application/json
class cosmic.http.DeleteEndpoint(model_cls)
Request:
Method:DELETE
URL:/models/<model>/<id> where model is the model name.
Response:
Code:204
Body:Empty.
class cosmic.http.GetListEndpoint(model_cls)
Request:
Method:GET
URL:/models/<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>*]
    }
}

In the above, self is the request URL, model is the name of the model that was requested and repr is a JSON representation of an instance of that model which was matched by the query.

Exceptions

class cosmic.exceptions.ModelNotFound
class cosmic.exceptions.SpecError

Tools and Helpers

class cosmic.tools.GetterNamespace(get_item, get_all=None)

An object that exposes an arbitrary mapping as a namespace, letting its values be accessible as attributes.

Parameters:
  • get_item – a function that takes a string and returns an item
  • get_all – a function that returns a list of all keys in the namespace

Example:

>>> d = {"a": 1, "b": 2}
>>> n = GetterNamespace(d.__getitem__, d.keys)
>>> n.a
1
>>> n.__all__
[u'a', u'b']
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, optional)

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.json_to_string(box)
cosmic.tools.validate_underscore_identifier(id)
cosmic.tools.is_string_type(serializer)
class cosmic.types.URLParams(param)

Bases: 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)}