Skip to main content

python3 base API client for shopware6

Project description

lib_shopware6_api_base

Version v1.0.0 as of 2021-12-26 see Changelog

build_badge license pypi black

codecov better_code Maintainability Maintainability Code Coverage snyk

this is a basic API client for shopware6 which can be used on windows, Linux, MacOs. It supports all available authorisation types to the Admin and Storefront API. Paginated requests are supported.

This is only the basic abstraction layer, to enjoy higher level functions, check out “lib_shopware6_api”

On github it can be only tested on linux, because we can not run a docker shopware container service on MacOS or Windows.


automated tests, Travis Matrix, Documentation, Badges, etc. are managed with PizzaCutter (cookiecutter on steroids)

Python version required: 3.6.0 or newer

tested on recent linux with python 3.6, 3.7, 3.8, 3.9, 3.10.0, pypy-3.8 - architectures: amd64

100% code coverage, flake8 style checking ,mypy static type checking ,



Usage

configuration

the configuration is passed to the client as a configuration object of the type “ConfShopware6ApiBase” simply copy the Class definition of “ConfShopware6ApiBase” and create Your own configuration file, for instance “my_shop_config.py”

import attr


@attr.dataclass()
class ConfShopware6ApiBase(object):
    # the api url, like : 'https://shop.yourdomain.com/api'
    shopware_admin_api_url: str = ""
    # the storefront api url, like : 'https://shop.yourdomain.com/store-api'
    shopware_storefront_api_url: str = ""

    """
    Admin API:
    for User Credentials Grant Type:
    ==================================
    - with refresh token
    - we recommend to only use this grant flow for client applications that should
      perform administrative actions and require a user-based authentication

    """
    username: str = ""
    password: str = ""

    """
    Admin API:
    for Resource Owner Password Grant Type:
    =======================================
    - no refresh token
    - should be used for machine-to-machine communications, such as CLI jobs or automated services
    see https://shopware.stoplight.io/docs/admin-api/ZG9jOjEwODA3NjQx-authentication-and-authorisation
    setup at admin/settings/system/itegrations: "access_id" and "access_secret"
    """
    # the client ID, set up at setup at admin/settings/system/itegrations/access_id
    client_id: str = ""
    # the client secret, set up at setup at admin/settings/system/itegrations/access_secret
    client_secret: str = ""

    """
    Admin API:
    Grant Type to use:
    ==================
    which grant type to use - can be either 'user_credentials'- or 'resource_owner'
    """
    grant_type: str = ""

    """
    Store API:
    sw-access-key set in Administration/Sales Channels/API
    """
    store_api_sw_access_key: str = ""

now You can use this configuration:

from lib_shopware6_api_base import Shopware6AdminAPIClientBase
from my_shop_config import ConfShopware6ApiBase

my_conf = ConfShopware6ApiBase()
my_api_client = Shopware6AdminAPIClientBase(config=my_conf)
...
  • test configuration

for testing we use the dockware docker container, see : dockware

on github actions the dockware docker test container is installed as a service and is available for communication on localhost

You can start the dockware container locally with the command : sudo docker run -d –rm -p 80:80 –name dockware dockware/dev:latest

now You can test against that container with :

my_api_client = Shopware6AdminAPIClientBase(use_docker_test_container=True)
...

methods

please note, that on github actions the test configuration is used automatically, therefore on all examples no configuration is passed on purpose.

  • Store API

    for the Store API only “request_post” is implemented at the moment, which might be used as an example to implement all other methods like ‘get’, ‘patch’, ‘put’, ‘delete’.

    this is, because I only need the AdminAPI myself - contributions welcome !

class Shopware6StoreAPIClientBase(object):
    def __init__(self, config: Optional[ConfShopware6ApiBase] = None, use_docker_test_container: bool = False) -> None:
        """
        the Shopware6 Store Base API

        :param config:  You can pass a configuration object here.
                        If not given and github actions is detected, or use_docker_test_container == True:
                            conf_shopware6_api_docker_testcontainer.py will be loaded automatically
                        If not given and no github actions is detected:
                            conf_shopware6_api_base_rotek.py will be loaded automatically

        :param use_docker_test_container:   if True, and no config is given, the dockware config will be loaded

        >>> # Test to load automatic configuration
        >>> my_api_client = Shopware6StoreAPIClientBase()

        >>> # Test pass configuration
        >>> if _is_github_actions():
        ...     my_config = _load_config_for_docker_test_container()
        ...     my_api_client = Shopware6StoreAPIClientBase(config=my_config)

        """
  • Store API Post

