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: |
|
---|
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(1, 2)
3
Models are stored in the _models property, but accessed through a proxy like so:
>>> mathy.models.Number
<class '__main__.Number'>
Simple way to run the API in development. Uses Werkzeug’s werkzeug.serving.run_simple() internally. See Serving for more options.
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")
{"name": "Earth"}
Parameters: | url – The API spec url, including /spec.json |
---|---|
Return type: | API instance |
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 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
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.
Subclasses of this class are fed into the model() decorator to attach models to an API.
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.
A list of methods that this model supports. Possible values are ‘get_by_id’, ‘create’, ‘update’, ‘delete’ and ‘get_list’.
A list of properties for the get_list() handler. They are defined in the same way as properties above.
A list of properties that can be returned along with the usual response for get_list(). These can be used for things like pagination.
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.
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.
Parameters: | id – |
---|---|
Returns: | Model representation |
Raises cosmic.exceptions.NotFound: | |
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. |
Parameters: | validated_patch – The model patch. |
---|---|
Returns: | A tuple of model id and model representation. |
Parameters: |
|
---|---|
Returns: | The model representation after patch has been applied. |
Raises cosmic.exceptions.NotFound: | |
Parameters: | id – |
---|---|
Raises cosmic.exceptions.NotFound: | |
Creates a lazy reference to a model, useful for defining links.
@familytree.model
class Person(BaseModel):
links = [
optional_link('mother', M('familytree.Person')),
optional_link('father', M('familytree.Person')),
]
Bases: teleport.BasicWrapper
A Teleport type representing an API model. Its JSON form is a dotted string, the native form is the model object:
>>> Model.to_json(places.models.City)
"places.City"
Note that when deserializing this type, the returned value isn’t exactly a model object, but a M object, a proxy that behaves identically to the model. The reason for this is that sometimes a reference to the model is needed before the model exists, for example, when defining links.
Bases: 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(places.models.City).to_json("3")
{"href": "/City/3"}
>>> Link(places.models.City).from_json({"href": "/City/3"})
"3"
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.
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.
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)}
Request: |
|
||||||||
---|---|---|---|---|---|---|---|---|---|
Response: |
|
Request: |
|
||||||
---|---|---|---|---|---|---|---|
Response: |
|
Request: |
|
||||||||
---|---|---|---|---|---|---|---|---|---|
Response: |
|
Request: |
|
||||||||
---|---|---|---|---|---|---|---|---|---|
Response: |
|
Request: |
|
||||
---|---|---|---|---|---|
Response: |
|
Request: |
|
||||||
---|---|---|---|---|---|---|---|
Response: |
|
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.
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.
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.
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().