Security News
Weekly Downloads Now Available in npm Package Search Results
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.
Cosmicray is a simple and high level http client API development framework. It provides the basic building blocks for defining enpoints, handling a request response and automatically converting the result into to Models.
Motivation:
.. warning::
Cosmicray is under development
.. code::
$ pip install cosmicray
Create App
.. code:: python
>>> from cosmicray import Cosmicray
>>> api = Cosmicray('myapp', domain='http://mydomain.com')
Define routes and response handlers
Using the app we created, we can now add routes for it and define a response handler for each one. The response handler is simply a regular function that accepts a single argument of type requests.Response
and returns the processed result.
.. code:: python
>>> @api.route('/v1/dogs/{id}', ['GET', 'POST', 'PUT', 'DELETE'])
>>> def dogs(response):
... return response.json()
The decorator api.route
creates an instance of cosmicray.Route
named dogs
and stores the given function internally as the response handler.
Instances of cosmicray.Route
are callable and accept parameters:
model_cls
: Optional: Class that implements _make(cls, response)
classmethod.
\*\*kwargs
: Keyword arguments.
urlargs
: Mapping for url formatting argumentsheaders
: Mapping for headersparams
: Mapping for query parametersdata
, json
, files
: Request bodyauthenticator
: Authenticator callbackWhen and instance of cosmicray.Route
is called, it returns a Request
object and with this you can:
get()
, post()
, put()
, delete()
)params
, headers
, etc.) with settersRoute
How to make requests
.. code:: python
>>> dogs().get()
>>> dogs(urlargs={id: 12345}).get()
>>> dogs(json={'name': 'Manu'}).post()
>>> dogs(urlargs={'id': 12345}, json={'age': 4}).put()
>>> dogs(urlargs={'id': 12345}).delete()
To specify request parameters
.. code:: python
>>> dogs(params={'breed': 'husky'},
... headers={'Content-Type': 'application/json'}).get()
Authenticating requests
Often you'll need to authenticate requests to access private resource and Cosmicray has a built-in mechanism to perform this step.
.. code:: python
>>> def authenticator(request):
... if not request.is_request_for(login):
... auth = login(json={'username': 'me', 'password': 'mysecret'}).post()
... return request.set_headers({'X-AUTH-TOKEN': auth['token']})
... return request
...
>>> @api.route('/oauth', ['POST'])
... def login(response):
... """Get an auth token for the given credentials"""
... return response.json()
...
>>> @api.route('/private/resource', ['GET'])
... def private_resource(response):
... """Must be authenticated to access this"""
... return response.json()
...
>>> api.configure(authenticator=authenticator)
>>> # Now the private resourse will be automatically updated to include auth headers
>>> private_resource.get()
Basics
- Cosmicray ships with a built-in Model class
- This base class is bound to a specific route handler and defines all the fields that would get mapped to a response or be part as the payload for `post` and `put` requests
- It automatically uses its defined fields as url parameters and as request body
- Provides functions to make http calls (ex: `get`, `create`, `update`, `delete`)
- You can override default behavior, such as create/update paylods
.. code:: python
>>> from cosmicray.model import Model
>>> class Dog(Model):
... __route__ = dogs
... __slots__ = [
... 'id',
... 'name',
... 'breed',
... 'age'
... ]
>>> manu = Dog(name='Manu', age=4).create()
>>> manu.breed = 'Husky'
>>> manu.update()
>>> manu.delete()
>>> manu = Dog(id=12345).get()
>>> alldogs = Dog().get()
Relationships with other models/routes
.. code:: python
>>> from cosmicray.model import relationhip, Model, ModelParam
>>> class Cat(cosmicray.model.Model):
... __route__ = cats
... __slots__ = [
... 'id',
... 'name',
... 'age'
... ]
... friends = relationhip('Friend', urlargs={'id': ModelParam('id')})
If you don't want to use cosmicray.Model
as your base, you can define your own OR
even use just use collections.namedtuple
as the model.
.. code:: python
>>> class MyModel(object):
... @classmethod
... def _make(cls, response):
... obj = cls()
... ... do stuff with the response
... return obj
FAQs
Develop a client for your HTTP API and document its quirks and features
We found that cosmicray demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.
Security News
A Stanford study reveals 9.5% of engineers contribute almost nothing, costing tech $90B annually, with remote work fueling the rise of "ghost engineers."
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.