swapi-client 0.2.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,26 @@
1
+ name: "Publish"
2
+
3
+ on:
4
+ release:
5
+ types: ["published"]
6
+
7
+ jobs:
8
+ run:
9
+ name: "Build and publish release"
10
+ runs-on: ubuntu-latest
11
+
12
+ steps:
13
+ - uses: actions/checkout@v4
14
+
15
+ - name: Set up uv
16
+ uses: astral-sh/setup-uv@v6
17
+ with:
18
+ python-version: '3.12'
19
+ enable-cache: true
20
+ cache-dependency-glob: uv.lock
21
+
22
+ - name: Build
23
+ run: uv build
24
+
25
+ - name: Publish
26
+ run: uv publish --token ${{ secrets.PYPI_TOKEN }}
@@ -0,0 +1,57 @@
1
+ name: Create Release
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - master
7
+ paths-ignore:
8
+ - README.md
9
+ - .gitignore
10
+
11
+ jobs:
12
+ release:
13
+ name: Create Release
14
+ runs-on: ubuntu-latest
15
+
16
+ steps:
17
+ - name: Check out the repo
18
+ uses: actions/checkout@v4.1.7
19
+ with:
20
+ token: ${{ secrets.RELEASE_GIT_TOKEN }}
21
+ - name: Update version in pyproject.toml
22
+ id: version_bump
23
+ run: |
24
+ OLD_VERSION=$(awk -F ' = ' '/^version =/ {gsub(/"/, "", $2); print $2}' pyproject.toml)
25
+
26
+ IFS='.' read -r -a V_PARTS <<< "$OLD_VERSION"
27
+ V_PARTS[2]=$((V_PARTS[2] + 1))
28
+ NEW_VERSION="${V_PARTS[0]}.${V_PARTS[1]}.${V_PARTS[2]}"
29
+
30
+ # Using awk for safer replacement
31
+ awk -v old="version = \"$OLD_VERSION\"" -v new="version = \"$NEW_VERSION\"" '{gsub(old, new)}1' pyproject.toml > pyproject.toml.tmp && mv pyproject.toml.tmp pyproject.toml
32
+
33
+ echo "New version: $NEW_VERSION"
34
+ echo "VERSION=$NEW_VERSION" >> "$GITHUB_OUTPUT"
35
+ - name: Commit and push changes
36
+ run: |
37
+ git config --global user.email "github@actions.com"
38
+ git config --global user.name "GitHub Actions"
39
+ git add pyproject.toml
40
+ if [[ -n "$(git diff --cached)" ]]; then
41
+ git commit -m "Bump version to ${{ steps.version_bump.outputs.VERSION }} [skip ci]"
42
+ git push
43
+ else
44
+ echo "No changes to commit"
45
+ fi
46
+ - name: Extract version from pyproject.toml
47
+ id: extract_metadata
48
+ run: |
49
+ VERSION=$(awk -F ' = ' '/^version =/ {gsub(/"/, "", $2); print $2}' ./pyproject.toml)
50
+ echo "version=$VERSION" >> "$GITHUB_OUTPUT"
51
+ shell: bash
52
+ - name: Release New Version
53
+ uses: softprops/action-gh-release@v1
54
+ with:
55
+ name: v${{ steps.extract_metadata.outputs.version }}
56
+ tag_name: v${{ steps.extract_metadata.outputs.version }}
57
+ token: ${{ secrets.RELEASE_GIT_TOKEN }}
@@ -0,0 +1,196 @@
1
+ # Created by https://www.toptal.com/developers/gitignore/api/python,visualstudiocode
2
+ # Edit at https://www.toptal.com/developers/gitignore?templates=python,visualstudiocode
3
+
4
+ ### Python ###
5
+ # Byte-compiled / optimized / DLL files
6
+ __pycache__/
7
+ *.py[cod]
8
+ *$py.class
9
+
10
+ # C extensions
11
+ *.so
12
+
13
+ # Distribution / packaging
14
+ .Python
15
+ build/
16
+ develop-eggs/
17
+ dist/
18
+ downloads/
19
+ eggs/
20
+ .eggs/
21
+ lib/
22
+ lib64/
23
+ parts/
24
+ sdist/
25
+ var/
26
+ wheels/
27
+ share/python-wheels/
28
+ *.egg-info/
29
+ .installed.cfg
30
+ *.egg
31
+ MANIFEST
32
+
33
+ # PyInstaller
34
+ # Usually these files are written by a python script from a template
35
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
36
+ *.manifest
37
+ *.spec
38
+
39
+ # Installer logs
40
+ pip-log.txt
41
+ pip-delete-this-directory.txt
42
+
43
+ # Unit test / coverage reports
44
+ htmlcov/
45
+ .tox/
46
+ .nox/
47
+ .coverage
48
+ .coverage.*
49
+ .cache
50
+ nosetests.xml
51
+ coverage.xml
52
+ *.cover
53
+ *.py,cover
54
+ .hypothesis/
55
+ .pytest_cache/
56
+ cover/
57
+
58
+ # Translations
59
+ *.mo
60
+ *.pot
61
+
62
+ # Django stuff:
63
+ *.log
64
+ local_settings.py
65
+ db.sqlite3
66
+ db.sqlite3-journal
67
+
68
+ # Flask stuff:
69
+ instance/
70
+ .webassets-cache
71
+
72
+ # Scrapy stuff:
73
+ .scrapy
74
+
75
+ # Sphinx documentation
76
+ docs/_build/
77
+
78
+ # PyBuilder
79
+ .pybuilder/
80
+ target/
81
+
82
+ # Jupyter Notebook
83
+ .ipynb_checkpoints
84
+
85
+ # IPython
86
+ profile_default/
87
+ ipython_config.py
88
+
89
+ # pyenv
90
+ # For a library or package, you might want to ignore these files since the code is
91
+ # intended to run in multiple environments; otherwise, check them in:
92
+ # .python-version
93
+
94
+ # pipenv
95
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
96
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
97
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
98
+ # install all needed dependencies.
99
+ #Pipfile.lock
100
+
101
+ # poetry
102
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
103
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
104
+ # commonly ignored for libraries.
105
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
106
+ #poetry.lock
107
+
108
+ # pdm
109
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
110
+ #pdm.lock
111
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
112
+ # in version control.
113
+ # https://pdm.fming.dev/#use-with-ide
114
+ .pdm.toml
115
+
116
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
117
+ __pypackages__/
118
+
119
+ # Celery stuff
120
+ celerybeat-schedule
121
+ celerybeat.pid
122
+
123
+ # SageMath parsed files
124
+ *.sage.py
125
+
126
+ # Environments
127
+ .env
128
+ .venv
129
+ env/
130
+ venv/
131
+ ENV/
132
+ env.bak/
133
+ venv.bak/
134
+
135
+ # Spyder project settings
136
+ .spyderproject
137
+ .spyproject
138
+
139
+ # Rope project settings
140
+ .ropeproject
141
+
142
+ # mkdocs documentation
143
+ /site
144
+
145
+ # mypy
146
+ .mypy_cache/
147
+ .dmypy.json
148
+ dmypy.json
149
+
150
+ # Pyre type checker
151
+ .pyre/
152
+
153
+ # pytype static type analyzer
154
+ .pytype/
155
+
156
+ # Cython debug symbols
157
+ cython_debug/
158
+
159
+ # PyCharm
160
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
161
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
162
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
163
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
164
+ #.idea/
165
+
166
+ ### Python Patch ###
167
+ # Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration
168
+ poetry.toml
169
+
170
+ # ruff
171
+ .ruff_cache/
172
+
173
+ # LSP config files
174
+ pyrightconfig.json
175
+
176
+ ### VisualStudioCode ###
177
+ .vscode/*
178
+ !.vscode/settings.json
179
+ !.vscode/tasks.json
180
+ !.vscode/launch.json
181
+ !.vscode/extensions.json
182
+ !.vscode/*.code-snippets
183
+
184
+ # Local History for Visual Studio Code
185
+ .history/
186
+
187
+ # Built Visual Studio Code Extensions
188
+ *.vsix
189
+
190
+ ### VisualStudioCode Patch ###
191
+ # Ignore all local history of files
192
+ .history
193
+ .ionide
194
+
195
+ # End of https://www.toptal.com/developers/gitignore/api/python,visualstudiocode
196
+ main.py
@@ -0,0 +1 @@
1
+ 3.12
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 qwizi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,219 @@
1
+ Metadata-Version: 2.4
2
+ Name: swapi-client
3
+ Version: 0.2.2
4
+ Summary: API client for Serwis Planner
5
+ Project-URL: Homepage, https://github.com/qwizi/swapi-client
6
+ Project-URL: Bug Tracker, https://github.com/qwizi/swapi-client/issues
7
+ Author-email: qwizi <qwizi@qwizi.dev>
8
+ License: MIT License
9
+
10
+ Copyright (c) 2025 qwizi
11
+
12
+ Permission is hereby granted, free of charge, to any person obtaining a copy
13
+ of this software and associated documentation files (the "Software"), to deal
14
+ in the Software without restriction, including without limitation the rights
15
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16
+ copies of the Software, and to permit persons to whom the Software is
17
+ furnished to do so, subject to the following conditions:
18
+
19
+ The above copyright notice and this permission notice shall be included in all
20
+ copies or substantial portions of the Software.
21
+
22
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28
+ SOFTWARE.
29
+ License-File: LICENSE
30
+ Requires-Python: >=3.12
31
+ Requires-Dist: httpx>=0.27.0
32
+ Requires-Dist: python-dotenv>=1.0.1
33
+ Description-Content-Type: text/markdown
34
+
35
+ # SW-API-Client
36
+
37
+ An asynchronous Python client for the Serwis Planner API.
38
+
39
+ ## Features
40
+
41
+ - Asynchronous design using `httpx` and `asyncio`.
42
+ - Token-based authentication.
43
+ - Helper methods for all major API endpoints.
44
+ - Generic helpers for `meta`, `autoselect`, `history`, and `audit` endpoints.
45
+ - Pagination helper (`get_all_pages`) to easily fetch all results from paginated endpoints.
46
+ - Powerful `SWQueryBuilder` for creating complex queries with filtering, sorting, and field selection.
47
+ - No Pydantic models required; uses plain Python dictionaries for all data.
48
+
49
+ ## Installation
50
+
51
+ First, install the package from PyPI:
52
+
53
+ ```bash
54
+ pip install swapi-client
55
+ ```
56
+
57
+ The client uses `python-dotenv` to manage environment variables for the example. Install it if you want to run the example code directly.
58
+
59
+ ```bash
60
+ pip install python-dotenv
61
+ ```
62
+
63
+ ## Usage
64
+
65
+ ### Configuration
66
+
67
+ Create a `.env` file in your project root to store your API credentials:
68
+
69
+ ```env
70
+ SW_API_URL=https://your-api-url.com
71
+ SW_CLIENT_ID=your_client_id
72
+ SW_AUTH_TOKEN=your_auth_token
73
+ SW_LOGIN=your_login_email
74
+ SW_PASSWORD=your_password
75
+ ```
76
+
77
+ ### Example
78
+
79
+ Here is a complete example demonstrating how to log in, fetch data, and use the query builder.
80
+
81
+ ```python
82
+ import asyncio
83
+ import os
84
+ import pprint
85
+ from dotenv import load_dotenv
86
+ from swapi_client import SWApiClient, SWQueryBuilder
87
+
88
+ # Load environment variables from .env file
89
+ load_dotenv()
90
+
91
+ async def main():
92
+ """
93
+ Main function to demonstrate the usage of the SWApiClient.
94
+ """
95
+ api_url = os.getenv("SW_API_URL")
96
+ client_id = os.getenv("SW_CLIENT_ID")
97
+ auth_token = os.getenv("SW_AUTH_TOKEN")
98
+ login_user = os.getenv("SW_LOGIN")
99
+ password = os.getenv("SW_PASSWORD")
100
+
101
+ if not all([api_url, client_id, auth_token, login_user, password]):
102
+ print("Please set all required environment variables in a .env file.")
103
+ return
104
+
105
+ # The client is used within an async context manager
106
+ async with SWApiClient(api_url) as client:
107
+ try:
108
+ # 1. Login to get an authentication token
109
+ print("Attempting to log in...")
110
+ token = await client.login(
111
+ clientId=client_id,
112
+ authToken=auth_token,
113
+ login=login_user,
114
+ password=password,
115
+ )
116
+ print(f"Successfully logged in. Token starts with: {token[:10]}...")
117
+
118
+ # 2. Verify the token and get current user info
119
+ me = await client.get_me()
120
+ print(f"Token verified. Logged in as: {me.get('user', {}).get('username')}")
121
+ print("-" * 30)
122
+
123
+ # 3. Example: Get all account companies using the pagination helper
124
+ print("Fetching all account companies (with pagination)...")
125
+ all_companies = await client.get_all_pages(client.get_account_companies)
126
+ print(f"Found a total of {len(all_companies)} companies.")
127
+ if all_companies:
128
+ print(f"First company: {all_companies[0].get('name')}")
129
+ print("-" * 30)
130
+
131
+ # 4. Example: Use the SWQueryBuilder to filter, sort, and select fields
132
+ print("Fetching filtered companies...")
133
+ query = (
134
+ SWQueryBuilder()
135
+ .filter("name", "STB", "contains")
136
+ .order("name", "asc")
137
+ .fields(["id", "name", "email"])
138
+ .page_limit(5)
139
+ )
140
+ filtered_companies_response = await client.get_account_companies(query_builder=query)
141
+ filtered_companies = filtered_companies_response.get('data', [])
142
+ print(f"Found {len(filtered_companies)} companies matching the filter.")
143
+ pprint.pprint(filtered_companies)
144
+ print("-" * 30)
145
+
146
+ # 5. Example: Get metadata for a module
147
+ print("Fetching metadata for the 'products' module...")
148
+ products_meta = await client.get_entity_meta("products")
149
+ print("Available fields for products (first 5):")
150
+ for field, details in list(products_meta.get('data', {}).get('fields', {}).items())[:5]:
151
+ print(f" - {field}: {details.get('label')}")
152
+ print("-" * 30)
153
+
154
+ # 6. Example: Use for_metadata to get dynamic metadata
155
+ print("Fetching metadata for a serviced product with specific attributes...")
156
+ meta_query = SWQueryBuilder().for_metadata({"id": 1, "commissionPhase": 1})
157
+ serviced_product_meta = await client.get_entity_meta(
158
+ "serviced_products", query_builder=meta_query
159
+ )
160
+ print("Metadata for serviced product with for[id]=1 and for[commissionPhase]=1:")
161
+ pprint.pprint(serviced_product_meta.get('data', {}).get('fields', {}).get('commission'))
162
+
163
+ except Exception as e:
164
+ print(f"An error occurred: {e}")
165
+
166
+ if __name__ == "__main__":
167
+ asyncio.run(main())
168
+ ```
169
+
170
+ ## SWQueryBuilder
171
+
172
+ The `SWQueryBuilder` provides a fluent interface to construct complex query parameters for the API.
173
+
174
+ | Method | Description |
175
+ | ------------------------------------- | ------------------------------------------------------------------------------------------------------- |
176
+ | `fields(["field1", "field2"])` | Specifies which fields to include in the response. |
177
+ | `extra_fields(["field1"])` | Includes additional, non-default fields. |
178
+ | `for_metadata({"id": 1})` | Simulates an object change to retrieve dynamic metadata (uses `for[fieldName]`). |
179
+ | `order("field", "desc")` | Sorts the results by a field in a given direction (`asc` or `desc`). |
180
+ | `page_limit(50)` | Sets the number of results per page. |
181
+ | `page_offset(100)` | Sets the starting offset for the results. |
182
+ | `page_number(3)` | Sets the page number to retrieve. |
183
+ | `filter("field", "value", "op")` | Adds a filter condition. Operators: `eq`, `neq`, `gt`, `gte`, `lt`, `lte`, `contains`, `in`, `isNull`, etc. |
184
+ | `filter_or({...}, group_index=0)` | Adds a group of conditions where at least one must be true. |
185
+ | `filter_and({...}, group_index=0)` | Adds a group of conditions where all must be true. |
186
+ | `with_relations(True)` | Includes related objects in the response. |
187
+ | `with_editable_settings_for_action()` | Retrieves settings related to a specific action. |
188
+ | `lang("en")` | Sets the language for the response. |
189
+ | `build()` | Returns the dictionary of query parameters. |
190
+
191
+ ## API Methods
192
+
193
+ The client provides a comprehensive set of methods for interacting with the Serwis Planner API. It includes specific methods for most endpoints (e.g., `get_products`, `create_account_user`) as well as generic helpers.
194
+
195
+ ### Generic Helpers
196
+
197
+ - `get_all_pages(paginated_method, ...)`: Automatically handles pagination for any list endpoint.
198
+ - `get_entity_meta(module, ...)`: Fetches metadata for any module.
199
+ - `get_entity_autoselect(module, ...)`: Fetches autoselect data for any module.
200
+ - `get_entity_history(module, ...)`: Fetches history records for any module.
201
+ - `get_entity_audit(module, ...)`: Fetches audit records for any module.
202
+
203
+ ### Major Endpoints Covered
204
+
205
+ - Account Companies
206
+ - Account Users
207
+ - Products & Serviced Products
208
+ - Baskets & Basket Positions
209
+ - Commissions
210
+ - File Uploads
211
+ - ODBC Reports
212
+ - Email Messages
213
+ - PDF Generation
214
+ - History and Auditing
215
+ - Bulk and Contextual Operations
216
+ - Global Search
217
+ - And many more...
218
+
219
+ Each endpoint has corresponding `get`, `create`, `update`, `patch`, and `delete` methods where applicable. For a full list of available methods, please refer to the source code in `src/swapi_client/client.py`.