def request_post(self, request_url: str, payload: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
    """

    >>> # Setup
    >>> my_api_client = Shopware6StoreAPIClientBase()

    >>> # test POST without payload
    >>> my_response = my_api_client.request_post(request_url='product')
    >>> assert 'elements' in my_response

    >>> # test POST with payload
    >>> # see : https://shopware.stoplight.io/docs/store-api/b3A6ODI2NTY4MQ-fetch-a-list-of-products
    >>> my_payload = {}  # noqa
    >>> my_payload["filter"] = [{"type": "equals", "field": "active", "value": "true"}]
    >>> my_response = my_api_client.request_post(request_url='product', payload=my_payload)
    >>> assert 'elements' in my_response

    """
  • Admin API

class Shopware6AdminAPIClientBase(object):
    def __init__(self, config: Optional[ConfShopware6ApiBase] = None, use_docker_test_container: bool = False) -> None:
        """
        the Shopware6 Admin Base API

        :param config:  You can pass a configuration object here.
                If not given and github actions is detected, or use_docker_test_container == True:
                    conf_shopware6_api_docker_testcontainer.py will be loaded automatically
                If not given and no github actions is detected:
                    conf_shopware6_api_base_rotek.py will be loaded automatically

        :param use_docker_test_container:   if True, and no config is given, the dockware config will be loaded

        >>> # Setup
        >>> my_api_client = Shopware6AdminAPIClientBase()

        """
  • Admin API GET

def request_get(self, request_url: str, payload: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
    """
    makes a get request

    parameters:
        request_url: API Url, without the common api prefix
        payload : a dictionary

    :returns
        response_dict: dictionary with the response as dict

    >>> # Setup
    >>> my_api_client = Shopware6AdminAPIClientBase()

    >>> # test resource owner token
    >>> ignore = my_api_client._get_access_token_by_user_credentials()
    >>> my_api_client._get_session()
    >>> ignore = my_api_client.request_get('customer-group')  # noqa

    >>> # test resource owner token refresh
    >>> my_access_token = my_api_client.token['access_token']
    >>> my_api_client.token['expires_in']=-1
    >>> my_api_client.token['expires_at']=time.time()-1
    >>> ignore = my_api_client.request_get('customer-group')
    >>> assert my_api_client.token['access_token'] != my_access_token

    >>> # Test client credentials token
    >>> ignore = my_api_client._get_access_token_by_resource_owner()
    >>> my_api_client._get_session()
    >>> ignore = my_api_client.request_get('customer-group')  # noqa

    >>> # test client credentials token refresh
    >>> my_access_token = my_api_client.token['access_token']
    >>> my_api_client.token['expires_in']=-1
    >>> my_api_client.token['expires_at']=time.time()-1
    >>> ignore = my_api_client.request_get('customer-group')
    >>> assert my_api_client.token['access_token'] != my_access_token

    """
  • Admin API GET Paginated

def request_get_paginated(self, request_url: str, payload: Optional[Dict[str, Any]] = None, limit: int = 100) -> Dict[str, Any]:
    """
    get the data paginated - metadata 'total' and 'totalCountMode' will be updated
    if You expect a big number of records, the paginated request reads those records in junks of limit=100 for performance reasons.

    parameters:
        request_url: API Url, without the common api prefix
        payload : a dictionary
        limit : the junk size

    :returns
        response_dict: dictionary with the response as dict

    >>> # Setup
    >>> my_api_client = Shopware6AdminAPIClientBase()

    >>> # test read product
    >>> my_response_dict = my_api_client.request_get_paginated(request_url='product', limit=3)
    >>> # we have got more then 3 items - so pagination is working
    >>> assert len(my_response_dict['data']) > 3

    """
  • Admin API PATCH

def request_patch(self, request_url: str, payload: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
    """
    makes a patch request

    parameters:
        request_url: API Url, without the common api prefix
        payload : a dictionary

    :returns
        response_dict: dictionary with the response as dict

    """
  • Admin API POST

def request_post(self, request_url: str, payload: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
    """
    makes a post request

    parameters:
        request_url: API Url, without the common api prefix
        payload : a dictionary

    :returns
        response_dict: dictionary with the response as dict

    """
  • Admin API POST PAGINATED

def request_post_paginated(self, request_url: str, payload: Optional[Dict[str, Any]] = None, limit: int = 100) -> Dict[str, Any]:
    """
    post the data paginated - metadata 'total' and 'totalCountMode' will be updated
    if You expect a big number of records, the paginated request reads those records in junks of limit=100 for performance reasons.

    parameters:
        request_url: API Url, without the common api prefix
        payload : a dictionary
        limit : the junk size

    :returns
        response_dict: dictionary with the response as dict

    """
  • Admin API PUT

def request_put(self, request_url: str, payload: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
    """
    makes a put request

    parameters:
        http_method: get, post, put, delete
        request_url: API Url, without the common api prefix
        payload : a dictionary

    :returns
        response_dict: dictionary with the response as dict

    """
  • Admin API DELETE

def request_delete(self, request_url: str, payload: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
    """
    makes a delete request

    parameters:
        http_method: get, post, put, delete
        request_url: API Url, without the common api prefix
        payload : a dictionary

    :returns
        response_dict: dictionary with the response as dict

    """

Usage from Commandline

Usage: lib_shopware6_api_base [OPTIONS] COMMAND [ARGS]...

  python3 base API client for shopware6

Options:
  --version                     Show the version and exit.
  --traceback / --no-traceback  return traceback information on cli
  -h, --help                    Show this message and exit.

Commands:
  info  get program informations

Installation and Upgrade

  • Before You start, its highly recommended to update pip and setup tools:

python -m pip --upgrade pip
python -m pip --upgrade setuptools
  • to install the latest release from PyPi via pip (recommended):

python -m pip install --upgrade lib_shopware6_api_base
  • to install the latest version from github via pip:

python -m pip install --upgrade git+https://github.com/bitranox/lib_shopware6_api_base.git
  • include it into Your requirements.txt:

# Insert following line in Your requirements.txt:
# for the latest Release on pypi:
lib_shopware6_api_base

# for the latest development version :
lib_shopware6_api_base @ git+https://github.com/bitranox/lib_shopware6_api_base.git

# to install and upgrade all modules mentioned in requirements.txt:
python -m pip install --upgrade -r /<path>/requirements.txt
  • to install the latest development version from source code:

# cd ~
$ git clone https://github.com/bitranox/lib_shopware6_api_base.git
$ cd lib_shopware6_api_base
python setup.py install
  • via makefile: makefiles are a very convenient way to install. Here we can do much more, like installing virtual environments, clean caches and so on.

# from Your shell's homedirectory:
$ git clone https://github.com/bitranox/lib_shopware6_api_base.git
$ cd lib_shopware6_api_base

# to run the tests:
$ make test

# to install the package
$ make install

# to clean the package
$ make clean

# uninstall the package
$ make uninstall

Requirements

following modules will be automatically installed :

## Project Requirements
attr
click
cli_exit_tools
lib_detect_testenv
oauthlib
requests
requests_oauthlib

Acknowledgements

  • special thanks to “uncle bob” Robert C. Martin, especially for his books on “clean code” and “clean architecture”

Contribute

I would love for you to fork and send me pull request for this project. - please Contribute

License

This software is licensed under the MIT license

Changelog

  • new MAJOR version for incompatible API changes,

  • new MINOR version for added functionality in a backwards compatible manner

  • new PATCH version for backwards compatible bug fixes

v1.0.0

2021-12-26: initial release

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

lib_shopware6_api_base-1.0.0.tar.gz (19.5 kB view details)

Uploaded Source

Built Distributions

If you're not sure about the file name format, learn more about wheel file names.

lib_shopware6_api_base-1.0.0-py3.10.egg (29.3 kB view details)

Uploaded Egg

lib_shopware6_api_base-1.0.0-py3.9.egg (29.2 kB view details)

Uploaded Egg

lib_shopware6_api_base-1.0.0-py3.8.egg (29.4 kB view details)

Uploaded Egg

lib_shopware6_api_base-1.0.0-py3.7.egg (29.2 kB view details)

Uploaded Egg

lib_shopware6_api_base-1.0.0-py3.6.egg (29.1 kB view details)

Uploaded Egg

lib_shopware6_api_base-1.0.0-py3-none-any.whl (17.6 kB view details)

Uploaded Python 3

File details

Details for the file lib_shopware6_api_base-1.0.0.tar.gz.

File metadata

  • Download URL: lib_shopware6_api_base-1.0.0.tar.gz
  • Upload date:
  • Size: 19.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.7.1 importlib_metadata/4.10.0 pkginfo/1.8.2 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.9.9

File hashes

Hashes for lib_shopware6_api_base-1.0.0.tar.gz
Algorithm Hash digest
SHA256 78861e209b0250690d2b871f0856905f40a34221f8e21bce918fd66f2880c60a
MD5 bab8a296c036c7d9735791aa050908b5
BLAKE2b-256 d4442b3967a87935da3c277b49f73a424fd619cea7e6f02686b6f255139c64ab

See more details on using hashes here.

File details

Details for the file lib_shopware6_api_base-1.0.0-py3.10.egg.

File metadata

  • Download URL: lib_shopware6_api_base-1.0.0-py3.10.egg
  • Upload date:
  • Size: 29.3 kB
  • Tags: Egg
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.7.1 importlib_metadata/4.10.0 pkginfo/1.8.2 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.10.0

File hashes

Hashes for lib_shopware6_api_base-1.0.0-py3.10.egg
Algorithm Hash digest
SHA256 dca9277fd73e89359c956799edb7bf0564c81cb3215d2ab33eb6cdb9dae52628
MD5 7e7f86e180a95a02f3c017a8dcf324c9
BLAKE2b-256 42cf8eff4b26e383d2db688ececfc8f72a0fe171c864b4a99e0a2354fd8e96a3

See more details on using hashes here.

File details

Details for the file lib_shopware6_api_base-1.0.0-py3.9.egg.

File metadata

  • Download URL: lib_shopware6_api_base-1.0.0-py3.9.egg
  • Upload date:
  • Size: 29.2 kB
  • Tags: Egg
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.7.1 importlib_metadata/4.10.0 pkginfo/1.8.2 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.9.9

File hashes

Hashes for lib_shopware6_api_base-1.0.0-py3.9.egg
Algorithm Hash digest
SHA256 9691f864597997d4524856806eadf4fd764534c7b69d697960a0f0f0d4dfe464
MD5 370c26230d3028971530f499d60df158
BLAKE2b-256 68105f91308420edf127ad126733661cc28618dd06ef615af74f17d32c864124

See more details on using hashes here.

File details

Details for the file lib_shopware6_api_base-1.0.0-py3.8.egg.

File metadata

  • Download URL: lib_shopware6_api_base-1.0.0-py3.8.egg
  • Upload date:
  • Size: 29.4 kB
  • Tags: Egg
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.7.1 importlib_metadata/4.10.0 pkginfo/1.8.2 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 PyPy/7.3.7

File hashes

Hashes for lib_shopware6_api_base-1.0.0-py3.8.egg
Algorithm Hash digest
SHA256 f6caf323282fdd0edd5530953e5ec9dcb8c804a977f9e8112cfdb3434efc8a69
MD5 02e4ddfd9749bb5fb391ada9ab419805
BLAKE2b-256 a19eda9e50e6d0810170df8506664222dd02c8dad0b4e2c61dd143d347bda52a

See more details on using hashes here.

File details

Details for the file lib_shopware6_api_base-1.0.0-py3.7.egg.

File metadata

  • Download URL: lib_shopware6_api_base-1.0.0-py3.7.egg
  • Upload date:
  • Size: 29.2 kB
  • Tags: Egg
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.7.1 importlib_metadata/4.2.0 pkginfo/1.8.2 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.7.12

File hashes

Hashes for lib_shopware6_api_base-1.0.0-py3.7.egg
Algorithm Hash digest
SHA256 7369228f60b821c02301c71c74f7fe5f345357dc44172d40e18cc90751dd16e7
MD5 913af322f9b3de693ad30c783cd6e01d
BLAKE2b-256 9faacac3c08698f7bc88531203b75f0ee6a85b7756a98d26024780d26045622f

See more details on using hashes here.

File details

Details for the file lib_shopware6_api_base-1.0.0-py3.6.egg.

File metadata

  • Download URL: lib_shopware6_api_base-1.0.0-py3.6.egg
  • Upload date:
  • Size: 29.1 kB
  • Tags: Egg
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.7.1 importlib_metadata/4.2.0 pkginfo/1.8.2 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.6.15

File hashes

Hashes for lib_shopware6_api_base-1.0.0-py3.6.egg
Algorithm Hash digest
SHA256 065de3c9b691f59d606039f5143d07d32401b1fbc188069d5c5e95c8864a636f
MD5 0ae492ac3ee41a28eeec43dfdb20f46d
BLAKE2b-256 f3e0829b5b4433ee227a2e78857bc73c4557684667ab61028a26118b80c31bee

See more details on using hashes here.

File details

Details for the file lib_shopware6_api_base-1.0.0-py3-none-any.whl.

File metadata

  • Download URL: lib_shopware6_api_base-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 17.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.7.1 importlib_metadata/4.10.0 pkginfo/1.8.2 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.9.9

File hashes

Hashes for lib_shopware6_api_base-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 2eca91889b2cce9c10a68574b78e27d42cef11c00c28c05dc202219fa4ff2085
MD5 2f9f0b970adb01f214ce664abf2f52fd
BLAKE2b-256 4d16caec0e04acc40a4fab14e34dd1b5e205d17ef7a2d7494fd0e6bf7d09d9e7

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page