All Projects → qvantel → Jsonapi Client

qvantel / Jsonapi Client

Licence: other
JSON API (jsonapi.org) client for Python

Programming Languages

python
139335 projects - #7 most used programming language

Projects that are alternatives of or similar to Jsonapi Client

jsonapi-serializable
Conveniently build and efficiently render JSON API resources.
Stars: ✭ 43 (-31.75%)
Mutual labels:  json-api, jsonapi
json-api-serializer
Node.js/browser framework agnostic JSON API (http://jsonapi.org/) serializer.
Stars: ✭ 141 (+123.81%)
Mutual labels:  json-api, jsonapi
fire
An idiomatic micro-framework for building Ember.js compatible APIs with Go.
Stars: ✭ 56 (-11.11%)
Mutual labels:  json-api, jsonapi
Jsonapi Rails
Rails gem for fast jsonapi-compliant APIs.
Stars: ✭ 242 (+284.13%)
Mutual labels:  json-api, jsonapi
Reservoir
A back end for your front end: a content repository. Powered by Drupal 8, JSON API and OAuth2.
Stars: ✭ 262 (+315.87%)
Mutual labels:  json-api, jsonapi
php-serializer
Serialize PHP variables, including objects, in any format. Support to unserialize it too.
Stars: ✭ 47 (-25.4%)
Mutual labels:  json-api, jsonapi
json-server
Create a dummy REST API from a json file with zero coding in seconds
Stars: ✭ 34 (-46.03%)
Mutual labels:  json-api, jsonapi
Json Api Client
A PHP package for mapping remote {json:api} resources to Eloquent like models and collections.
Stars: ✭ 159 (+152.38%)
Mutual labels:  json-api, client
Vox
Swift JSON:API client framework
Stars: ✭ 47 (-25.4%)
Mutual labels:  json-api, jsonapi
jsonapi-deserializable
Conveniently deserialize JSON API payloads into custom hashes.
Stars: ✭ 23 (-63.49%)
Mutual labels:  json-api, jsonapi
Jsonapi Rb
Efficiently produce and consume JSON API documents.
Stars: ✭ 219 (+247.62%)
Mutual labels:  json-api, jsonapi
Redux Json Api
Redux actions, action creators and reducers to make life with JSON APIs a breeze.
Stars: ✭ 374 (+493.65%)
Mutual labels:  json-api, jsonapi
Jsonapi Utils
Build JSON API-compliant APIs on Rails with no (or less) learning curve.
Stars: ✭ 191 (+203.17%)
Mutual labels:  json-api, jsonapi
Json Api Dart
JSON:API client for Dart/Flutter
Stars: ✭ 53 (-15.87%)
Mutual labels:  json-api, jsonapi
Json Api
Implementation of JSON API in PHP 7
Stars: ✭ 171 (+171.43%)
Mutual labels:  json-api, jsonapi
FSharp.JsonApi
Use F# to create and consume flexible, strongly typed web APIs following the JSON:API specification
Stars: ✭ 20 (-68.25%)
Mutual labels:  json-api, jsonapi
Yang
The efficient and elegant, PSR-7 compliant JSON:API 1.1 client library for PHP
Stars: ✭ 148 (+134.92%)
Mutual labels:  json-api, client
Coloquent
Javascript/Typescript library mapping objects and their interrelations to JSON API, with a clean, fluent ActiveRecord-like (e.g. similar to Laravel's Eloquent) syntax for creating, retrieving, updating and deleting model objects.
Stars: ✭ 149 (+136.51%)
Mutual labels:  json-api, jsonapi
laravel5-jsonapi-dingo
Laravel5 JSONAPI and Dingo together to build APIs fast
Stars: ✭ 29 (-53.97%)
Mutual labels:  json-api, jsonapi
Laravel5 Jsonapi
Laravel 5 JSON API Transformer Package
Stars: ✭ 313 (+396.83%)
Mutual labels:  json-api, jsonapi

.. image:: https://travis-ci.org/qvantel/jsonapi-client.svg?branch=master :target: https://travis-ci.org/qvantel/jsonapi-client

.. image:: https://coveralls.io/repos/github/qvantel/jsonapi-client/badge.svg :target: https://coveralls.io/github/qvantel/jsonapi-client

.. image:: https://img.shields.io/pypi/v/jsonapi-client.svg :target: https://pypi.python.org/pypi/jsonapi-client

.. image:: https://img.shields.io/pypi/pyversions/jsonapi-client.svg :target: https://pypi.python.org/pypi/jsonapi-client

.. image:: https://img.shields.io/badge/licence-BSD%203--clause-blue.svg :target: https://github.com/qvantel/jsonapi-client/blob/master/LICENSE.txt

========================== JSON API client for Python

Introduction

Package repository: https://github.com/qvantel/jsonapi-client

This Python (3.6+) library provides easy-to-use, pythonic, ORM-like access to JSON API ( http://jsonapi.org )

  • Optional asyncio implementation
  • Optional model schema definition and validation (=> easy reads even without schema)
  • Resource caching within session

Installation

From Pypi::

pip install jsonapi-client

Or from sources::

./setup.py install

Usage

Client session

.. code-block:: python

from jsonapi_client import Session, Filter, ResourceTuple

s = Session('http://localhost:8080/')

To start session in async mode

s = Session('http://localhost:8080/', enable_async=True)

You can also pass extra arguments that are passed directly to requests or aiohttp methods,

such as authentication object

s = Session('http://localhost:8080/', request_kwargs=dict(auth=HTTPBasicAuth('user', 'password'))

You can also use Session as a context manager. Changes are committed in the end

and session is closed.

with Session(...) as s: your code

Or with enable_async=True

async with Session(..., enable_async=True): your code

If you are not using context manager, you need to close session manually

s.close()

Again, don't forget to await in the AsyncIO mode

await s.close()

Fetching documents

documents = s.get('resource_type')

Or if you want only 1, then

documents = s.get('resource_type', 'id_of_document')

AsyncIO the same but remember to await:

documents = await s.get('resource_type')

Filtering and including

.. code-block:: python

You need first to specify your filter instance.

- filtering with two criteria (and)

filter = Filter(attribute='something', attribute2='something_else')

- filtering some-dict.some-attr == 'something'

filter = Filter(some_dict__some_attr='something'))

Same thing goes for including.

- including two fields

include = Inclusion('related_field', 'other_related_field')

Custom syntax for request parameters.

If you have different URL schema for filtering or other GET parameters,

you can implement your own Modifier class (derive it from Modifier and

reimplement appended_query).

modifier = Modifier('filter[post]=1&filter[author]=2')

All above classes subclass Modifier and can be added to concatenate

parameters

modifier_sum = filter + include + modifier

Now fetch your document

filtered = s.get('resource_type', modifier_sum) # AsyncIO with await

To access resources included in document:

r1 = document.resources[0] # first ResourceObject of document. r2 = document.resource # if there is only 1 resource we can use this

Pagination

.. code-block:: python

Pagination links can be accessed via Document object.

next_doc = document.links.next.fetch()

AsyncIO

next_doc = await document.links.next.fetch()

Iteration through results (uses pagination):

for r in s.iterate('resource_type'): print(r)

AsyncIO:

async for r in s.iterate('resource_type'): print(r)

Resource attribute and relationship access

.. code-block:: python

- attribute access

attr1 = r1.some_attr nested_attr = r1.some_dict.some_attr

Attributes can always also be accessed via getitem:

nested_attr = r1['some-dict']['some-attr']

If there is namespace collision, you can also access attributes via .fields proxy

(both attributes and relationships)

attr2 = r1.fields.some_attr

- relationship access.

* Sync, this gives directly ResourceObject

rel = r1.some_relation attr3 = r1.some_relation.some_attr # Relationship attribute can be accessed directly

* AsyncIO, this gives Relationship object instead because we anyway need to

call asynchronous fetch function.

rel = r1.some_relation

To access ResourceObject you need to first fetch content

await r1.some_relation.fetch()

and then you can access associated resourceobject

res = r1.some_relation.resource attr3 = res.some_attr # Attribute access through ResourceObject

If you need to access relatinoship object itself (with sync API), you can do it via

.relationships proxy. For example, if you are interested in links or metadata

provided within relationship, or intend to manipulate relationship.

rel_obj = r1.relationships.relation_name

Resource updating

.. code-block:: python

Updating / patching existing resources

r1.some_attr = 'something else'

Patching element in nested json

r1.some_dict.some_dict.some_attr = 'something else'

change relationships, to-many. Accepts also iterable of ResourceObjects/

ResourceIdentifiers/ResourceTuples

r1.comments = ['1', '2']

or if resource type is not known or can have multiple types of resources

r1.comments_or_people = [ResourceTuple('1', 'comments'), ResourceTuple('2', 'people')]

or if you want to add some resources you can

r1.comments_or_people += [ResourceTuple('1', 'people')] r1.commit()

change to-one relationships

r1.author = '3' # accepts also ResourceObjects/ResourceIdentifiers/ResourceTuple

or resource type is not known (via schema etc.)

r1.author = ResourceTuple('3', 'people')

Committing changes (PATCH request)

r1.commit(meta={'some_meta': 'data'}) # Resource committing supports optional meta data

AsyncIO

await r1.commit(meta={'some_meta': 'data'})

Creating new resources

.. code-block:: python

Creating new resources. Schema must be given. Accepts dictionary of schema models

(key is model name and value is schema as json-schema.org).

models_as_jsonschema = { 'articles': {'properties': { 'title': {'type': 'string'}, 'author': {'relation': 'to-one', 'resource': ['people']}, 'comments': {'relation': 'to-many', 'resource': ['comments']}, }}, 'people': {'properties': { 'first-name': {'type': 'string'}, 'last-name': {'type': 'string'}, 'twitter': {'type': ['null', 'string']}, }}, 'comments': {'properties': { 'body': {'type': 'string'}, 'author': {'relation': 'to-one', 'resource': ['people']} }} }

If you type schema by hand, it could be more convenient to type it as yml in a file

instead

s = Session('http://localhost:8080/', schema=models_as_jsonschema) a = s.create('articles') # Creates empty ResourceObject of 'articles' type a.title = 'Test title'

Validates and performs POST request, and finally updates resource based on server response

a.commit(meta={'some_meta': 'data'})

Or with AsyncIO, remember to await

await a.commit(meta={'some_meta': 'data'})

Commit metadata could be also saved in advance:

a.commit_metadata = {'some_meta': 'data'}

You can also commit all changed resources in session by

s.commit()

or with AsyncIO

await s.commit()

Another example of resource creation, setting attributes and relationships & committing:

If you have underscores in your field names, you can pass them in fields keyword argument as

a dictionary:

cust1 = s.create_and_commit('articles', attribute='1', dict_object__attribute='2', to_one_relationship='3', to_many_relationship=['1', '2'], fields={'some_field_with_underscore': '1'} )

Async:

cust1 = await s.create_and_commit('articles', attribute='1', dict_object__attribute='2', to_one_relationship='3', to_many_relationship=['1', '2'], fields={'some_field_with_underscore': '1'} )

Deleting resources

.. code-block:: python

# Delete resource
cust1.delete() # Mark to be deleted
cust1.commit() # Actually delete

Credits

License

Copyright (c) 2017, Qvantel

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  • Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  • Neither the name of the Qvantel nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL QVANTEL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].