Package: jsonapi-client
JSON API client for PythonIntroductionPackage repository:https://github.com/qvantel/jsonapi-clientThis Python (3.6+) library provides easy-to-use, pythonic, ORM-like access to
JSON API (http://jsonapi.org)Optional asyncio implementationOptional model schema definition and validation (=> easy reads even without schema)Resource caching within sessionInstallationFrom Pypi:pip install jsonapi-clientOr from sources:./setup.py installUsageClient sessionfromjsonapi_clientimportSession,Filter,ResourceTuples=Session('http://localhost:8080/')# To start session in async modes=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 objects=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.withSession(...)ass:yourcode# Or with enable_async=TrueasyncwithSession(...,enable_async=True):yourcode# If you are not using context manager, you need to close session manuallys.close()# Again, don't forget to await in the AsyncIO modeawaits.close()# Fetching documentsdocuments=s.get('resource_type')# Or if you want only 1, thendocuments=s.get('resource_type','id_of_document')# AsyncIO the same but remember to await:documents=awaits.get('resource_type')Filtering and including# 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 fieldsinclude=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# parametersmodifier_sum=filter+include+modifier# Now fetch your documentfiltered=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 thisPagination# Pagination links can be accessed via Document object.next_doc=document.links.next.fetch()# AsyncIOnext_doc=awaitdocument.links.next.fetch()# Iteration through results (uses pagination):forrins.iterate('resource_type'):print(r)# AsyncIO:asyncforrins.iterate('resource_type'):print(r)Resource attribute and relationship access# - attribute accessattr1=r1.some_attrnested_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 ResourceObjectrel=r1.some_relationattr3=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 contentawaitr1.some_relation.fetch()#     and then you can access associated resourceobjectres=r1.some_relation.resourceattr3=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_nameResource updating# Updating / patching existing resourcesr1.some_attr='something else'# Patching element in nested jsonr1.some_dict.some_dict.some_attr='something else'# change relationships, to-many. Accepts also iterable of ResourceObjects/# ResourceIdentifiers/ResourceTuplesr1.comments=['1','2']# or if resource type is not known or can have multiple types of resourcesr1.comments_or_people=[ResourceTuple('1','comments'),ResourceTuple('2','people')]# or if you want to add some resources you canr1.comments_or_people+=[ResourceTuple('1','people')]r1.commit()# change to-one relationshipsr1.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# AsyncIOawaitr1.commit(meta={'some_meta':'data'})Creating new resources# 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# insteads=Session('http://localhost:8080/',schema=models_as_jsonschema)a=s.create('articles')# Creates empty ResourceObject of 'articles' typea.title='Test title'# Validates and performs POST request, and finally updates resource based on server responsea.commit(meta={'some_meta':'data'})# Or with AsyncIO, remember to awaitawaita.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 bys.commit()# or with AsyncIOawaits.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=awaits.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# Delete resourcecust1.delete()# Mark to be deletedcust1.commit()# Actually deleteCreditsWork was supported by Qvantel (http://qvantel.com).Author and package maintainer: Tuomas Airaksinen (https://github.com/tuomas2/).LicenseCopyright (c) 2017, QvantelAll 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.CHANGELOG0.9.9 (2020-03-12)Adapt to aiohttp>3.0Workaround a weird bugFix deprecation warningsPrevent AttributeDict() from modifying its input#24: Fix error handling of server response0.9.8 (2020-02-14)#25: Fix for fetching resources without attributesStop following next when there are no more itemsFix buildUse custom_url logic for all request methods#27: Await close on async sessionsAdd apk libffi-dev dependencyFix pytest.raise exception validation e.valueAdded .venv, .vscode, .pytest_cache to .gitignoreAdd support for extra headers as request_kwargs0.9.7 (2019-02-01)Support __getitem__ in MetaHandle empty relationship data listAllow returning link to relationship as an iteratorFix handling null one-to-one-relationshipDon’t explicitly quote filter valuesInclude support0.9.6 (2017-06-26)When creating new resources, use default value specified in
jsonschema, when available.0.9.5 (2017-06-16)Change Session.create_and_commit signature similarly as Session.create0.9.4 (2017-06-16)Remove ? from filenames (illegal in Windows)Pass event loop aiohttp’s ClientSessionReturn resource from .commit if return status is 202Support underscores in field names in Session.create() through fields keyword argument.Add support for extra arguments such as authentication objectAsyncIO support for context manager usage of Session0.9.3 (2017-04-03)Added aiohttp to install requirements0.9.2 (2017-04-03)Github release.0.9.1 (2017-03-23)Fix async content_type checkingUse Python 3’s new typing.NamedTuple instead of collections.NamedTupleMake included resources available from DocumentResourceObject.json property