├── .github ├── CODEOWNERS ├── dependabot.yml └── workflows │ ├── ci.yml │ └── releases.yml ├── .gitignore ├── .secrets └── .gitignore ├── LICENSE ├── README.md ├── config.sample.json ├── meltano.yml ├── mypy.ini ├── poetry.lock ├── pyproject.toml ├── tap-rest-api-msdk.sh ├── tap_rest_api_msdk ├── __init__.py ├── auth.py ├── client.py ├── pagination.py ├── streams.py ├── tap.py └── utils.py ├── tests ├── __init__.py ├── schema.json ├── test_core.py ├── test_streams.py ├── test_tap.py └── test_utils.py └── tox.ini /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | jlloyd@widen.com -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "py" # See documentation for possible values 9 | directory: "/" # Location of package manifests 10 | schedule: 11 | interval: "weekly" 12 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI (Testing/Linting) Workflow 2 | 3 | on: 4 | push: 5 | branches-ignore: 6 | - main 7 | 8 | jobs: 9 | build: 10 | runs-on: ubuntu-latest 11 | strategy: 12 | fail-fast: false 13 | matrix: 14 | python-version: ["3.8", "3.9", "3.10", "3.11", "3.12"] 15 | steps: 16 | - uses: actions/checkout@v2 17 | - name: Set up Python ${{ matrix.python-version }} 18 | uses: actions/setup-python@v2 19 | with: 20 | python-version: ${{ matrix.python-version }} 21 | - name: Install dependencies 22 | run: | 23 | python -m pip install pipx 24 | python -m pipx ensurepath 25 | python -m pipx install poetry 26 | # Force update PATH to include pipx executables 27 | export PATH=$PATH:/root/.local/bin 28 | # Create virtual environment and install dependencies 29 | poetry env use python 30 | poetry install --no-root 31 | - name: Test and lint the code 32 | run: | 33 | poetry run tox -e py 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /.github/workflows/releases.yml: -------------------------------------------------------------------------------- 1 | name: Publish New Releases to Pypi 2 | 3 | on: 4 | release: 5 | types: [published] 6 | workflow_dispatch: 7 | 8 | jobs: 9 | deploy: 10 | 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - uses: actions/checkout@v2 15 | - name: Set up Python 16 | uses: actions/setup-python@v2 17 | with: 18 | python-version: '3.9' 19 | - name: Install Poetry 20 | uses: snok/install-poetry@v1 21 | with: 22 | version: 1.3.2 23 | - name: Install dependencies 24 | run: | 25 | poetry env use python 26 | poetry install --no-root 27 | - name: Build package 28 | run: poetry build 29 | - name: Publish package 30 | uses: pypa/gh-action-pypi-publish@release/v1 31 | with: 32 | user: __token__ 33 | password: ${{ secrets.PYPI_API_TOKEN_PROD }} 34 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Secrets and internal config files 2 | **/.secrets/* 3 | 4 | # Ignore meltano internal cache and sqlite systemdb 5 | 6 | .meltano/ 7 | 8 | # Byte-compiled / optimized / DLL files 9 | __pycache__/ 10 | *.py[cod] 11 | *$py.class 12 | 13 | # C extensions 14 | *.so 15 | 16 | # Distribution / packaging 17 | .Python 18 | build/ 19 | develop-eggs/ 20 | dist/ 21 | downloads/ 22 | eggs/ 23 | .eggs/ 24 | lib/ 25 | lib64/ 26 | parts/ 27 | sdist/ 28 | var/ 29 | wheels/ 30 | pip-wheel-metadata/ 31 | share/python-wheels/ 32 | *.egg-info/ 33 | .installed.cfg 34 | *.egg 35 | MANIFEST 36 | 37 | # PyInstaller 38 | # Usually these files are written by a python script from a template 39 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 40 | *.manifest 41 | *.spec 42 | 43 | # Installer logs 44 | pip-log.txt 45 | pip-delete-this-directory.txt 46 | 47 | # Unit test / coverage reports 48 | htmlcov/ 49 | .tox/ 50 | .nox/ 51 | .coverage 52 | .coverage.* 53 | .cache 54 | nosetests.xml 55 | coverage.xml 56 | *.cover 57 | *.py,cover 58 | .hypothesis/ 59 | .pytest_cache/ 60 | 61 | # Translations 62 | *.mo 63 | *.pot 64 | 65 | # Django stuff: 66 | *.log 67 | local_settings.py 68 | db.sqlite3 69 | db.sqlite3-journal 70 | 71 | # Flask stuff: 72 | instance/ 73 | .webassets-cache 74 | 75 | # Scrapy stuff: 76 | .scrapy 77 | 78 | # Sphinx documentation 79 | docs/_build/ 80 | 81 | # PyBuilder 82 | target/ 83 | 84 | # Jupyter Notebook 85 | .ipynb_checkpoints 86 | 87 | # IPython 88 | profile_default/ 89 | ipython_config.py 90 | 91 | # pyenv 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 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 102 | __pypackages__/ 103 | 104 | # Celery stuff 105 | celerybeat-schedule 106 | celerybeat.pid 107 | 108 | # SageMath parsed files 109 | *.sage.py 110 | 111 | # Environments 112 | .env 113 | .venv 114 | env/ 115 | venv/ 116 | ENV/ 117 | env.bak/ 118 | venv.bak/ 119 | 120 | # Spyder project settings 121 | .spyderproject 122 | .spyproject 123 | 124 | # Rope project settings 125 | .ropeproject 126 | 127 | # mkdocs documentation 128 | /site 129 | 130 | # mypy 131 | .mypy_cache/ 132 | .dmypy.json 133 | dmypy.json 134 | 135 | # Pyre type checker 136 | .pyre/ 137 | 138 | # other 139 | .idea 140 | output 141 | -------------------------------------------------------------------------------- /.secrets/.gitignore: -------------------------------------------------------------------------------- 1 | # IMPORTANT! This folder is hidden from git - if you need to store config files or other secrets, 2 | # make sure those are never staged for commit into your git repo. You can store them here or another 3 | # secure location. 4 | # 5 | # Note: This may be redundant with the global .gitignore for, and is provided 6 | # for redundancy. If the `.secrets` folder is not needed, you may delete it 7 | # from the project. 8 | 9 | .gitignore 10 | !.gitignore 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # tap-rest-api-msdk 2 | ![singer_rest_api_tap](https://user-images.githubusercontent.com/84364906/220881634-c0d0145a-ab85-44e9-91b6-e8d365da25f3.png) 3 | 4 | `tap-rest-api-msdk` is a Singer tap for generic rest-apis. The novelty of this particular tap 5 | is that it will auto-discover the stream's schema. 6 | 7 | This is particularly useful if you have a stream with a very large and complex schema or 8 | a stream that outputs records with varying schemas for each record. Can also be used for 9 | simpler more reliable streams. 10 | 11 | There are many forms of Authentication supported by this tap. By default for legacy support, you can pass Authentication via headers. If you want to use the built in support for Authentication, this tap supports 12 | - Basic Authentication 13 | - API Key 14 | - Bearer Token 15 | - OAuth 16 | - AWS 17 | 18 | Please note that OAuthJWTAuthentication has not been developed. If you are interested in contributing this, please fork and make a pull request. 19 | 20 | Built with the Meltano [SDK](https://gitlab.com/meltano/sdk) for Singer Taps. 21 | 22 | Gratitude goes to [anelendata](https://github.com/anelendata/tap-rest-api) for inspiring this "SDK-ized" version of their tap. 23 | 24 | ## Installation 25 | If using via Meltano, add the following lines to your `meltano.yml` file and run the following command: 26 | 27 | ```yaml 28 | plugins: 29 | extractors: 30 | - name: tap-rest-api-msdk 31 | namespace: tap_rest_api_msdk 32 | pip_url: tap-rest-api-msdk 33 | executable: tap-rest-api-msdk 34 | capabilities: 35 | - state 36 | - catalog 37 | - discover 38 | settings: 39 | - name: api_url 40 | kind: string 41 | - name: next_page_token_path 42 | kind: string 43 | - name: pagination_request_style 44 | kind: string 45 | - name: pagination_response_style 46 | kind: string 47 | - name: use_request_body_not_params 48 | kind: boolean 49 | - name: backoff_type 50 | kind: string 51 | - name: backoff_param 52 | kind: string 53 | - name: backoff_time_extension 54 | kind: integer 55 | - name: store_raw_json_message 56 | kind: boolean 57 | - name: pagination_page_size 58 | kind: integer 59 | - name: pagination_results_limit 60 | kind: integer 61 | - name: pagination_next_page_param 62 | kind: string 63 | - name: pagination_limit_per_page_param 64 | kind: string 65 | - name: pagination_total_limit_param 66 | kind: string 67 | - name: pagination_initial_offset 68 | kind: integer 69 | - name: offset_records_jsonpath 70 | kind: string 71 | - name: streams 72 | kind: array 73 | - name: name 74 | kind: string 75 | - name: path 76 | kind: string 77 | - name: params 78 | kind: object 79 | - name: headers 80 | kind: object 81 | - name: records_path 82 | kind: string 83 | - name: primary_keys 84 | kind: array 85 | - name: replication_key 86 | kind: string 87 | - name: except_keys 88 | kind: array 89 | - name: num_inference_records 90 | kind: integer 91 | - name: start_date 92 | kind: date_iso8601 93 | - name: source_search_field 94 | kind: string 95 | - name: source_search_query 96 | kind: string 97 | - name: auth_method 98 | kind: string 99 | - name: api_key 100 | kind: object 101 | - name: client_id 102 | kind: password 103 | - name: client_secret 104 | kind: password 105 | - name: username 106 | kind: string 107 | - name: password 108 | kind: password 109 | - name: bearer_token 110 | kind: password 111 | - name: refresh_token 112 | kind: oauth 113 | - name: grant_type 114 | kind: string 115 | - name: scope 116 | kind: string 117 | - name: access_token_url 118 | kind: string 119 | - name: redirect_uri 120 | kind: string 121 | - name: oauth_extras 122 | kind: object 123 | - name: oauth_expiration_secs 124 | kind: integer 125 | - name: aws_credentials 126 | kind: object 127 | ``` 128 | 129 | ```bash 130 | meltano install extractor tap-rest-api-msdk 131 | ``` 132 | 133 | ## Configuration 134 | 135 | ### Accepted Config Options 136 | 137 | 138 | A full list of supported settings and capabilities for this 139 | tap is available by running: 140 | 141 | ```bash 142 | tap-rest-api-msdk --about 143 | ``` 144 | 145 | #### Top-level config options. 146 | Parameters that appear at the stream-level will overwrite their top-level 147 | counterparts except where noted in the stream-level params. Otherwise, the values 148 | provided at the top-level will be the default values for each stream.: 149 | - `api_url`: required: the base url/endpoint for the desired api. 150 | - `pagination_request_style`: optional: style for requesting pagination, defaults to `default` which is the `jsonpath_paginator`, see Pagination below. 151 | - `pagination_response_style`: optional: style of pagination results, defaults to `default` which is the `page` style response, see Pagination below. 152 | - `use_request_body_not_params`: optional: sends the request parameters in the request body. This is normally not required, a few API's like OpenSearch require this. Defaults to `False`. 153 | - `backoff_type`: optional: The style of Backoff [message|header] applied to rate limited APIs. Backoff times (seconds) come from response either the `message` or `header`. Defaults to `None`. 154 | - `backoff_param`: optional: the header parameter to inspect for a backoff time. Defaults to `Retry-After`. 155 | - `backoff_time_extension`: optional: An additional extension (seconds) to the backoff time over and above a jitter value - use where an API is not precise in it's backoff times. Defaults to `0`. 156 | - `store_raw_json_message`: optional: An additional extension which will emit the whole message into an field `_sdc_raw_json`. Useful for a dynamic schema which cannot be automatically discovered. Defaults to `False`. 157 | - `pagination_page_size`: optional: limit for size of page, defaults to None. 158 | - `pagination_results_limit`: optional: limits the max number of records. Note: Will cause an exception if the limit is hit (except for the `restapi_header_link_paginator`). This should be used for development purposes to restrict the total number of records returned by the API. Defaults to None. 159 | - `pagination_next_page_param`: optional: The name of the param that indicates the page/offset. Defaults to None. 160 | - `pagination_limit_per_page_param`: optional: The name of the param that indicates the limit/per_page. Defaults to None. 161 | - `pagination_total_limit_param`: optional: The name of the param that indicates the total limit e.g. total, count. Defaults to total 162 | - `pagination_initial_offset`: optional: The initial offset for the first request. Defaults to 1. 163 | - `offset_records_jsonpath`: optional: a jsonpath string representing the path to the records. Defaults to `None`. 164 | - `next_page_token_path`: optional: a jsonpath string representing the path to the "next page" token. Defaults to `'$.next_page'` for the `jsonpath_paginator` paginator only otherwise None. 165 | - `streams`: required: a list of objects that contain the configuration of each stream. See stream-level params below. 166 | - `path`: optional: see stream-level params below. 167 | - `params`: optional: see stream-level params below. 168 | - `headers`: optional: see stream-level params below. 169 | - `records_path`: optional: see stream-level params below. 170 | - `primary_keys`: optional: see stream-level params below. 171 | - `replication_key`: optional: see stream-level params below. 172 | - `except_keys`: optional: see stream-level params below. 173 | - `num_inference_keys`: optional: see stream-level params below. 174 | - `start_date`: optional: see stream-level params below. 175 | - `source_search_field`: optional: see stream-level params below. 176 | - `source_search_query`: optional: see stream-level params below. 177 | - `auth_method`: optional: see authentication params below. 178 | - `api_key`: optional: see authentication params below. 179 | - `client_id`: optional: see authentication params below. 180 | - `client_secret`: optional: see authentication params below. 181 | - `username`: optional: see authentication params below. 182 | - `password`: optional: see authentication params below. 183 | - `bearer_token`: optional: see authentication params below. 184 | - `refresh_token`: optional: see authentication params below. 185 | - `grant_type`: optional: see authentication params below. 186 | - `scope`: optional: see authentication params below. 187 | - `access_token_url`: optional: see authentication params below. 188 | - `redirect_uri`: optional: see authentication params below. 189 | - `oauth_extras`: optional: see authentication params below. 190 | - `oauth_expiration_secs`: optional: see authentication params below. 191 | - `aws_credentials`: optional: see authentication params below. 192 | - `offset_records_jsonpath`: optional: see pagination params below. 193 | 194 | #### Stream level config options. 195 | Parameters that appear at the stream-level 196 | will overwrite their top-level counterparts except where noted below: 197 | - `name`: required: name of the stream. 198 | - `path`: optional: the path appended to the `api_url`. 199 | - `params`: optional: an object of objects that provide the `params` in a `requests.get` method. 200 | Stream level params will be merged with top-level params with stream level params overwriting 201 | top-level params with the same key. 202 | - `headers`: optional: an object of headers to pass into the api calls. Stream level 203 | headers will be merged with top-level params with stream level params overwriting 204 | top-level params with the same key 205 | - `records_path`: optional: a jsonpath string representing the path in the requests response that contains the records to process. Defaults to `$[*]`. 206 | - `primary_keys`: required: a list of the json keys of the primary key for the stream. 207 | - `replication_key`: optional: the json key of the replication key. Note that this should be an incrementing integer or datetime object. 208 | - `except_keys`: This tap automatically flattens the entire json structure and builds keys based on the corresponding paths. 209 | Keys, whether composite or otherwise, listed in this dictionary will not be recursively flattened, but instead their values will be 210 | turned into a json string and processed in that format. This is also automatically done for any lists within the records; therefore, 211 | records are not duplicated for each item in lists. 212 | - `num_inference_keys`: optional: number of records used to infer the stream's schema. Defaults to 50. 213 | - `schema`: optional: A valid Singer schema or a path-like string that provides 214 | the path to a `.json` file that contains a valid Singer schema. If provided, 215 | the schema will not be inferred from the results of an api call. 216 | - `start_date`: optional: used by the the **offset**, **page**, and **hateoas_body** response styles. This is an initial starting date for an incremental replication if there is no 217 | existing state provided for an incremental replication. Example format 2022-06-10:23:10:10+1200. 218 | - `source_search_field`: optional: used by the **offset**, **page**, and **hateoas_body** response style. This is a search/query parameter used by the API for an incremental replication. 219 | 220 | The difference between the `replication_key` and the `source_search_field` is the search field used in request parameters whereas the replication_key is the name of the field in the API reponse. Example if the source_search_field = **last-updated** the generated schema from the api discovery 221 | might be **meta_lastUpdated**. The replication_key is set to meta_lastUpdated, and the search_parameter to last-updated. Note: Please set the `replication_key`, `start_date`, `source_search_field`, and `source_search_query` parameters all together. 222 | - `source_search_query`: optional: used by the **offset**, **page**, and **hateoas_body** response style. This is a query template to be issued against the API. A simple query template example for FHIR API's is **gt$last_run_date**. 223 | 224 | A more complex example against an Opensearch API, **{\\"bool\\": {\\"filter\\": [{\\"range\\": { \\"meta.lastUpdated\\": { \\"gt\\": \\"$last_run_date\\" }}}] }}**. Note: Any required double quotes in the query template must be escaped. 225 | 226 | At run-time, the tap will dynamically change the value **$last_run_date** with either the defined `start_date` parameter or the last bookmark / state value. 227 | Example: source_search_field=**last-updated**, the 228 | source_search_query = **gt$last_run_date**, and the current replication state = 2022-08-10:23:10:10+1200. At run time this creates a request parameter **last-updated=gt2022-06-10:23:10:10+1200**. 229 | 230 | #### Top-Level Authentication config options. 231 | - `auth_method`: optional: The method of authentication used by the API. Supported options 232 | include: 233 | - **oauth**: for OAuth2 authentication 234 | - **basic**: Basic Header authentication - base64-encoded username + password config items 235 | - **api_key**: for API Keys in the header e.g. X-API-KEY. 236 | - **bearer_token**: for Bearer token authentication. 237 | - **aws**: for AWS authentication. Works with the `aws_credentials` parameter. 238 | - Defaults to no_auth which will take authentication parameters passed via the headers config. 239 | - `api_keys`: optional: A dictionary of API Key/Value pairs used by the api_key auth method 240 | Example: { "X-API-KEY": "my secret value"}. 241 | - `client_id`: optional: Used for the OAuth2 authentication method. The public application ID 242 | that's assigned for Authentication. The **client_id** should accompany a **client_secret**. 243 | - `client_secret`: optional: Used for the OAuth2 authentication method. The client_secret is a 244 | secret known only to the application and the authorization server. It is essential the 245 | application's own password. 246 | - `username`: optional: Used for a number of authentication methods that use a user 247 | password combination for authentication. 248 | - `password`: optional: Used for a number of authentication methods that use a user password 249 | combination for authentication. 250 | - `bearer_token`: optional: Used for the Bearer Authentication method, which uses a token as part 251 | of the authorization header for authentication. 252 | - `refresh_token`: optional: An OAuth2 Refresh Token is a string that the OAuth2 client can use to 253 | get a new access token without the user's interaction. 254 | - `grant_type`: optional: Used for the OAuth2 authentication method. The grant_type is required 255 | to describe the OAuth2 flow. Flows support by this tap include **client_credentials**, **refresh_token**, **password**. 256 | - `scope`: optional: Used for the OAuth2 authentication method. The scope is optional, it is a 257 | mechanism to limit the amount of access that is granted to an access token. One or more scopes 258 | can be provided delimited by a space. 259 | - `access_token_url`: optional: Used for the OAuth2 authentication method. This is the end-point 260 | for the authentication server used to exchange the authorization codes for a access token. 261 | - `redirect_uri`: optional: Used for the OAuth2 authentication method. This optional as the 262 | redirect_uri may be part of the token returned by the authentication server. If a redirect_uri 263 | is provided, it determines where the API server redirects the user after the user completes the 264 | authorization flow. 265 | - `oauth_extras`: optional: A object of Key/Value pairs for additional oauth config parameters 266 | which may be required by the authorization server. Example: { "resource": "https://analysis.windows.net/powerbi/api" }. 267 | - `oauth_expiration_secs`: optional: Used for OAuth2 authentication method. This optional setting 268 | is a timer for the expiration of a token in seconds. If not set the OAuth will use the default 269 | expiration set in the token by the authorization server. 270 | - `aws_credentials`: optional: A object of Key/Value pairs to support AWS authentication when using the AWS authenticator. While the tap can use AWS [boto3](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html) environment variables and aws_profiles instead of supplying the keys and region, the [AWS service code](https://docs.aws.amazon.com/general/latest/gr/rande.html) needs to be specified e.g. `es` for OpenSearch / Elastic Search. By default the requirement to use `use_signed_credentials` is set to true. Config example: 271 | ```json 272 | { "aws_access_key_id": "my_aws_key_id", 273 | "aws_secret_access_key": "my_aws_secret_access_key", 274 | "aws_region": "us-east-1", 275 | "aws_service": "es", 276 | "use_signed_credentials": true} 277 | ``` 278 | 279 | #### Complex Authentication 280 | 281 | The previous section showed out of the box methods for a single factor of authentication e.g. x-api-key, basic or oauth. If the API requires multiple forms of authentication, you may need to pass some of the authentication methods via the headers to be be combined with the main auth_method. 282 | 283 | Example: 284 | An API may use OAuth2 for authentication but also requires an X-API-KEY to be supplied as well. In this situation pass the X-API-KEY as part of the `headers` config, and the rest of the config should be set for OAuth e.g. 285 | 286 | - headers = '{"x-api-key": "my_secret_api_key"}' 287 | - auth_method = "oauth" 288 | - grant_type = "client_credentials" 289 | - access_token_url = "https://auth.example.server/oauth2/token" 290 | - client_id = "my_example_client_id" 291 | - client_secret = "my_example_client_secret" 292 | 293 | Some servers may require additional information like a `Request-Context` which is usually Base64 encoded. If this is the case it should be included in the `headers` config as well. 294 | 295 | Example: 296 | 297 | - headers = '{"x-api-key": "my_secret_api_key", "Request-Context": "my_example_Base64_encoded_json_object"}' 298 | 299 | ## Pagination 300 | API Pagination is a complex topic as there is no real single standard, and many different implementations. Unless options are provided, both the request and results style type default to the `default`, which is the pagination style originally implemented. Where possible, this tap utilises the Meltano SDK paginators https://sdk.meltano.com/en/latest/reference.html#pagination . 301 | 302 | ### Default Request Style 303 | The default request style for pagination is using a `JSONPath Paginator` to locate the next page token. 304 | 305 | ### Default Response Style 306 | The default response style for pagination is described below: 307 | - If there is a token, add that as a `page` URL parameter. 308 | 309 | ### Additional Request / Paginator Styles 310 | There are additional request styles supported as follows for pagination. 311 | - `jsonpath_paginator` or `default` - This style obtains the token for the next page from a specific location in the response body via JSONPath notation. In many situations the `jsonpath_paginator` is a more appropriate paginator to the `hateoas_paginator`. 312 | - `next_page_token_path` - The jsonpath to next page token. Example: `"$['@odata.nextLink']"`, this locates the token returned via the Microsoft Graph API. Default `'$.next_page'` for the `jsonpath_paginator` paginator only otherwise None. 313 | - `offset_paginator` or `style1` - This style uses URL parameters named offset and limit 314 | - `offset` is calculated from the previous response, or not set if there is no previous response 315 | - `pagination_page_size` - Sets a limit to number of records per page / response. Default `25` records. 316 | - `pagination_limit_per_page_param` - the name of the API parameter to limit number of records per page. Default parameter name `limit`. 317 | - `pagination_total_limit_param` - The name of the param that indicates the total limit e.g. total, count. Defaults to total 318 | - `next_page_token_path` - Used to locate an appropriate link in the response. Default None - but looks in the `pagination` section of the JSON response by default. Example, jsonpath to get the offset from the NOAA API `'$.metadata.resultset'`. 319 | - `pagination_initial_offset` - The initial offset for the first request. Defaults to 1. 320 | - `simple_header_paginator` - This style uses links in the Header Response to locate the next page. Example the `x-next-page` link used by the Gitlab API. 321 | - `header_link_paginator` - This style uses the default header link paginator from the Meltano SDK. 322 | - `restapi_header_link_paginator` - This style is a variant on the header_link_paginator. It supports the ability to read from GitHub API. 323 | - `pagination_page_size` - Sets a limit to number of records per page / response. Default `25` records. 324 | - `pagination_limit_per_page_param` - the name of the API parameter to limit number of records per page. Default parameter name `per_page`. 325 | - `pagination_results_limit` - Restricts the total number of records returned from the API. Default None i.e. no limit. 326 | - `hateoas_paginator` - This style parses the next_token response for the parameters to pass. It is used by API's utilising the HATEOAS Rest style [HATEOAS](https://en.wikipedia.org/wiki/HATEOAS), including [FHIR API's](https://hl7.org/fhir/http.html). 327 | - `pagination_page_size` - Sets a limit to number of records per page / response. Default None. 328 | - `pagination_limit_per_page_param` - the name of the API parameter to limit number of records per page e.g. `_count` for [FHIR API's](https://hl7.org/fhir/http.html). Default None. 329 | - `single_page_paginator` - A paginator that does works with single-page endpoints. 330 | - `page_number_paginator` - Paginator class for APIs that use page number. Looks at the response link to determine more pages. 331 | - `next_page_token_path` - Use to locate an appropriate link in the response. Default `"hasMore"`. 332 | - `pagination_initial_offset` - Use to set the initial page number. Default `1`. 333 | - `simple_offset_paginator` - A paginator that uses `offset` and `limit` parameters to page through a collection of resources. Unlike `offset_paginator`, this paginator does not rely on any headers to determine whether it should keep paginating. Instead, it will continue paginating (by sending requests with increasing `offset`) until the API returns 0 results. You can use this paginator if the API returns a JSON array of records rather than a top-level object. 334 | - `pagination_page_size` - Sets a limit to number of records per page / response. Default `25` records. 335 | - `offset_records_jsonpath` - The JSONPath to the records in the response. Defaults to `None`. In the example below we would select the contacts array with `"offset_records_jsonpath": "$.contacts"`. Once the number of records doe not equal `pagination_page_size` the tap will stop paginating. 336 | 337 | ```json 338 | { 339 | "contacts": [ 340 | { 341 | "id": 52, 342 | "emailBlacklisted": false, 343 | "smsBlacklisted": false, 344 | "createdAt": "2024-09-24T01:00:00.000-00:00", 345 | "modifiedAt": "2024-09-25T01:00:00.000-00:00", 346 | } 347 | ], 348 | "count": 256 349 | } 350 | ``` 351 | 352 | ### Additional Response Styles 353 | There are additional response styles supported as follows. 354 | - `default` or `page` - This style uses page style offsets params to identify the next page. 355 | - `offset` or `style1` - This style retrieves pagination information by default from the `pagination` top-level element in the response. Expected format is as follows: 356 | ```json 357 | "pagination": { 358 | "total": 136, 359 | "limit": 2, 360 | "offset": 2 361 | } 362 | ``` 363 | The next page token, which in this case is really the next starting record number, is calculated by the limit, current offset, or None is returned to indicate no more data. For this style, the response style _must_ include the limit in the response, even if none is specified in the request, as well as ( `total` or `count` ) and offset to calculate the next token value. 364 | 365 | It is expected that this API Response Style will be used with request style of `offset_paginator` or `style1`. 366 | - The `next_page_token_jsonpath` can be used to provide a JSONPath location to the pagination location e.g. `'$.metadata.resultset'`. Default `pagination` from the tap-level element in the response. 367 | - `header_link` - This style parses the next page link in the Header Response. It is expected that this response will be used with an appropriate request style e.g. `restapi_header_link_paginator`. 368 | - `pagination_page_size` - Sets a limit to number of records per page / response. Default `25` records. 369 | - `pagination_limit_per_page_param` - the name of the API parameter to limit number of records per page. Default parameter name `per_page`. 370 | - `pagination_results_limit` - Restricts the total number of records returned from the API. Default None i.e. no limit. 371 | - `hateoas_body` - This style requires a well crafted `next_page_token_path` configuration 372 | parameter to retrieve the request parameters from the GET request response for a subsequent request. 373 | 374 | ### JSON Path for extracting tokens 375 | The `next_page_token_path` and `records_path` use JSONPath to locate sections within the request reponse. 376 | 377 | The following example extracts the URL for the next pagination page. 378 | ```json 379 | "next_page_token_path": "$.link[?(@.relation=='next')].url." 380 | ``` 381 | 382 | The following example demonstrates the power of JSONPath extensions by further splitting the URL and extracting just the parameters. Note: This is not required for FHIR API's but is provided for illustration of added functionality for complex use cases. 383 | ```json 384 | "next_page_token_path": "$.link[?(@.relation=='next')].url.`split(?, 1, 1)`" 385 | ``` 386 | The [JSONPath Evaluator](https://jsonpath.com/) website is useful to test the correct json path expression to use. 387 | 388 | Example json response from a FHIR API. 389 | 390 | 391 | ```json 392 | { 393 | "resourceType": "Bundle", 394 | "id": "44f2zf06-g53c-4218-a3ef-08bb6c2fde4a", 395 | "meta": { 396 | "lastUpdated": "2022-06-28T18:25:01.165+12:00" 397 | }, 398 | "type": "searchset", 399 | "total": 63, 400 | "link": [ 401 | { 402 | "relation": "self", 403 | "url": "https://myexample_fhir_api_url/base_folder/ExampleService?_count=10&_getpageoffset=10&services-provided-type=MY_INITIAL_EXAMPLE_SERVICE" 404 | }, 405 | { 406 | "relation": "next", 407 | "url": "https://myexample_fhir_api_url/base_folder?_getpages=44f2zf06-g53c-4218-a3ef-08bb6c2fde4a&_getpagesoffset=10&_count=10&_pretty=true&_bundletype=searchset" 408 | } 409 | ], 410 | "entry": [ 411 | { 412 | "fullUrl": "https://myexample_fhir_api_url/base_folder/ExampleService/example-service-123456", 413 | "resource": { 414 | "resourceType": "ExampleService", 415 | "id": "example-service-123456" 416 | } 417 | } 418 | ] 419 | } 420 | ``` 421 | 422 | Note: If you wish to extract the body from example GET request response above the following configuration parameter `records_path` will return the actual json content. 423 | ```json 424 | "records_path": "$.entry[*].resource" 425 | ``` 426 | 427 | ## Example settings for different API's 428 | 429 | This section provides examples of settings for accessing different API's. The tap configuration examples are provide in the form of environment variables. You could easily provide a configuration file [config.json](config.sample.json) instead of environment variables. 430 | 431 | Where config values have with `` replace the text with your Authentication and API config. 432 | 433 | ### Microsoft Graph API v1.0 434 | 435 | This example uses the `jsonpath paginator`. In this example, it requires a Microsoft Azure AD admin to register an APP to obtain an OAuth Token to perform an OAuth flow with the Microsoft Graph API. The details below may be different based on your setup, adjust accordingly. 436 | 437 | Result: Two streamed datasets, one `whoami` a simple json response about yourself, two a sharepoint list `my_sharepoint_list`. 438 | 439 | ``` 440 | # Access MSOFFICE objects via the GraphAPI 441 | export TAP_REST_API_MSDK_API_URL=https://graph.microsoft.com 442 | export TAP_REST_API_MSDK_PAGINATION_REQUEST_STYLE="jsonpath_paginator" 443 | export TAP_REST_API_MSDK_PAGINATION_RESPONSE_STYLE="hateoas_body" 444 | export TAP_REST_API_MSDK_NEXT_PAGE_TOKEN_PATH="$['@odata.nextLink']" 445 | export TAP_REST_API_MSDK_START_DATE="2001-01-01T00:00:00.00+12:00" 446 | export TAP_REST_API_MSDK_AUTH_METHOD="oauth" 447 | export TAP_REST_API_MSDK_USERNAME="" 448 | export TAP_REST_API_MSDK_PASSWORD="" 449 | export TAP_REST_API_MSDK_GRANT_TYPE="password" 450 | export TAP_REST_API_MSDK_ACCESS_TOKEN_URL="https://login.microsoftonline.com//oauth2/v2.0/token" 451 | export TAP_REST_API_MSDK_CLIENT_ID="" 452 | export TAP_REST_API_MSDK_CLIENT_SECRET="" 453 | export TAP_REST_API_MSDK_SCOPE="" 454 | export TAP_REST_API_MSDK_STREAMS='[{"name": "whoami", "path": "/v1.0/me", "primary_keys": ["id"]},{"name": "my_sharepoint_list", "path": "/v1.0/sites//Lists//items/?expand=columns,items(expand=fields)", "primary_keys": ["id"], "records_path": "$.value[*].fields"}]' 455 | ``` 456 | 457 | ### Gitlab API 458 | 459 | This example uses the `simple header paginator` and returns 50 records from the Gitlab API for Projects. Note: There is an exception raised due to the 50 record limit - this is an example hence the limit. 460 | 461 | ``` 462 | # Access Gitlab projects via the GitLab API 463 | export TAP_REST_API_MSDK_API_URL=https://gitlab.com/api/v4/projects 464 | export TAP_REST_API_MSDK_PAGINATION_REQUEST_STYLE="simple_header_paginator" 465 | export TAP_REST_API_MSDK_PAGINATION_RESULTS_LIMIT=50 466 | export TAP_REST_API_MSDK_STREAMS='[{"name": "gitlab_projects", "primary_keys": ["id"]}]' 467 | ``` 468 | 469 | You could authenticate to Gitlab using a Personal Access Token (PAT) by adding this config. 470 | ``` 471 | export TAP_REST_API_MSDK_HEADERS='{"Authorization": "Bearer "}' 472 | ``` 473 | 474 | ### GitHub API 475 | 476 | This example uses the `headerlink paginator` and returns approximately 250 records from the GitHub API for Projects. 477 | 478 | ``` 479 | # Access GitHub users via the GitHub API 480 | export TAP_REST_API_MSDK_API_URL=https://api.github.com/users 481 | export TAP_REST_API_MSDK_PAGINATION_REQUEST_STYLE="restapi_header_link_paginator" 482 | export TAP_REST_API_MSDK_PAGINATION_RESPONSE_STYLE="header_link" 483 | export TAP_REST_API_MSDK_PAGINATION_PAGE_SIZE=50 484 | export TAP_REST_API_MSDK_PAGINATION_RESULTS_LIMIT=250 485 | export TAP_REST_API_MSDK_STREAMS='[{"name": "github_users", "primary_keys": ["id"]}]' 486 | ``` 487 | 488 | You could authenticate to GitHub using a Personal Access Token (PAT) by adding this config. 489 | ``` 490 | export TAP_REST_API_MSDK_HEADERS='{"Authorization": "Bearer "}' 491 | ``` 492 | 493 | ### FHIR API 494 | 495 | This example uses the `jsonpath paginator` to access a FHIR API. It uses the `hateoas response style` to process the next tokens. 496 | 497 | This particular configuration will do an intial load of all data for a given resource defined in the `streams` config from the 01-Jan-2001. It will in subsequent runs incrementally pull changed data based on the lastUpdated timestamp by searching for records greater than the highest last updated timestamp. In this example the PlanDefinition FHIR resource is being extracted. 498 | 499 | You will need appropriate OAuth Token details provided by the Administrator of the API. 500 | 501 | ``` 502 | export TAP_REST_API_MSDK_API_URL= 503 | export TAP_REST_API_MSDK_PAGINATION_REQUEST_STYLE="jsonpath_paginator" 504 | export TAP_REST_API_MSDK_PAGINATION_RESPONSE_STYLE="hateoas_body" 505 | export TAP_REST_API_MSDK_NEXT_PAGE_TOKEN_PATH="$.link[?(@.relation=='next')].url" 506 | export TAP_REST_API_MSDK_START_DATE="2001-01-01T00:00:00.00+12:00" 507 | export TAP_REST_API_MSDK_AUTH_METHOD="oauth" 508 | export TAP_REST_API_MSDK_GRANT_TYPE="client_credentials" 509 | export TAP_REST_API_MSDK_ACCESS_TOKEN_URL="https://login.microsoftonline.com//oauth2/v2.0/token" 510 | export TAP_REST_API_MSDK_CLIENT_ID="" 511 | export TAP_REST_API_MSDK_CLIENT_SECRET="" 512 | export TAP_REST_API_MSDK_SCOPE="" 513 | export TAP_REST_API_MSDK_STREAMS='[{"name":"plan_definition","path":"/PlanDefinition","primary_keys":["id"],"records_path":"$.entry[*].resource","replication_key":"meta_lastUpdated","search_parameter":"_lastUpdated","source_search_query": "gt$last_run_date"}]' 514 | ``` 515 | 516 | ### NOAA API Example 517 | 518 | This example uses the `offset paginator` to access the NOAA API to return location categories. In this example the offset tokens are not in the default location of `pagination` so the `next_page_token_path` is set to the NOAA API offset location in the json response i.e. `'$.metadata.resultset'`. This example also sets a limit parameter in the `streams` to only return 5 records at a time to prove the pagination is working. 519 | 520 | ``` 521 | # Access Locations Categories objects via the NOAA API 522 | export TAP_REST_API_MSDK_API_URL=https://www.ncei.noaa.gov/cdo-web/api/v2 523 | export TAP_REST_API_MSDK_HEADERS='{"token": ""}' 524 | export TAP_REST_API_MSDK_NEXT_PAGE_TOKEN_PATH='$.metadata.resultset' 525 | export TAP_REST_API_MSDK_PAGINATION_REQUEST_STYLE="offset_paginator" 526 | export TAP_REST_API_MSDK_PAGINATION_RESPONSE_STYLE="style1" 527 | export TAP_REST_API_MSDK_PAGINATION_TOTAL_LIMIT_PARAM="count" 528 | export TAP_REST_API_MSDK_STREAMS='[{"name": "locationcategories", "params": {"limit": "5"}, "path": "/locationcategories", "primary_keys": ["id"], "records_path": "$.results[*]"}]' 529 | ``` 530 | 531 | ### dbt Cloud API Example 532 | 533 | This example uses the `offset paginator` to access the dbt Cloud API to return location categories. In this example the offset tokens are not in the default location of `pagination` so the `next_page_token_path` is set to the dbt API offset location in the json response i.e. `'$.extra'`. This example also sets the streams record_path to `"$.data[*]"` which is the location of the data. 534 | 535 | ``` 536 | # Access Locations Categories objects via the dbt Cloud API 537 | # Access Gitlab objects via the dbt Cloud API 538 | export TAP_REST_API_MSDK_API_URL=https://.getdbt.com/api/v2/accounts/ 539 | export TAP_REST_API_MSDK_HEADERS='{"Authorization": "Bearer "}' 540 | export TAP_REST_API_MSDK_NEXT_PAGE_TOKEN_PATH='$.extra' 541 | export TAP_REST_API_MSDK_PAGINATION_REQUEST_STYLE="offset_paginator" 542 | export TAP_REST_API_MSDK_PAGINATION_RESPONSE_STYLE="style1" 543 | export TAP_REST_API_MSDK_PAGINATION_TOTAL_LIMIT_PARAM="total_count" 544 | export TAP_REST_API_MSDK_STREAMS='[{"name": "jobs", "path": "/jobs", "primary_keys": ["id"], "records_path": "$.data[*]"}]' 545 | ``` 546 | 547 | ### AWS OpenSearch API Example 548 | 549 | This complex example uses the [AWS4Auth](https://github.com/tedder/requests-aws4auth) authenticator to provide signed AWS credentials in the requests to the AWS OpenSearch API endpoint. The `auth_method` is set to 'aws', and the required `aws_credentials` are provided. 550 | 551 | Note: The AWS authentication does support [boto3](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html) environment variables and aws_profiles. 552 | 553 | For pagination, the next page token is located in the **last** returned record. Using JSON Path the appropriate token response can be extracted via '$.hits.hits[-1:].sort' (-1 selects the last record in the array) and this is set in the `next_page_token_path` config setting. The API parameter used to select the next page is 'search_after' and this is set in the `pagination_next_page_param` config setting. To enable pagination in OpenSearch an API parameter named 'sort' must be set to a unique key e.g. '_id'. The number of records to returned per page is controlled via an API parameter called 'size'. 554 | 555 | The OpenSearch API has a complex incremental replication query which must be sent in the request body. This is enabled by setting the `use_request_body_not_params` to True. 556 | 557 | Finally set the replication suite of config settings ( `start_date`, `replication_key`, `source_search_field`, and `source_search_query` ) to enable incremental replication of data since the last run. For OpenSearch there is a complex query template which must be set in the streams `source_search_query` config setting. 558 | 559 | Unlike most API requests, the API query is against an API parameter named `query` rather than the name of the API field. For this reason the `source_search_field` is set to 'query' in the streams array. Additionally, the streams record_path to `"$.hits.hits[*]"` which is the location of the records in the requests response. 560 | 561 | ``` 562 | # Access AWS objects via the AWS Open/Elastic Search API 563 | export TAP_REST_API_MSDK_API_URL="https://...amazonaws.com" 564 | export TAP_REST_API_MSDK_AWS_CREDENTIALS='{"aws_access_key_id": "", "aws_secret_access_key": "removed aws secret access key>", "aws_region": "", "aws_service": "", "create_signed_credentials": true}' 565 | export TAP_REST_API_MSDK_START_DATE="2001-01-01T00:00:00.00+12:00" 566 | export TAP_REST_API_MSDK_PAGINATION_REQUEST_STYLE="jsonpath_paginator" 567 | export TAP_REST_API_MSDK_PAGINATION_RESPONSE_STYLE="offset" 568 | export TAP_REST_API_MSDK_USE_REQUEST_BODY_NOT_PARAMS=true 569 | export TAP_REST_API_MSDK_NEXT_PAGE_TOKEN_PATH='$.hits.hits[-1:].sort' 570 | export TAP_REST_API_MSDK_PAGINATION_NEXT_PAGE_PARAM="search_after" 571 | export TAP_REST_API_MSDK_AUTH_METHOD='aws' 572 | export TAP_REST_API_MSDK_STREAMS='[{"name": "careplan", "params": {"size": 100, "sort": "_id"}, "path": "/careplan/_search", "primary_keys": [], "records_path": "$.hits.hits[*]", "replication_key": "_source_meta_lastUpdated", "source_search_field": "query", "source_search_query": "{\"bool\": {\"filter\": [{\"range\": { \"meta.lastUpdated\": { \"gt\": \"$last_run_date\" }}}] }}"}]' 573 | ``` 574 | 575 | ## Usage 576 | 577 | 578 | You can easily run `tap-rest-api-msdk` by itself or in a pipeline using [Meltano](www.meltano.com). 579 | 580 | ### Executing the Tap Directly 581 | 582 | ```bash 583 | tap-rest-api-msdk --version 584 | tap-rest-api-msdk --help 585 | tap-rest-api-msdk --config CONFIG --discover > ./catalog.json 586 | ``` 587 | 588 | or 589 | 590 | ```bash 591 | bash tap-rest-api-msdk --config=config.sample.json 592 | ``` 593 | 594 | ## Developer Resources 595 | 596 | ### Initialize your Development Environment 597 | 598 | ```bash 599 | pipx install poetry 600 | poetry install 601 | ``` 602 | 603 | ### Create and Run Tests 604 | 605 | Create tests within the `tests/` directory and 606 | then run: 607 | 608 | ```bash 609 | poetry run pytest 610 | ``` 611 | 612 | You can also test the `tap-rest-api-msdk` CLI interface directly using `poetry run`: 613 | 614 | ```bash 615 | poetry run tap-rest-api-msdk --help 616 | ``` 617 | 618 | ### Continuous Integration 619 | Run through the full suite of tests and linters by running 620 | 621 | ```bash 622 | poetry run tox -e py 623 | ``` 624 | 625 | These must pass in order for PR's to be merged. 626 | 627 | ### Testing with [Meltano](https://www.meltano.com) 628 | 629 | _**Note:** This tap will work in any Singer environment and does not require Meltano. 630 | Examples here are for convenience and to streamline end-to-end orchestration scenarios._ 631 | 632 | This project comes with an example `meltano.yml` project file already created. 633 | 634 | Next, install Meltano (if you haven't already) and any needed plugins: 635 | 636 | ```bash 637 | # Install meltano 638 | pipx install meltano 639 | # Initialize meltano within this directory 640 | cd tap-rest-api-msdk 641 | meltano install 642 | ``` 643 | 644 | Now you can test and orchestrate using Meltano: 645 | 646 | ```bash 647 | # Test invocation: 648 | meltano invoke tap-rest-api-msdk --version 649 | # OR run a test `elt` pipeline: 650 | meltano elt tap-rest-api-msdk target-jsonl 651 | ``` 652 | 653 | ### SDK Dev Guide 654 | 655 | See the [dev guide](https://sdk.meltano.com/en/latest/dev_guide.html) for more instructions on how to use the SDK to 656 | develop your own taps and targets. 657 | -------------------------------------------------------------------------------- /config.sample.json: -------------------------------------------------------------------------------- 1 | { 2 | "pagination_request_style": "jsonpath_paginator", 3 | "pagination_response_style": "hateoas_body", 4 | "api_url": "https://myexample_fhir_api_url/base_folder", 5 | "pagination_page_size": 100, 6 | "next_page_token_path": "$.link[?(@.relation=='next')].url", 7 | "headers": { 8 | "X-API-KEY": "my_secret_hex_string_for_authentication" 9 | }, 10 | "streams": [ 11 | { 12 | "name": "my_sample_table_name", 13 | "path": "/ExampleService", 14 | "params": { 15 | "services-provided-type": "MY_INITIAL_EXAMPLE_SERVICE" 16 | }, 17 | "primary_keys": [ 18 | "id" 19 | ], 20 | "records_path": "$.entry[*].resource", 21 | "replication_key": "meta_lastUpdated", 22 | "start_date": "2001-01-01T00:00:00.00+12:00", 23 | "source_search_field": "last-updated", 24 | "source_search_query": "gt$last_run_date" 25 | } 26 | ] 27 | } -------------------------------------------------------------------------------- /meltano.yml: -------------------------------------------------------------------------------- 1 | version: 1 2 | send_anonymous_usage_stats: false 3 | plugins: 4 | extractors: 5 | - name: tap-rest-api-msdk 6 | namespace: tap_rest_api_msdk 7 | executable: ./tap-rest-api-msdk.sh 8 | capabilities: 9 | - state 10 | - catalog 11 | - discover 12 | settings: 13 | - name: api_url 14 | kind: string 15 | - name: next_page_token_path 16 | kind: string 17 | - name: pagination_request_style 18 | kind: string 19 | - name: pagination_response_style 20 | kind: string 21 | - name: use_request_body_not_params 22 | kind: boolean 23 | - name: backoff_type 24 | kind: string 25 | - name: backoff_param 26 | kind: string 27 | - name: backoff_time_extension 28 | kind: integer 29 | - name: store_raw_json_message 30 | kind: boolean 31 | - name: pagination_page_size 32 | kind: integer 33 | - name: pagination_results_limit 34 | kind: integer 35 | - name: pagination_next_page_param 36 | kind: string 37 | - name: pagination_limit_per_page_param 38 | kind: string 39 | - name: pagination_total_limit_param 40 | kind: string 41 | - name: pagination_initial_offset 42 | kind: integer 43 | - name: streams 44 | kind: array 45 | - name: path 46 | kind: string 47 | - name: params 48 | kind: object 49 | - name: headers 50 | kind: object 51 | - name: records_path 52 | kind: string 53 | - name: primary_keys 54 | kind: array 55 | - name: replication_key 56 | kind: string 57 | - name: except_keys 58 | kind: array 59 | - name: num_inference_records 60 | kind: integer 61 | - name: start_date 62 | kind: date_iso8601 63 | - name: source_search_field 64 | kind: string 65 | - name: source_search_query 66 | kind: string 67 | - name: auth_method 68 | kind: string 69 | - name: api_key 70 | kind: object 71 | - name: client_id 72 | kind: password 73 | - name: client_secret 74 | kind: password 75 | - name: username 76 | kind: string 77 | - name: password 78 | kind: password 79 | - name: bearer_token 80 | kind: password 81 | - name: refresh_token 82 | kind: oauth 83 | - name: grant_type 84 | kind: string 85 | - name: scope 86 | kind: string 87 | - name: access_token_url 88 | kind: string 89 | - name: redirect_uri 90 | kind: string 91 | - name: oauth_extras 92 | kind: object 93 | - name: oauth_expiration_secs 94 | kind: integer 95 | - name: aws_credentials 96 | kind: object 97 | config: 98 | api_url: https://earthquake.usgs.gov/fdsnws 99 | records_path: "$.features[*]" 100 | streams: 101 | - name: us_earthquakes 102 | path: /event/1/query 103 | params: 104 | format: geojson 105 | starttime: "2014-01-01" 106 | endtime: "2014-01-02" 107 | minmagnitude: 1 108 | primary_keys: 109 | - id 110 | num_inference_records: 100 111 | select: 112 | - '*.*' 113 | loaders: 114 | - name: target-jsonl 115 | variant: andyh1203 116 | pip_url: target-jsonl -------------------------------------------------------------------------------- /mypy.ini: -------------------------------------------------------------------------------- 1 | [mypy] 2 | python_version = 3.8 3 | warn_unused_configs = True 4 | warn_return_any = True 5 | exclude = tests 6 | 7 | [mypy-singer.*] 8 | # Library 'pipelinewise-singer-tools' does not have type hints: 9 | # - https://github.com/transferwise/pipelinewise-singer-python/issues/25 10 | ignore_missing_imports = True 11 | 12 | [mypy-backoff.*] 13 | # Frozen due to pipelinewise-singer-tools dependency 14 | ignore_missing_imports = True 15 | 16 | [mypy-bcrypt.*] 17 | ignore_missing_imports = True 18 | 19 | [mypy-boto3.*] 20 | ignore_missing_imports = True 21 | 22 | [mypy-joblib.*] 23 | ignore_missing_imports = True 24 | 25 | [mypy-pyarrow.*] 26 | ignore_missing_imports = True 27 | 28 | [mypy-pandas.*] 29 | ignore_missing_imports = True 30 | 31 | [mypy-jsonschema.*] 32 | ignore_missing_imports = True 33 | 34 | [mypy-jsonpath_ng.*] 35 | ignore_missing_imports = True 36 | 37 | [mypy-genson.*] 38 | ignore_missing_imports = True 39 | 40 | [mypy-requests_aws4auth.*] 41 | ignore_missing_imports = True 42 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.poetry] 2 | name = "tap-rest-api-msdk" 3 | version = "1.4.2" 4 | description = "`tap-rest-api-msdk` is a Singer tap for REST APIs, built with the Meltano SDK for Singer Taps." 5 | authors = ["Josh Lloyd", "Fred Reimer"] 6 | keywords = [ 7 | "ELT", 8 | "rest-api-msdk", 9 | "Meltano", 10 | "Singer", 11 | "REST", 12 | "API", 13 | "tap" 14 | ] 15 | license = "Apache 2.0" 16 | homepage = "https://github.com/Widen/tap-rest-api-msdk" 17 | repository = "https://github.com/Widen/tap-rest-api-msdk" 18 | readme = "README.md" 19 | 20 | [tool.poetry.dependencies] 21 | python = ">=3.8" 22 | requests = "^2.25.1" 23 | singer-sdk = { version = "^0.40.0", python = "<4" } 24 | genson = "^1.2.2" 25 | atomicwrites = "^1.4.0" 26 | requests-aws4auth = "^1.2.3" 27 | boto3 = "^1.26.156" 28 | 29 | [tool.poetry.dev-dependencies] 30 | pytest = "^8.2.2" 31 | tox = "^4.15.1" 32 | flake8 = { version = "^7.1.0", python = ">=3.8.1" } 33 | black = "^24.4.2" 34 | pydocstyle = "^6.3.0" 35 | mypy = "^1.10.0" 36 | types-requests = "^2.25.8" 37 | requests-mock = "^1.9.3" 38 | isort = "^5.13.2" 39 | types-python-dateutil = "^2.8.19.14" 40 | 41 | [tool.black] 42 | exclude = ".*simpleeval.*" 43 | 44 | [tool.isort] 45 | profile = "black" 46 | multi_line_output = 3 # Vertical Hanging Indent 47 | src_paths = "singer_sdk" 48 | known_first_party = ["tests", "samples"] 49 | 50 | [build-system] 51 | requires = ["poetry-core>=1.0.0"] 52 | build-backend = "poetry.core.masonry.api" 53 | 54 | [tool.poetry.scripts] 55 | # CLI declaration 56 | tap-rest-api-msdk = 'tap_rest_api_msdk.tap:TapRestApiMsdk.cli' 57 | -------------------------------------------------------------------------------- /tap-rest-api-msdk.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # This simple script allows you to test your tap from any directory, while still taking 4 | # advantage of the poetry-managed virtual environment. 5 | # Adapted from: https://github.com/python-poetry/poetry/issues/2179#issuecomment-668815276 6 | 7 | unset VIRTUAL_ENV 8 | 9 | STARTDIR=$(pwd) 10 | TOML_DIR=$(dirname "$0") 11 | 12 | cd "$TOML_DIR" || exit 13 | poetry install 1>&2 14 | poetry run tap-rest-api-msdk $* 15 | -------------------------------------------------------------------------------- /tap_rest_api_msdk/__init__.py: -------------------------------------------------------------------------------- 1 | """Package initialization.""" 2 | -------------------------------------------------------------------------------- /tap_rest_api_msdk/auth.py: -------------------------------------------------------------------------------- 1 | """REST authentication handling.""" 2 | 3 | import os 4 | from typing import Any 5 | 6 | import boto3 7 | from requests_aws4auth import AWS4Auth 8 | from singer_sdk.authenticators import ( 9 | APIAuthenticatorBase, 10 | APIKeyAuthenticator, 11 | BasicAuthenticator, 12 | BearerTokenAuthenticator, 13 | OAuthAuthenticator, 14 | ) 15 | 16 | 17 | class AWSConnectClient: 18 | """A connection class to AWS Resources.""" 19 | 20 | def __init__(self, connection_config, create_signed_credentials: bool = True): 21 | self.connection_config = connection_config 22 | 23 | # Initialise the variables 24 | self.create_signed_credentials = create_signed_credentials 25 | self.aws_auth = None 26 | self.region = None 27 | self.credentials = None 28 | self.aws_service = None 29 | self.aws_session = None 30 | 31 | # Establish a AWS Client 32 | self.credentials = self._create_aws_client() 33 | 34 | # Store AWS Signed Credentials 35 | self._store_aws4auth_credentials() 36 | 37 | def _create_aws_client(self, config=None): 38 | if not config: 39 | config = self.connection_config 40 | 41 | # Get the required parameters from config file and/or environment variables 42 | aws_profile = config.get("aws_profile") or os.environ.get("AWS_PROFILE") 43 | aws_access_key_id = config.get("aws_access_key_id") or os.environ.get( 44 | "AWS_ACCESS_KEY_ID" 45 | ) 46 | aws_secret_access_key = config.get("aws_secret_access_key") or os.environ.get( 47 | "AWS_SECRET_ACCESS_KEY" 48 | ) 49 | aws_session_token = config.get("aws_session_token") or os.environ.get( 50 | "AWS_SESSION_TOKEN" 51 | ) 52 | aws_region = config.get("aws_region") or os.environ.get("AWS_REGION") 53 | self.aws_service = config.get("aws_service", None) or os.environ.get( 54 | "AWS_SERVICE" 55 | ) 56 | 57 | if not config.get("create_signed_credentials", True): 58 | self.create_signed_credentials = False 59 | 60 | # AWS credentials based authentication 61 | if aws_access_key_id and aws_secret_access_key: 62 | self.aws_session = boto3.session.Session( 63 | aws_access_key_id=aws_access_key_id, 64 | aws_secret_access_key=aws_secret_access_key, 65 | region_name=aws_region, 66 | aws_session_token=aws_session_token, 67 | ) 68 | # AWS Profile based authentication 69 | elif aws_profile: 70 | self.aws_session = boto3.session.Session(profile_name=aws_profile) 71 | else: 72 | self.aws_session = None 73 | 74 | if self.aws_session: 75 | self.region = self.aws_session.region_name 76 | return self.aws_session.get_credentials() 77 | else: 78 | return None 79 | 80 | def _store_aws4auth_credentials(self): 81 | """Store the AWS Signed Credential for the available AWS credentials. 82 | 83 | Returns: 84 | The None. 85 | 86 | """ 87 | if self.create_signed_credentials and self.credentials: 88 | self.aws_auth = AWS4Auth( 89 | self.credentials.access_key, 90 | self.credentials.secret_key, 91 | self.region, 92 | self.aws_service, 93 | aws_session=self.credentials.token, 94 | ) 95 | else: 96 | self.aws_auth = None 97 | 98 | def get_awsauth(self): 99 | """Return the AWS Signed Connection for provided credentials. 100 | 101 | Returns: 102 | The awsauth object. 103 | 104 | """ 105 | return self.aws_auth 106 | 107 | def get_aws_session_client(self): 108 | """Return the AWS Signed Connection for provided credentials. 109 | 110 | Returns: 111 | The an AWS Session Client. 112 | 113 | """ 114 | return self.aws_session.client(self.aws_service, region_name=self.region) 115 | 116 | 117 | class ConfigurableOAuthAuthenticator(OAuthAuthenticator): 118 | """Configurable OAuth Authenticator.""" 119 | 120 | def get_initial_oauth_token(self): 121 | """Get oauth token for the tap schema discovery. 122 | 123 | Requests an oauth token and sets the auth headers. 124 | """ 125 | if not self.is_token_valid(): 126 | self.update_access_token() 127 | 128 | self.auth_headers["Authorization"] = f"Bearer {self.access_token}" 129 | 130 | @property 131 | def oauth_request_body(self) -> dict: 132 | """Build up a list of OAuth2 parameters. 133 | 134 | Build up a list of OAuth2 parameters to use depending 135 | on what configuration items have been set and the type of OAuth 136 | flow set by the grant_type. 137 | """ 138 | # Test where the config is located in self 139 | if self.config: # Tap Config 140 | my_config = self.config 141 | elif self._config: # Stream Config 142 | my_config = self._config 143 | 144 | client_id = my_config.get("client_id") 145 | client_secret = my_config.get("client_secret") 146 | username = my_config.get("username") 147 | password = my_config.get("password") 148 | refresh_token = my_config.get("refresh_token") 149 | grant_type = my_config.get("grant_type") 150 | scope = my_config.get("scope") 151 | redirect_uri = my_config.get("redirect_uri") 152 | oauth_extras = my_config.get("oauth_extras") 153 | 154 | oauth_params = {} 155 | 156 | # Test mandatory parameters based on grant_type 157 | if grant_type: 158 | oauth_params["grant_type"] = grant_type 159 | else: 160 | raise ValueError("Missing grant type for OAuth Token.") 161 | 162 | if grant_type == "client_credentials": 163 | if not (client_id and client_secret): 164 | raise ValueError( 165 | "Missing either client_id or client_secret for " 166 | "'client_credentials' grant_type." 167 | ) 168 | 169 | if grant_type == "password": 170 | if not (username and password): 171 | raise ValueError( 172 | "Missing either username or password for 'password' grant_type." 173 | ) 174 | 175 | if grant_type == "refresh_token": 176 | if not refresh_token: 177 | raise ValueError( 178 | "Missing either refresh_token for 'refresh_token' grant_type." 179 | ) 180 | 181 | # Add parameters if they are set 182 | if scope: 183 | oauth_params["scope"] = scope 184 | if client_id: 185 | oauth_params["client_id"] = client_id 186 | if client_secret: 187 | oauth_params["client_secret"] = client_secret 188 | if username: 189 | oauth_params["username"] = username 190 | if password: 191 | oauth_params["password"] = password 192 | if refresh_token: 193 | oauth_params["refresh_token"] = refresh_token 194 | if redirect_uri: 195 | oauth_params["redirect_uri"] = redirect_uri 196 | if oauth_extras: 197 | for k, v in oauth_extras.items(): 198 | oauth_params[k] = v 199 | 200 | return oauth_params 201 | 202 | 203 | def select_authenticator(self) -> Any: 204 | """Call an appropriate SDK Authentication method. 205 | 206 | Calls an appropriate SDK Authentication method based on the the set auth_method. 207 | If an auth_method is not provided, the tap will call the API using any settings from 208 | the headers and params config. 209 | Note: Each auth method requires certain configuration to be present see README.md 210 | for each auth methods configuration requirements. 211 | 212 | Raises: 213 | ValueError: if the auth_method is unknown. 214 | 215 | Returns: 216 | A SDK Authenticator or None if no auth_method supplied. 217 | 218 | """ 219 | # Test where the config is located in self 220 | if self.config: # Tap Config 221 | my_config = self.config 222 | elif self._config: # Stream Config 223 | my_config = self._config 224 | 225 | auth_method = my_config.get("auth_method", "") 226 | api_keys = my_config.get("api_keys", "") 227 | self.http_auth = None 228 | 229 | # Set http headers if headers are supplied 230 | # Some OAUTH2 API's require headers to be supplied 231 | # In the OAUTH request. 232 | auth_headers = my_config.get("headers", None) 233 | 234 | # Using API Key Authenticator, keys are extracted from api_keys dict 235 | if auth_method == "api_key": 236 | if api_keys: 237 | for k, v in api_keys.items(): 238 | key = k 239 | value = v 240 | return APIKeyAuthenticator(stream=self, key=key, value=value) 241 | # Using Basic Authenticator 242 | elif auth_method == "basic": 243 | return BasicAuthenticator( 244 | stream=self, 245 | username=my_config.get("username", ""), 246 | password=my_config.get("password", ""), 247 | ) 248 | # Using OAuth Authenticator 249 | elif auth_method == "oauth": 250 | return ConfigurableOAuthAuthenticator( 251 | stream=self, 252 | auth_endpoint=my_config.get("access_token_url", ""), 253 | oauth_scopes=my_config.get("scope", ""), 254 | default_expiration=my_config.get("oauth_expiration_secs", ""), 255 | oauth_headers=auth_headers, 256 | ) 257 | # Using Bearer Token Authenticator 258 | elif auth_method == "bearer_token": 259 | return BearerTokenAuthenticator( 260 | stream=self, 261 | token=my_config.get("bearer_token", ""), 262 | ) 263 | # Using AWS Authenticator 264 | elif auth_method == "aws": 265 | # Establish an AWS Connection Client and returned Signed Credentials 266 | self.aws_connection = AWSConnectClient( 267 | connection_config=my_config.get("aws_credentials", None) 268 | ) 269 | 270 | if self.aws_connection.aws_auth: 271 | self.http_auth = self.aws_connection.aws_auth 272 | else: 273 | self.http_auth = None 274 | 275 | return self.http_auth 276 | elif auth_method != "no_auth": 277 | self.logger.error( 278 | f"Unknown authentication method {auth_method}. Use api_key, basic, oauth, " 279 | f"bearer_token, or aws." 280 | ) 281 | raise ValueError( 282 | f"Unknown authentication method {auth_method}. Use api_key, basic, oauth, " 283 | f"bearer_token, or aws." 284 | ) 285 | 286 | 287 | def get_authenticator(self) -> Any: 288 | """Retrieve the appropriate authenticator in tap and stream. 289 | 290 | If the authenticator already exists, use the cached 291 | Authenticator 292 | 293 | Note: Store the authenticator in class variables used by the SDK. 294 | 295 | Returns: 296 | None 297 | 298 | """ 299 | # Test where the config is located in self 300 | if self.config: # Tap Config 301 | my_config = self.config 302 | elif self._config: # Stream Config 303 | my_config = self._config 304 | 305 | auth_method = my_config.get("auth_method", None) 306 | self.http_auth = None 307 | 308 | if not self._authenticator: 309 | self._authenticator = select_authenticator(self) 310 | if not self._authenticator: 311 | # No Auth Method, use default Authenticator 312 | self._authenticator = APIAuthenticatorBase(stream=self) 313 | if auth_method == "oauth": 314 | if not self._authenticator.is_token_valid(): 315 | # Obtain a new OAuth token as it has expired 316 | self._authenticator = select_authenticator(self) 317 | if auth_method == "aws": 318 | # Set the http_auth which is used in the Request call for AWS 319 | self.http_auth = self._authenticator 320 | -------------------------------------------------------------------------------- /tap_rest_api_msdk/client.py: -------------------------------------------------------------------------------- 1 | """REST client handling, including RestApiStream base class.""" 2 | 3 | from pathlib import Path 4 | from typing import Any 5 | 6 | from singer_sdk.streams import RESTStream 7 | from tap_rest_api_msdk.auth import get_authenticator 8 | 9 | SCHEMAS_DIR = Path(__file__).parent / Path("./schemas") 10 | 11 | 12 | class RestApiStream(RESTStream): 13 | """rest-api stream class.""" 14 | 15 | def __init__(self, *args, **kwargs): 16 | super().__init__(*args, **kwargs) 17 | self.http_auth = None 18 | self._authenticator = getattr(self, "assigned_authenticator", None) 19 | 20 | @property 21 | def url_base(self) -> Any: 22 | """Return the API URL root, configurable via tap settings. 23 | 24 | Returns: 25 | The base url for the api call. 26 | 27 | """ 28 | return self.config["api_url"] 29 | 30 | @property 31 | def authenticator(self) -> Any: 32 | """Call an appropriate SDK Authentication method. 33 | 34 | Calls an appropriate SDK Authentication method based on the the set 35 | auth_method which is set via the config. 36 | If an authenticator (auth_method) is not specified, REST-based taps will simply 37 | pass `http_headers` as defined in the tap and stream classes. 38 | 39 | Note 1: Each auth method requires certain configuration to be present see 40 | README.md for each auth methods configuration requirements. 41 | 42 | Note 2: Using Singleton Pattern on the autenticator for caching with a check 43 | if an OAuth Token has expired and needs to be refreshed. 44 | 45 | Raises: 46 | ValueError: if the auth_method is unknown. 47 | 48 | Returns: 49 | A SDK Authenticator or APIAuthenticatorBase if no auth_method supplied. 50 | 51 | """ 52 | # Obtaining Authenticator for authorisation to extract data. 53 | get_authenticator(self) 54 | 55 | return self._authenticator 56 | -------------------------------------------------------------------------------- /tap_rest_api_msdk/pagination.py: -------------------------------------------------------------------------------- 1 | """REST API pagination handling.""" 2 | 3 | from typing import Any, Optional, cast 4 | from urllib.parse import parse_qs, urlparse 5 | 6 | import requests 7 | from dateutil.parser import parse 8 | from singer_sdk.helpers.jsonpath import extract_jsonpath 9 | from singer_sdk.pagination import ( 10 | BaseOffsetPaginator, 11 | BasePageNumberPaginator, 12 | HeaderLinkPaginator, 13 | ) 14 | from tap_rest_api_msdk.utils import unnest_dict 15 | 16 | 17 | class RestAPIBasePageNumberPaginator(BasePageNumberPaginator): 18 | """REST API Base Page Number Paginator.""" 19 | 20 | def __init__(self, *args, jsonpath=None, **kwargs): 21 | super().__init__(*args, **kwargs) 22 | self._jsonpath = jsonpath 23 | 24 | def has_more(self, response: requests.Response): 25 | """Return True if there are more pages to fetch. 26 | 27 | Args: 28 | response: The most recent response object. 29 | jsonpath: An optional jsonpath to where the tokens are located in 30 | the response, defaults to `hasMore` in the response. 31 | 32 | Returns: 33 | Whether there are more pages to fetch. 34 | 35 | """ 36 | if self._jsonpath: 37 | return next(extract_jsonpath(self._jsonpath, response.json()), None) 38 | else: 39 | return response.json().get("hasMore", None) 40 | 41 | 42 | class RestAPIOffsetPaginator(BaseOffsetPaginator): 43 | """REST API Offset Paginator.""" 44 | 45 | def __init__( 46 | self, *args, jsonpath=None, pagination_total_limit_param: str, **kwargs 47 | ): 48 | super().__init__(*args, **kwargs) 49 | self.jsonpath = jsonpath 50 | self.pagination_total_limit_param = pagination_total_limit_param 51 | 52 | def has_more(self, response: requests.Response): 53 | """Return True if there are more pages to fetch. 54 | 55 | Args: 56 | response: The most recent response object. 57 | jsonpath: An optional jsonpath to where the tokens are located in 58 | the response, defaults to pagination in the response. 59 | 60 | Returns: 61 | Whether there are more pages to fetch. 62 | 63 | """ 64 | if self.jsonpath: 65 | pagination = next(extract_jsonpath(self.jsonpath, response.json()), None) 66 | else: 67 | pagination = response.json().get("pagination", None) 68 | if pagination: 69 | pagination = unnest_dict(pagination) 70 | 71 | if pagination and all(x in pagination for x in ["offset", "limit"]): 72 | record_limit = pagination.get(self.pagination_total_limit_param, 0) 73 | records_read = pagination["offset"] + pagination["limit"] 74 | if records_read <= record_limit: 75 | return True 76 | 77 | return False 78 | 79 | 80 | class SimpleOffsetPaginator(BaseOffsetPaginator): 81 | """Simple Offset Paginator.""" 82 | 83 | def __init__( 84 | self, 85 | *args, 86 | offset_records_jsonpath=None, 87 | pagination_page_size: int = 25, 88 | **kwargs 89 | ): 90 | super().__init__(*args, **kwargs) 91 | self._offset_records_jsonpath = offset_records_jsonpath 92 | self._pagination_page_size = pagination_page_size 93 | 94 | def has_more(self, response: requests.Response): 95 | """Return True if there are more pages to fetch. 96 | 97 | Args: 98 | response: The most recent response object. 99 | 100 | Returns: 101 | Whether there are more pages to fetch. 102 | 103 | """ 104 | if self._offset_records_jsonpath: 105 | records_left = len( 106 | next( 107 | extract_jsonpath(self._offset_records_jsonpath, response.json()), 0 108 | ) 109 | ) # type: ignore 110 | return records_left == self._pagination_page_size 111 | 112 | return len(response.json()) == self._pagination_page_size 113 | 114 | 115 | class RestAPIHeaderLinkPaginator(HeaderLinkPaginator): 116 | """REST API Header Link Paginator.""" 117 | 118 | def __init__( 119 | self, 120 | *args, 121 | pagination_page_size: int = 25, 122 | pagination_results_limit: Optional[int] = None, 123 | use_fake_since_parameter: Optional[bool] = False, 124 | replication_key: Optional[str] = None, 125 | **kwargs 126 | ): 127 | super().__init__(*args, **kwargs) 128 | self.pagination_page_size = pagination_page_size 129 | self.pagination_results_limit = pagination_results_limit 130 | self.use_fake_since_parameter = use_fake_since_parameter 131 | self.replication_key = replication_key 132 | 133 | def get_next_url(self, response: requests.Response) -> Optional[Any]: 134 | """Return next page parameter(s). 135 | 136 | Return next page parameter(s) for identifying the next page 137 | or None if no more pages. 138 | 139 | Logic based on https://github.com/MeltanoLabs/tap-github 140 | 141 | Args: 142 | response: The most recent response object. 143 | pagination_page_size: A limit for records per page. Default=25 144 | pagination_results_limit: A limit to the number of pages returned 145 | use_fake_since_parameter: A work around for GitHub. default=False 146 | replication_key: Key for incremental processing 147 | 148 | Returns: 149 | Page Parameters if there are more pages to fetch, else None. 150 | 151 | """ 152 | # Exit if the set Record Limit is reached. 153 | if ( 154 | self._page_count 155 | and self.pagination_results_limit 156 | and ( 157 | cast(int, self._page_count) * self.pagination_page_size 158 | >= self.pagination_results_limit 159 | ) 160 | ): 161 | return None 162 | 163 | # Leverage header links returned by the GitHub API. 164 | if "next" not in response.links.keys(): 165 | return None 166 | 167 | # Exit early if there is no URL in the next links 168 | if not response.links.get("next", {}).get("url"): 169 | return None 170 | 171 | resp_json = response.json() 172 | if isinstance(resp_json, list): 173 | results = resp_json 174 | else: 175 | results = resp_json.get("items") 176 | 177 | # Exit early if the response has no items. ? Maybe duplicative the "next" link 178 | # check. 179 | if not results: 180 | return None 181 | 182 | # Unfortunately endpoints such as /starred, /stargazers, /events and /pulls do 183 | # not support the "since" parameter out of the box. So we use a workaround here 184 | # to exit early. For such streams, we sort by descending dates (most recent 185 | # first), and paginate "back in time" until we reach records before our 186 | # "fake_since" parameter. 187 | if self.replication_key and self.use_fake_since_parameter: 188 | request_parameters = parse_qs(str(urlparse(response.request.url).query)) 189 | # parse_qs interprets "+" as a space, revert this to keep an aware datetime 190 | try: 191 | since = ( 192 | request_parameters["fake_since"][0].replace(" ", "+") 193 | if "fake_since" in request_parameters 194 | else "" 195 | ) 196 | except IndexError: 197 | return None 198 | 199 | direction = ( 200 | request_parameters["direction"][0] 201 | if "direction" in request_parameters 202 | else None 203 | ) 204 | 205 | # commit_timestamp is a constructed key which does not exist in the raw 206 | # response 207 | replication_date = ( 208 | results[-1][self.replication_key] 209 | if self.replication_key != "commit_timestamp" 210 | else results[-1]["commit"]["committer"]["date"] 211 | ) 212 | # exit early if the replication_date is before our since parameter 213 | if ( 214 | since 215 | and direction == "desc" 216 | and (parse(replication_date) < parse(since)) 217 | ): 218 | return None 219 | 220 | # Use header links returned by the API to return the query parameters. 221 | parsed_url = urlparse(response.links["next"]["url"]) 222 | 223 | if parsed_url.query: 224 | return parsed_url.query 225 | 226 | return None 227 | -------------------------------------------------------------------------------- /tap_rest_api_msdk/streams.py: -------------------------------------------------------------------------------- 1 | """Stream type classes for tap-rest-api-msdk.""" 2 | 3 | import email.utils 4 | import json 5 | from datetime import datetime 6 | from string import Template 7 | from typing import Any, Dict, Generator, Iterable, Optional, Union 8 | from urllib.parse import parse_qs, parse_qsl, urlparse 9 | 10 | import requests 11 | from singer_sdk.helpers import types 12 | from singer_sdk.helpers.jsonpath import extract_jsonpath 13 | from singer_sdk.pagination import ( 14 | BaseHATEOASPaginator, 15 | HeaderLinkPaginator, 16 | JSONPathPaginator, 17 | SimpleHeaderPaginator, 18 | SinglePagePaginator, 19 | ) 20 | from tap_rest_api_msdk.client import RestApiStream 21 | from tap_rest_api_msdk.pagination import ( 22 | RestAPIBasePageNumberPaginator, 23 | RestAPIHeaderLinkPaginator, 24 | RestAPIOffsetPaginator, 25 | SimpleOffsetPaginator, 26 | ) 27 | from tap_rest_api_msdk.utils import flatten_json, get_start_date 28 | 29 | # Remove commented section to show http_request for debugging 30 | # import logging 31 | # import http.client 32 | 33 | # http.client.HTTPConnection.debuglevel = 1 34 | 35 | # logging.basicConfig() 36 | # logging.getLogger().setLevel(logging.DEBUG) 37 | # requests_log = logging.getLogger("requests.packages.urllib3") 38 | # requests_log.setLevel(logging.DEBUG) 39 | # requests_log.propagate = True 40 | 41 | 42 | class DynamicStream(RestApiStream): 43 | """Define custom stream.""" 44 | 45 | def __init__( 46 | self, 47 | tap: Any, 48 | name: str, 49 | records_path: str, 50 | path: str, 51 | params: Optional[dict] = None, 52 | headers: Optional[dict] = None, 53 | primary_keys: Optional[list] = None, 54 | replication_key: Optional[str] = None, 55 | except_keys: Optional[list] = None, 56 | next_page_token_path: Optional[str] = None, 57 | schema: Optional[dict] = None, 58 | pagination_request_style: str = "default", 59 | pagination_response_style: str = "default", 60 | pagination_page_size: Optional[int] = None, 61 | pagination_results_limit: Optional[int] = None, 62 | pagination_next_page_param: Optional[str] = None, 63 | pagination_limit_per_page_param: Optional[str] = None, 64 | pagination_total_limit_param: Optional[str] = None, 65 | pagination_initial_offset: int = 1, 66 | offset_records_jsonpath: Optional[str] = None, 67 | start_date: Optional[datetime] = None, 68 | source_search_field: Optional[str] = None, 69 | source_search_query: Optional[str] = None, 70 | use_request_body_not_params: Optional[bool] = False, 71 | backoff_type: Optional[str] = None, 72 | backoff_param: Optional[str] = "Retry-After", 73 | backoff_time_extension: Optional[int] = 0, 74 | store_raw_json_message: Optional[bool] = False, 75 | authenticator: Optional[object] = None, 76 | ) -> None: 77 | """Class initialization. 78 | 79 | Args: 80 | tap: see tap.py 81 | name: see tap.py 82 | path: see tap.py 83 | params: see tap.py 84 | headers: see tap.py 85 | primary_keys: see tap.py 86 | replication_key: see tap.py 87 | except_keys: see tap.py 88 | records_path: see tap.py 89 | next_page_token_path: see tap.py 90 | schema: the json schema for the stream. 91 | pagination_request_style: see tap.py 92 | pagination_response_style: see tap.py 93 | pagination_page_size: see tap.py 94 | pagination_results_limit: see tap.py 95 | pagination_next_page_param: see tap.py 96 | pagination_limit_per_page_param: see tap.py 97 | pagination_total_limit_param: see tap.py 98 | pagination_initial_offset: see tap.py 99 | start_date: see tap.py 100 | source_search_field: see tap.py 101 | source_search_query: see tap.py 102 | use_request_body_not_params: see tap.py 103 | backoff_type: see tap.py 104 | backoff_param: see tap.py 105 | backoff_time_extension: see tap.py 106 | store_raw_json_message: see tap.py 107 | authenticator: see tap.py 108 | 109 | """ 110 | super().__init__(tap=tap, name=tap.name, schema=schema) 111 | 112 | if primary_keys is None: 113 | primary_keys = [] 114 | 115 | self.name = name 116 | self.path = path 117 | self.params = params if params else {} 118 | self.headers = headers 119 | self.assigned_authenticator = authenticator 120 | self._authenticator = authenticator 121 | self.primary_keys = primary_keys 122 | self.replication_key = replication_key 123 | self.except_keys = except_keys 124 | self.records_path = records_path 125 | 126 | if next_page_token_path: 127 | self.next_page_token_jsonpath = next_page_token_path 128 | elif ( 129 | pagination_request_style == "jsonpath_paginator" 130 | or pagination_request_style == "default" 131 | ): 132 | self.next_page_token_jsonpath = ( 133 | "$.next_page" # Set default for jsonpath_paginator 134 | ) 135 | get_url_params_styles = { 136 | "style1": self._get_url_params_offset_style, 137 | "offset": self._get_url_params_offset_style, 138 | "page": self._get_url_params_page_style, 139 | "header_link": self._get_url_params_header_link, 140 | "hateoas_body": self._get_url_params_hateoas_body, 141 | } 142 | 143 | # Selecting the appropriate method to send Parameters as part of the 144 | # request. If use_request_body_not_params is set the parameters are sent 145 | # in the request body instead of request parameters. The 146 | # pagination_response_style config determines what style of parameter 147 | # processing is invoked. 148 | 149 | self.use_request_body_not_params = use_request_body_not_params 150 | self.backoff_type = backoff_type 151 | self.backoff_param = backoff_param 152 | self.backoff_time_extension = backoff_time_extension 153 | self.store_raw_json_message = store_raw_json_message 154 | if self.use_request_body_not_params: 155 | self.prepare_request_payload = get_url_params_styles.get( # type: ignore 156 | pagination_response_style, self._get_url_params_page_style 157 | ) # Defaults to page_style url_params 158 | else: 159 | self.get_url_params = get_url_params_styles.get( # type: ignore 160 | pagination_response_style, self._get_url_params_page_style 161 | ) # Defaults to page_style url_params 162 | 163 | self.pagination_request_style = pagination_request_style 164 | self.pagination_results_limit = pagination_results_limit 165 | self.pagination_next_page_param = pagination_next_page_param 166 | self.pagination_limit_per_page_param = pagination_limit_per_page_param 167 | self.pagination_total_limit_param = pagination_total_limit_param 168 | self.start_date = start_date 169 | self.source_search_field = source_search_field 170 | self.source_search_query = source_search_query 171 | self.pagination_page_size: Optional[int] 172 | self.pagination_initial_offset = pagination_initial_offset 173 | self.offset_records_jsonpath = offset_records_jsonpath 174 | 175 | # Setting Pagination Limits 176 | if self.pagination_request_style == "restapi_header_link_paginator": 177 | if pagination_page_size: 178 | self.pagination_page_size = pagination_page_size 179 | else: 180 | if self.pagination_limit_per_page_param: 181 | page_limit_param = self.pagination_limit_per_page_param 182 | else: 183 | page_limit_param = "per_page" 184 | self.pagination_page_size = int( 185 | self.params.get(page_limit_param, 25) 186 | ) # Default to requesting 25 records 187 | elif ( 188 | self.pagination_request_style == "style1" 189 | or self.pagination_request_style == "offset_paginator" 190 | ): 191 | if self.pagination_results_limit: 192 | self.ABORT_AT_RECORD_COUNT = ( 193 | self.pagination_results_limit 194 | ) # Will raise an exception. 195 | if pagination_page_size: 196 | self.pagination_page_size = pagination_page_size 197 | else: 198 | if self.pagination_limit_per_page_param: 199 | page_limit_param = self.pagination_limit_per_page_param 200 | else: 201 | page_limit_param = "limit" 202 | self.pagination_page_size = int( 203 | self.params.get(page_limit_param, 25) 204 | ) # Default to requesting 25 records 205 | else: 206 | if self.pagination_results_limit: 207 | self.ABORT_AT_RECORD_COUNT = ( 208 | self.pagination_results_limit 209 | ) # Will raise an exception. 210 | self.pagination_page_size = pagination_page_size 211 | 212 | # GitHub is missing the "since" parameter on a few endpoints 213 | # set this parameter to True if your stream needs to navigate data in 214 | # descending order 215 | # and try to exit early on its own. 216 | # This only has effect on streams whose `replication_key` is `updated_at`. 217 | self.use_fake_since_parameter = False 218 | 219 | @property 220 | def http_headers(self) -> dict: 221 | """Return the http headers needed. 222 | 223 | Returns: 224 | A dictionary of the headers to be included in the request. 225 | 226 | """ 227 | headers = {} 228 | if "user_agent" in self.config: 229 | headers["User-Agent"] = self.config.get("user_agent") 230 | # If not using an authenticator, you may also provide inline auth headers: 231 | # headers["Private-Token"] = self.config.get("auth_token") 232 | 233 | if self.headers: 234 | for k, v in self.headers.items(): 235 | headers[k] = v 236 | 237 | return headers 238 | 239 | def backoff_wait_generator( 240 | self, 241 | ) -> Generator[Union[int, float], None, None]: 242 | """Return a backoff generator as required to manage Rate Limited APIs. 243 | 244 | Supply a backoff_type in the config to indicate the style of backoff. 245 | If the backoff response is in a header, supply a backoff_param 246 | indicating what key contains the backoff delay. 247 | 248 | Note: If the backoff_type is message, the message is parsed for numeric 249 | values. It is assumed that the highest numeric value discovered is the 250 | backoff value in seconds. 251 | 252 | Returns: 253 | Backoff Generator with value to wait based on the API Response. 254 | 255 | """ 256 | 257 | def _backoff_from_headers(exception): 258 | response_headers = exception.response.headers 259 | 260 | return ( 261 | int(response_headers.get(self.backoff_param, 0)) 262 | + self.backoff_time_extension 263 | ) 264 | 265 | def _get_wait_time_from_response(exception): 266 | response_message = exception.response.json().get("message", 0) 267 | res = [int(i) for i in response_message.split() if i.isdigit()] 268 | 269 | return int(max(res)) + self.backoff_time_extension 270 | 271 | if self.backoff_type == "message": 272 | return self.backoff_runtime(value=_get_wait_time_from_response) 273 | elif self.backoff_type == "header": 274 | return self.backoff_runtime(value=_backoff_from_headers) 275 | else: 276 | # No override required. Use SDK backoff_wait_generator 277 | return super().backoff_wait_generator() 278 | 279 | def get_new_paginator(self): 280 | """Return the requested paginator required to retrieve all data from the API. 281 | 282 | Returns: 283 | Paginator Class. 284 | 285 | """ 286 | self.logger.info( 287 | f"the next_page_token_jsonpath = {self.next_page_token_jsonpath}." 288 | ) 289 | 290 | if ( 291 | self.pagination_request_style == "jsonpath_paginator" 292 | or self.pagination_request_style == "default" 293 | ): 294 | return JSONPathPaginator(self.next_page_token_jsonpath) 295 | elif ( 296 | self.pagination_request_style == "simple_header_paginator" 297 | ): # Example Gitlab.com 298 | if self.next_page_token_jsonpath: 299 | return JSONPathPaginator(self.next_page_token_jsonpath) 300 | 301 | return SimpleHeaderPaginator("X-Next-Page") 302 | elif self.pagination_request_style == "header_link_paginator": 303 | return HeaderLinkPaginator() 304 | elif ( 305 | self.pagination_request_style == "restapi_header_link_paginator" 306 | ): # Example GitHub.com 307 | return RestAPIHeaderLinkPaginator( 308 | pagination_page_size=self.pagination_page_size, 309 | pagination_results_limit=self.pagination_results_limit, 310 | replication_key=self.replication_key, 311 | ) 312 | elif ( 313 | self.pagination_request_style == "style1" 314 | or self.pagination_request_style == "offset_paginator" 315 | ): 316 | return RestAPIOffsetPaginator( 317 | start_value=self.pagination_initial_offset, 318 | page_size=self.pagination_page_size, 319 | jsonpath=self.next_page_token_jsonpath, 320 | pagination_total_limit_param=self.pagination_total_limit_param, 321 | ) 322 | elif self.pagination_request_style == "hateoas_paginator": 323 | return BaseHATEOASPaginator() 324 | elif self.pagination_request_style == "single_page_paginator": 325 | return SinglePagePaginator() 326 | elif self.pagination_request_style == "page_number_paginator": 327 | return RestAPIBasePageNumberPaginator( 328 | start_value=self.pagination_initial_offset, 329 | jsonpath=self.next_page_token_jsonpath 330 | ) 331 | elif self.pagination_request_style == "simple_offset_paginator": 332 | return SimpleOffsetPaginator( 333 | start_value=self.pagination_initial_offset, 334 | page_size=self.pagination_page_size, 335 | offset_records_jsonpath=self.offset_records_jsonpath, 336 | pagination_page_size=self.pagination_page_size, 337 | ) 338 | else: 339 | self.logger.error( 340 | f"Unknown paginator {self.pagination_request_style}. Please declare " 341 | f"a valid paginator." 342 | ) 343 | raise ValueError( 344 | f"Unknown paginator {self.pagination_request_style}. Please declare " 345 | f"a valid paginator." 346 | ) 347 | 348 | def _get_url_params_page_style( 349 | self, context: Optional[dict], next_page_token: Optional[Any] 350 | ) -> Dict[str, Any]: 351 | """Return a dictionary of values to be used in URL parameterization. 352 | 353 | Args: 354 | context: optional - the singer context object. 355 | next_page_token: optional - the token for the next page of results. 356 | 357 | Returns: 358 | An object containing the parameters to add to the request. 359 | 360 | """ 361 | # Initialise Starting Values 362 | last_run_date = get_start_date(self, context) 363 | params: dict = {} 364 | if self.params: 365 | for k, v in self.params.items(): 366 | params[k] = v 367 | if next_page_token: 368 | if self.pagination_next_page_param: 369 | next_page_parm = self.pagination_next_page_param 370 | else: 371 | next_page_parm = "page" 372 | params[next_page_parm] = next_page_token 373 | if self.replication_key: 374 | # Use incremental replication (if available) via a filter query being 375 | # sent to the API This assumes storing a replication timestamp and querying 376 | # records greater than that date in subsequent runs. Config the appropriate 377 | # source field and query template. 378 | if self.source_search_field and self.source_search_query and last_run_date: 379 | query_template = Template(self.source_search_query) 380 | if self.use_request_body_not_params: 381 | params[self.source_search_field] = json.loads( 382 | query_template.substitute(last_run_date=last_run_date) 383 | ) 384 | else: 385 | params[self.source_search_field] = query_template.substitute( 386 | last_run_date=last_run_date 387 | ) 388 | else: 389 | params["sort"] = "asc" 390 | params["order_by"] = self.replication_key 391 | 392 | return params 393 | 394 | def _get_url_params_offset_style( 395 | self, context: Optional[dict], next_page_token: Optional[Any] 396 | ) -> Dict[str, Any]: 397 | """Return a dictionary of values to be used in URL parameterization. 398 | 399 | Args: 400 | context: optional - the singer context object. 401 | next_page_token: optional - the token for the next page of results. 402 | 403 | Returns: 404 | An object containing the parameters to add to the request. 405 | 406 | """ 407 | # Initialise Starting Values 408 | last_run_date = get_start_date(self, context) 409 | params: dict = {} 410 | 411 | if self.params: 412 | for k, v in self.params.items(): 413 | params[k] = v 414 | if next_page_token: 415 | if self.pagination_next_page_param: 416 | next_page_parm = self.pagination_next_page_param 417 | else: 418 | next_page_parm = "offset" 419 | params[next_page_parm] = next_page_token 420 | if self.pagination_page_size is not None: 421 | if self.pagination_limit_per_page_param: 422 | limit_per_page_param = self.pagination_limit_per_page_param 423 | else: 424 | limit_per_page_param = "limit" 425 | params[limit_per_page_param] = self.pagination_page_size 426 | if self.replication_key: 427 | # Use incremental replication (if available) via a filter query being sent 428 | # to the API This assumes storing a replication timestamp and querying 429 | # records greater than that date in subsequent runs. Config the appropriate 430 | # source field and query template. 431 | if self.source_search_field and self.source_search_query and last_run_date: 432 | query_template = Template(self.source_search_query) 433 | if self.use_request_body_not_params: 434 | params[self.source_search_field] = json.loads( 435 | query_template.substitute(last_run_date=last_run_date) 436 | ) 437 | else: 438 | params[self.source_search_field] = query_template.substitute( 439 | last_run_date=last_run_date 440 | ) 441 | else: 442 | params["sort"] = "asc" 443 | params["order_by"] = self.replication_key 444 | 445 | return params 446 | 447 | def _get_url_params_header_link( 448 | self, context: Optional[Dict], next_page_token: Optional[Any] 449 | ) -> Dict[str, Any]: 450 | """Return a dictionary of values to be used in URL parameterization. 451 | 452 | Logic based on https://github.com/MeltanoLabs/tap-github 453 | 454 | Args: 455 | context: optional - the singer context object. 456 | next_page_token: optional - the token for the next page of results. 457 | 458 | Returns: 459 | An object containing the parameters to add to the request. 460 | 461 | """ 462 | params: dict = {} 463 | if self.params: 464 | for k, v in self.params.items(): 465 | params[k] = v 466 | if self.pagination_page_size: 467 | pagination_page_size = self.pagination_page_size 468 | else: 469 | pagination_page_size = 25 # Default to 25 per page if not set 470 | if self.pagination_limit_per_page_param: 471 | limit_per_page_param = self.pagination_limit_per_page_param 472 | else: 473 | limit_per_page_param = "per_page" 474 | params[limit_per_page_param] = pagination_page_size 475 | if next_page_token: 476 | request_parameters = parse_qs(str(next_page_token)) 477 | for k, v in request_parameters.items(): 478 | params[k] = v 479 | 480 | if self.replication_key == "updated_at": 481 | params["sort"] = "updated" 482 | params["direction"] = "desc" if self.use_fake_since_parameter else "asc" 483 | 484 | # Unfortunately the /starred, /stargazers (starred_at) and /events (created_at) 485 | # endpoints do not support the "since" parameter out of the box. But we use a 486 | # workaround in 'get_next_page_token'. 487 | elif self.replication_key in ["starred_at", "created_at"]: 488 | params["sort"] = "created" 489 | params["direction"] = "desc" 490 | 491 | # Warning: /commits endpoint accept "since" but results are ordered by 492 | # descending commit_timestamp 493 | elif self.replication_key == "commit_timestamp": 494 | params["direction"] = "desc" 495 | 496 | elif self.replication_key: 497 | self.logger.warning( 498 | f"The replication key '{self.replication_key}' is not fully supported " 499 | f"by this client yet." 500 | ) 501 | 502 | since = self.get_starting_timestamp(context) 503 | since_key = "since" if not self.use_fake_since_parameter else "fake_since" 504 | if self.replication_key and since: 505 | params[since_key] = since 506 | # Leverage conditional requests to save API quotas 507 | # https://github.community/t/how-does-if-modified-since-work/139627 508 | self._http_headers["If-modified-since"] = email.utils.format_datetime(since) 509 | 510 | return params 511 | 512 | def _get_url_params_hateoas_body( 513 | self, context: Optional[dict], next_page_token: Optional[Any] 514 | ) -> Dict[str, Any]: 515 | """Return a dictionary of values to be used in URL parameterization. 516 | 517 | Args: 518 | context: optional - the singer context object. 519 | next_page_token: optional - the token for the next page of results. 520 | 521 | 522 | HATEOAS stands for "Hypermedia as the Engine of Application State". 523 | See https://en.wikipedia.org/wiki/HATEOAS. 524 | 525 | Note: Under the HATEOAS model, the returned token contains all the 526 | required parameters for the subsequent call. The function splits the 527 | parameters into Dict key value pairs for subsequent requests. 528 | 529 | Returns: 530 | An object containing the parameters to add to the request. 531 | 532 | """ 533 | # Initialise Starting Values 534 | last_run_date = get_start_date(self, context) 535 | params: dict = {} 536 | 537 | if self.params: 538 | for k, v in self.params.items(): 539 | params[k] = v 540 | 541 | # Set Pagination Limits if required. 542 | if self.pagination_page_size and self.pagination_limit_per_page_param: 543 | params[self.pagination_limit_per_page_param] = self.pagination_page_size 544 | 545 | if next_page_token: 546 | # Parse the next_page_token for the path and parameters 547 | url_parsed = urlparse(next_page_token) 548 | if url_parsed.query: 549 | params.update(parse_qsl(url_parsed.query)) 550 | else: 551 | params.update(parse_qsl(url_parsed.path)) 552 | if url_parsed.path == next_page_token: 553 | self.path = "" 554 | else: 555 | self.path = url_parsed.path 556 | elif self.replication_key: 557 | # Use incremental replication (if available) via a filter query being sent 558 | # to the API This assumes storing a replication timestamp and querying 559 | # records greater than that date in subsequent runs. Config the appropriate 560 | # source field and query template. 561 | if self.source_search_field and self.source_search_query and last_run_date: 562 | query_template = Template(self.source_search_query) 563 | if self.use_request_body_not_params: 564 | params[self.source_search_field] = json.loads( 565 | query_template.substitute(last_run_date=last_run_date) 566 | ) 567 | else: 568 | params[self.source_search_field] = query_template.substitute( 569 | last_run_date=last_run_date 570 | ) 571 | elif self.source_search_field and last_run_date: 572 | params[self.source_search_field] = "gt" + last_run_date 573 | 574 | return params 575 | 576 | def parse_response(self, response: requests.Response) -> Iterable[dict]: 577 | """Parse the response and return an iterator of result rows. 578 | 579 | Args: 580 | response: required - the requests.Response given by the api call. 581 | 582 | Yields: 583 | Parsed records. 584 | 585 | """ 586 | yield from extract_jsonpath(self.records_path, input=response.json()) 587 | 588 | def post_process( # noqa: PLR6301 589 | self, 590 | row: types.Record, 591 | context: Optional[types.Context] = None, # noqa: ARG002 592 | ) -> Optional[dict]: 593 | """As needed, append or transform raw data to match expected structure. 594 | 595 | Args: 596 | row: required - the record for processing. 597 | context: optional - the singer context object. 598 | 599 | Returns: 600 | A record that has been processed. 601 | 602 | """ 603 | return flatten_json(row, self.except_keys, self.store_raw_json_message) 604 | -------------------------------------------------------------------------------- /tap_rest_api_msdk/tap.py: -------------------------------------------------------------------------------- 1 | """rest-api tap class.""" 2 | 3 | import copy 4 | import json 5 | from typing import Any, List, Optional 6 | 7 | import requests 8 | from genson import SchemaBuilder 9 | from singer_sdk import Tap 10 | from singer_sdk import typing as th 11 | from singer_sdk.authenticators import APIAuthenticatorBase 12 | from singer_sdk.helpers.jsonpath import extract_jsonpath 13 | from tap_rest_api_msdk.auth import ConfigurableOAuthAuthenticator, get_authenticator 14 | from tap_rest_api_msdk.streams import DynamicStream 15 | from tap_rest_api_msdk.utils import flatten_json 16 | 17 | 18 | class TapRestApiMsdk(Tap): 19 | """rest-api tap class.""" 20 | 21 | name = "tap-rest-api-msdk" 22 | 23 | # Required for Authentication in tap.py - function APIAuthenticatorBase 24 | tap_name = name 25 | 26 | # Used to cache the Authenticator to prevent over hitting the Authentication 27 | # end-point for each stream. 28 | _authenticator: Optional[APIAuthenticatorBase] = None 29 | 30 | common_properties = th.PropertiesList( 31 | th.Property( 32 | "path", 33 | th.StringType, 34 | required=False, 35 | description="the path appended to the `api_url`. Stream-level path will " 36 | "overwrite top-level path", 37 | ), 38 | th.Property( 39 | "params", 40 | th.ObjectType(), 41 | default={}, 42 | required=False, 43 | description="an object providing the `params` in a `requests.get` method. " 44 | "Stream level params will be merged" 45 | "with top-level params with stream level params overwriting" 46 | "top-level params with the same key.", 47 | ), 48 | th.Property( 49 | "headers", 50 | th.ObjectType(), 51 | required=False, 52 | description="An object of headers to pass into the api calls. Stream level" 53 | "headers will be merged with top-level params with stream" 54 | "level params overwriting top-level params with the same key.", 55 | ), 56 | th.Property( 57 | "records_path", 58 | th.StringType, 59 | required=False, 60 | description="a jsonpath string representing the path in the requests " 61 | "response that contains the records to process. Defaults " 62 | "to `$[*]`. Stream level records_path will overwrite " 63 | "the top-level records_path", 64 | ), 65 | th.Property( 66 | "primary_keys", 67 | th.ArrayType(th.StringType), 68 | required=False, 69 | description="a list of the json keys of the primary key for the stream.", 70 | ), 71 | th.Property( 72 | "replication_key", 73 | th.StringType, 74 | required=False, 75 | description="the json response field representing the replication key." 76 | "Note that this should be an incrementing integer or datetime object.", 77 | ), 78 | th.Property( 79 | "except_keys", 80 | th.ArrayType(th.StringType), 81 | default=[], 82 | required=False, 83 | description="This tap automatically flattens the entire json structure " 84 | "and builds keys based on the corresponding paths.; Keys, " 85 | "whether composite or otherwise, listed in this dictionary " 86 | "will not be recursively flattened, but instead their values " 87 | "will be; turned into a json string and processed in that " 88 | "format. This is also automatically done for any lists within " 89 | "the records; therefore, records are not duplicated for each " 90 | "item in lists.", 91 | ), 92 | th.Property( 93 | "num_inference_records", 94 | th.NumberType, 95 | default=50, 96 | required=False, 97 | description="number of records used to infer the stream's schema. " 98 | "Defaults to 50.", 99 | ), 100 | th.Property( 101 | "start_date", 102 | th.DateTimeType, 103 | required=False, 104 | description="An optional field. Normally required when using the" 105 | "replication_key. This is the initial starting date when using a" 106 | "date based replication key and there is no state available.", 107 | ), 108 | th.Property( 109 | "source_search_field", 110 | th.StringType, 111 | required=False, 112 | description="An optional field name which can be used for querying " 113 | "specific records from supported API's. The intend for this " 114 | "parameter is to continue incrementally processing from a " 115 | "previous state. Example `last-updated`. Note: You must also " 116 | "set the replication_key, where the replication_key isjson " 117 | "response representation of the API `source_search_field`. " 118 | "You shouldalso supply the `source_search_query`, " 119 | "`replication_key` and `start_date`.", 120 | ), 121 | th.Property( 122 | "source_search_query", 123 | th.StringType, 124 | required=False, 125 | description="An optional query template to be issued against the API." 126 | "Substitute the query field you are querying against with " 127 | "$last_run_date. Atrun-time, the tap will dynamically update " 128 | "the token with either the `start_date`or the last bookmark / " 129 | "state value. A simple template Example for FHIR API's: " 130 | "gt$last_run_date. A more complex example against an " 131 | "Opensearch API, " 132 | '{"bool": {"filter": [{"range": ' 133 | '{ "meta.lastUpdated": { "gt": "$last_run_date" }}}] }} .' 134 | "Note: Any required double quotes in the query template must " 135 | "be escaped.", 136 | ), 137 | ) 138 | 139 | top_level_properties = th.PropertiesList( 140 | th.Property( 141 | "api_url", 142 | th.StringType, 143 | required=True, 144 | description="the base url/endpoint for the desired api", 145 | ), 146 | th.Property( 147 | "auth_method", 148 | th.StringType, 149 | default="no_auth", 150 | required=False, 151 | description="The method of authentication used by the API. Supported " 152 | "options include oauth: for OAuth2 authentication, basic: " 153 | "Basic Header authorization - base64-encoded username + " 154 | "password config items, api_key: for API Keys in the header " 155 | "e.g. X-API-KEY,bearer_token: for Bearer token authorization, " 156 | "aws: for AWS Authentication.Defaults to no_auth which will " 157 | "take authentication parameters passed via the headersconfig.", 158 | ), 159 | th.Property( 160 | "api_keys", 161 | th.ObjectType(), 162 | required=False, 163 | description="A object of API Key/Value pairs used by the api_key auth " 164 | "method Example: { X-API-KEY: my secret value}.", 165 | ), 166 | th.Property( 167 | "client_id", 168 | th.StringType, 169 | required=False, 170 | description="Used for the OAuth2 authentication method. The public " 171 | "application ID that's assigned for Authentication. The " 172 | "client_id should accompany a client_secret.", 173 | ), 174 | th.Property( 175 | "client_secret", 176 | th.StringType, 177 | required=False, 178 | description="Used for the OAuth2 authentication method. The client_secret " 179 | "is a secret known only to the application and the " 180 | "authorization server. It is essential the application's " 181 | "own password.", 182 | ), 183 | th.Property( 184 | "username", 185 | th.StringType, 186 | required=False, 187 | description="Used for a number of authentication methods that use a user " 188 | "password combination for authentication.", 189 | ), 190 | th.Property( 191 | "password", 192 | th.StringType, 193 | required=False, 194 | description="Used for a number of authentication methods that use a user " 195 | "password combination for authentication.", 196 | ), 197 | th.Property( 198 | "bearer_token", 199 | th.StringType, 200 | required=False, 201 | description="Used for the Bearer Authentication method, which uses a token " 202 | "as part of the authorization header for authentication.", 203 | ), 204 | th.Property( 205 | "refresh_token", 206 | th.StringType, 207 | required=False, 208 | description="An OAuth2 Refresh Token is a string that the OAuth2 " 209 | "client can use to get a new access token without the user's " 210 | "interaction.", 211 | ), 212 | th.Property( 213 | "grant_type", 214 | th.StringType, 215 | required=False, 216 | description="Used for the OAuth2 authentication method. The grant_type " 217 | "is required to describe the OAuth2 flow. Flows support by " 218 | "this tap include client_credentials, refresh_token, password.", 219 | ), 220 | th.Property( 221 | "scope", 222 | th.StringType, 223 | required=False, 224 | description="Used for the OAuth2 authentication method. The scope is " 225 | "optional, it is a mechanism to limit the amount of access " 226 | "that is granted to an access token. One or more scopes can " 227 | "be provided delimited by a space.", 228 | ), 229 | th.Property( 230 | "access_token_url", 231 | th.StringType, 232 | required=False, 233 | description="Used for the OAuth2 authentication method. This is the " 234 | "end-point for the authentication server used to exchange " 235 | "the authorization codes for a access token.", 236 | ), 237 | th.Property( 238 | "redirect_uri", 239 | th.StringType, 240 | required=False, 241 | description="Used for the OAuth2 authentication method. This is optional " 242 | "as the redirect_uri may be part of the token returned by " 243 | "the authentication server. If a redirect_uri is provided, " 244 | "it determines where the API server redirects the user after " 245 | "the user completes the authorization flow.", 246 | ), 247 | th.Property( 248 | "oauth_extras", 249 | th.ObjectType(), 250 | required=False, 251 | description="A object of Key/Value pairs for additional oauth config " 252 | "parameters which may be required by the authorization server." 253 | "Example: " 254 | "{resource: https://analysis.windows.net/powerbi/api}.", 255 | ), 256 | th.Property( 257 | "oauth_expiration_secs", 258 | th.IntegerType, 259 | default=None, 260 | required=False, 261 | description="Used for OAuth2 authentication method. This optional " 262 | "setting is a timer for the expiration of a token in " 263 | "seconds. If not set the OAuth will use the default " 264 | "expiration set in the token by the authorization server.", 265 | ), 266 | th.Property( 267 | "aws_credentials", 268 | th.ObjectType(), 269 | default=None, 270 | required=False, 271 | description="An object of aws credentials to authenticate to access AWS " 272 | "services. This example is to access the AWS OpenSearch " 273 | "service. Example: { aws_access_key_id: my_aws_key_id, " 274 | "aws_secret_access_key: my_aws_secret_access_key, " 275 | "aws_region: us-east-1, " 276 | "aws_service: es, use_signed_credentials: true} ", 277 | ), 278 | th.Property( 279 | "next_page_token_path", 280 | th.StringType, 281 | default=None, 282 | required=False, 283 | description="a jsonpath string representing the path to the 'next page' " 284 | "token. Defaults to `$.next_page`", 285 | ), 286 | th.Property( 287 | "pagination_request_style", 288 | th.StringType, 289 | default="default", 290 | required=False, 291 | description="the pagination style to use for requests. " 292 | "Defaults to `default`", 293 | ), 294 | th.Property( 295 | "pagination_response_style", 296 | th.StringType, 297 | default="default", 298 | required=False, 299 | description="the pagination style to use for response. " 300 | "Defaults to `default`", 301 | ), 302 | th.Property( 303 | "use_request_body_not_params", 304 | th.BooleanType, 305 | default=False, 306 | required=False, 307 | description="sends the request parameters in the request body." 308 | "This is normally not required, a few API's like OpenSearch" 309 | "require this. Defaults to `False`", 310 | ), 311 | th.Property( 312 | "backoff_type", 313 | th.StringType, 314 | default=None, 315 | required=False, 316 | allowed_values=[None, "message", "header"], 317 | description="The style of Backoff applied to rate limited APIs." 318 | "None: Default Meltano SDK backoff_wait_generator, message: Scans " 319 | "the response message for a time interval, header: retrieves the " 320 | "backoff value from a header key response." 321 | " Defaults to `None`", 322 | ), 323 | th.Property( 324 | "backoff_param", 325 | th.StringType, 326 | default="Retry-After", 327 | required=False, 328 | description="The name of the key which contains a the " 329 | "backoff value in the response. This is very applicable to backoff" 330 | " values in headers. Defaults to `Retry-After`", 331 | ), 332 | th.Property( 333 | "backoff_time_extension", 334 | th.IntegerType, 335 | default=0, 336 | required=False, 337 | description="A time extension (in seconds) to add to the backoff " 338 | "value from the API plus jitter. Some APIs are not precise" 339 | ", this adds an additional wait delay. Defaults to `0`", 340 | ), 341 | th.Property( 342 | "store_raw_json_message", 343 | th.BooleanType, 344 | default=False, 345 | required=False, 346 | description="Adds an additional _SDC_RAW_JSON column as an " 347 | "object. This will store the raw incoming message in this " 348 | "column when provisioned. Useful for semi-structured records " 349 | "when the schema is not well defined. Defaults to `False`", 350 | ), 351 | th.Property( 352 | "pagination_page_size", 353 | th.IntegerType, 354 | default=None, 355 | required=False, 356 | description="the size of each page in records. Defaults to None", 357 | ), 358 | th.Property( 359 | "pagination_results_limit", 360 | th.IntegerType, 361 | default=None, 362 | required=False, 363 | description="limits the max number of records. Defaults to None", 364 | ), 365 | th.Property( 366 | "pagination_next_page_param", 367 | th.StringType, 368 | default=None, 369 | required=False, 370 | description="The name of the param that indicates the page/offset. " 371 | "Defaults to None", 372 | ), 373 | th.Property( 374 | "pagination_limit_per_page_param", 375 | th.StringType, 376 | default=None, 377 | required=False, 378 | description="The name of the param that indicates the limit/per_page. " 379 | "Defaults to None", 380 | ), 381 | th.Property( 382 | "pagination_total_limit_param", 383 | th.StringType, 384 | default="total", 385 | required=False, 386 | description="The name of the param that indicates the total limit e.g. " 387 | "total, count. Defaults to total", 388 | ), 389 | th.Property( 390 | "pagination_initial_offset", 391 | th.IntegerType, 392 | default=1, 393 | required=False, 394 | description="The initial offset to start pagination from. Defaults to 1", 395 | ), 396 | th.Property( 397 | "offset_records_jsonpath", 398 | th.StringType, 399 | default=None, 400 | required=False, 401 | description="Optional jsonpath string representing the path in the results " 402 | "Defaults to `None`.", 403 | ), 404 | ) 405 | 406 | # add common properties to top-level properties 407 | for prop in common_properties.wrapped.values(): 408 | top_level_properties.append(prop) 409 | 410 | # add common properties to the stream schema 411 | stream_properties = th.PropertiesList() 412 | stream_properties.wrapped = copy.copy(common_properties.wrapped) 413 | stream_properties.append( 414 | th.Property( 415 | "name", th.StringType, required=True, description="name of the stream" 416 | ), 417 | ) 418 | stream_properties.append( 419 | th.Property( 420 | "schema", 421 | th.CustomType( 422 | {"anyOf": [{"type": "string"}, {"type": "null"}, {"type:": "object"}]} 423 | ), 424 | required=False, 425 | description="A valid Singer schema or a path-like string that provides " 426 | "the path to a `.json` file that contains a valid Singer " 427 | "schema. If provided, the schema will not be inferred from " 428 | "the results of an api call.", 429 | ), 430 | ) 431 | 432 | # add streams schema to top-level properties 433 | top_level_properties.append( 434 | th.Property( 435 | "streams", 436 | th.ArrayType(th.ObjectType(*stream_properties.wrapped.values())), 437 | required=False, 438 | description="An array of streams, designed for separate paths using the" 439 | "same base url.", 440 | ), 441 | ) 442 | 443 | config_jsonschema = top_level_properties.to_dict() 444 | 445 | def discover_streams(self) -> List[DynamicStream]: # type: ignore 446 | """Return a list of discovered streams. 447 | 448 | Returns: 449 | A list of streams. 450 | 451 | """ 452 | # print(self.top_level_properties.to_dict()) 453 | 454 | streams = [] 455 | for stream in self.config["streams"]: 456 | # resolve config 457 | records_path = stream.get( 458 | "records_path", self.config.get("records_path", "$[*]") 459 | ) 460 | except_keys = stream.get("except_keys", self.config.get("except_keys", [])) 461 | path = stream.get("path", self.config.get("path", "")) 462 | params = {**self.config.get("params", {}), **stream.get("params", {})} 463 | headers = {**self.config.get("headers", {}), **stream.get("headers", {})} 464 | start_date = stream.get("start_date", self.config.get("start_date", "")) 465 | replication_key = stream.get( 466 | "replication_key", self.config.get("replication_key", "") 467 | ) 468 | source_search_field = stream.get( 469 | "source_search_field", self.config.get("source_search_field", "") 470 | ) 471 | source_search_query = stream.get( 472 | "source_search_query", self.config.get("source_search_query", "") 473 | ) 474 | offset_records_jsonpath = stream.get( 475 | "offset_records_jsonpath", 476 | self.config.get("offset_records_jsonpath", None), 477 | ) 478 | 479 | schema = {} 480 | schema_config = stream.get("schema") 481 | if isinstance(schema_config, str): 482 | self.logger.info("Found path to a schema, not doing discovery.") 483 | with open(schema_config, "r") as f: 484 | schema = json.load(f) 485 | 486 | elif isinstance(schema_config, dict): 487 | self.logger.info("Found schema in config, not doing discovery.") 488 | builder = SchemaBuilder() 489 | builder.add_schema(schema_config) 490 | schema = builder.to_schema() 491 | 492 | else: 493 | self.logger.info("No schema found. Inferring schema from API call.") 494 | schema = self.get_schema( 495 | records_path, 496 | except_keys, 497 | stream.get( 498 | "num_inference_records", 499 | self.config["num_inference_records"], 500 | ), 501 | path, 502 | params, 503 | headers, 504 | ) 505 | 506 | streams.append( 507 | DynamicStream( 508 | tap=self, 509 | name=stream["name"], 510 | path=path, 511 | params=params, 512 | headers=headers, 513 | records_path=records_path, 514 | primary_keys=stream.get( 515 | "primary_keys", self.config.get("primary_keys", []) 516 | ), 517 | replication_key=replication_key, 518 | except_keys=except_keys, 519 | next_page_token_path=self.config.get("next_page_token_path"), 520 | pagination_request_style=self.config["pagination_request_style"], 521 | pagination_response_style=self.config["pagination_response_style"], 522 | pagination_page_size=self.config.get("pagination_page_size"), 523 | pagination_results_limit=self.config.get( 524 | "pagination_results_limit" 525 | ), 526 | pagination_next_page_param=self.config.get( 527 | "pagination_next_page_param" 528 | ), 529 | pagination_limit_per_page_param=self.config.get( 530 | "pagination_limit_per_page_param" 531 | ), 532 | pagination_total_limit_param=self.config.get( 533 | "pagination_total_limit_param" 534 | ), 535 | pagination_initial_offset=self.config.get( 536 | "pagination_initial_offset", 537 | 1, 538 | ), 539 | offset_records_jsonpath=offset_records_jsonpath, 540 | schema=schema, 541 | start_date=start_date, 542 | source_search_field=source_search_field, 543 | source_search_query=source_search_query, 544 | use_request_body_not_params=self.config.get( 545 | "use_request_body_not_params" 546 | ), 547 | backoff_type=self.config.get("backoff_type"), 548 | backoff_param=self.config.get("backoff_param"), 549 | backoff_time_extension=self.config.get("backoff_time_extension"), 550 | store_raw_json_message=self.config.get("store_raw_json_message"), 551 | authenticator=self._authenticator, 552 | ) 553 | ) 554 | 555 | return streams 556 | 557 | def get_schema( 558 | self, 559 | records_path: str, 560 | except_keys: list, 561 | inference_records: int, 562 | path: str, 563 | params: dict, 564 | headers: dict, 565 | ) -> Any: 566 | """Infer schema from the first records returned by api. Creates a Stream object. 567 | 568 | If auth_method is set, will call get_authenticator to obtain credentials 569 | to issue a request to sample some records. The get_authenticator will: 570 | - stores the authenticator in self._authenticator 571 | - sets the self.http_auth if required by a given authenticator 572 | - use an existing authenticator if one exists and is cached. 573 | 574 | Args: 575 | records_path: required - see config_jsonschema. 576 | except_keys: required - see config_jsonschema. 577 | inference_records: required - see config_jsonschema. 578 | path: required - see config_jsonschema. 579 | params: required - see config_jsonschema. 580 | headers: required - see config_jsonschema. 581 | 582 | Raises: 583 | ValueError: if the response is not valid or a record is not valid json. 584 | 585 | Returns: 586 | A schema for the stream. 587 | 588 | """ 589 | # TODO: this request format is not very robust 590 | 591 | # Initialise Variables 592 | auth_method = self.config.get("auth_method", "") 593 | self.http_auth = None 594 | 595 | if auth_method and not auth_method == "no_auth": 596 | # Obtaining Authenticator for authorisation to obtain a schema. 597 | get_authenticator(self) 598 | 599 | # Get an initial oauth token if an oauth method 600 | if auth_method == "oauth" and isinstance( 601 | self._authenticator, ConfigurableOAuthAuthenticator 602 | ): 603 | self._authenticator.get_initial_oauth_token() 604 | 605 | headers.update(getattr(self._authenticator, "auth_headers", {})) 606 | params.update(getattr(self._authenticator, "auth_params", {})) 607 | 608 | r = requests.get( 609 | self.config["api_url"] + path, 610 | auth=self.http_auth, 611 | params=params, 612 | headers=headers, 613 | ) 614 | if r.ok: 615 | records = extract_jsonpath(records_path, input=r.json()) 616 | else: 617 | self.logger.error(f"Error Connecting, message = {r.text}") 618 | raise ValueError(r.text) 619 | 620 | builder = SchemaBuilder() 621 | builder.add_schema(th.PropertiesList().to_dict()) 622 | for i, record in enumerate(records): 623 | if type(record) is not dict: 624 | self.logger.error("Input must be a dict object.") 625 | raise ValueError("Input must be a dict object.") 626 | 627 | flat_record = flatten_json( 628 | record, except_keys, store_raw_json_message=False 629 | ) 630 | 631 | builder.add_object(flat_record) 632 | # Optional add _sdc_raw_json field to store the raw message 633 | if self.config.get("store_raw_json_message"): 634 | builder.add_object({"_sdc_raw_json": {}}) 635 | 636 | if i >= inference_records: 637 | break 638 | 639 | self.logger.debug(f"{builder.to_json(indent=2)}") 640 | return builder.to_schema() 641 | -------------------------------------------------------------------------------- /tap_rest_api_msdk/utils.py: -------------------------------------------------------------------------------- 1 | """Basic utility functions.""" 2 | 3 | import json 4 | from typing import Any, Optional 5 | 6 | 7 | def flatten_json( 8 | obj: dict, 9 | except_keys: Optional[list] = None, 10 | store_raw_json_message: Optional[bool] = False, 11 | ) -> dict: 12 | """Flattens a json object by appending the patch as a key in the returned object. 13 | 14 | Automatically converts arrays and any provided keys into json strings to prevent 15 | flattening further into those branches. 16 | 17 | Args: 18 | obj: the json object to be flattened. 19 | except_keys: list of the keys of the nodes that should be converted to json 20 | strings. 21 | store_raw_json_message: Additionally adds the raw JSON message to a field 22 | named _sdc_raw_json. Note: The field is a JSON type of object. 23 | 24 | Returns: 25 | A flattened json object. 26 | 27 | """ 28 | out = {} 29 | if not except_keys: 30 | except_keys = [] 31 | 32 | def t(s: str) -> str: 33 | """Translate a string to db friendly column names. 34 | 35 | Args: 36 | s: required - string to make a translation table from. 37 | 38 | Returns: 39 | Translation table. 40 | 41 | """ 42 | translation_table = s.maketrans("-.", "__") 43 | return s.translate(translation_table) 44 | 45 | def flatten(o: Any, exception_keys: list, name: str = "") -> None: 46 | """Recursive flattening of the json object in place. 47 | 48 | Args: 49 | o: the json object to be flattened. 50 | exception_keys: list of the keys of the nodes that should 51 | be converted to json strings. 52 | name: the prefix for the exception_keys 53 | 54 | """ 55 | if type(o) is dict: 56 | for k in o: 57 | # the key is in the list of keys to skip, convert to json string 58 | if name + k in exception_keys: 59 | out[t(name + k)] = json.dumps(o[k]) 60 | else: 61 | flatten(o[k], exception_keys, name + k + "_") 62 | 63 | # if the object is an array, convert to a json string 64 | elif type(o) is list: 65 | out[t(name[:-1])] = json.dumps(o) 66 | 67 | # otherwise, translate the key to be database friendly 68 | else: 69 | out[t(name[:-1])] = o 70 | 71 | flatten(obj, exception_keys=except_keys) 72 | # Optional store the whole row in the _sdc_raw_json field. 73 | if store_raw_json_message: 74 | out["_sdc_raw_json"] = obj # type: ignore[assignment] 75 | return out 76 | 77 | 78 | def unnest_dict(d): 79 | """Flattens a dict object by create a new object with the key value pairs. 80 | 81 | Recursive flattening any nested dicts to a single level. 82 | 83 | Args: 84 | obj: the dict object to be flattened. 85 | 86 | Returns: 87 | A flattened dict object. 88 | 89 | """ 90 | result = {} 91 | for k, v in d.items(): 92 | if isinstance(v, dict): 93 | result.update(unnest_dict(v)) 94 | else: 95 | result[k] = v 96 | return result 97 | 98 | 99 | def get_start_date(self, context: Optional[dict]) -> Any: 100 | """Return a start date if a DateTime bookmark is available. 101 | 102 | Otherwise it returns the starting date as defined in 103 | the start_date parameter. 104 | 105 | Args: 106 | context: - the singer context object. 107 | 108 | Returns: 109 | An start date else and empty string. 110 | 111 | """ 112 | try: 113 | return self.get_starting_timestamp(context).strftime("%Y-%m-%dT%H:%M:%S") 114 | except (ValueError, AttributeError): 115 | return self.get_starting_replication_key_value(context) 116 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | """Test suite for tap-rest-api-msdk.""" 2 | -------------------------------------------------------------------------------- /tests/schema.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json-schema.org/schema#", 3 | "type": "object", 4 | "properties": { 5 | "key1": { 6 | "type": "string" 7 | }, 8 | "key2": { 9 | "type": "string" 10 | }, 11 | "key3": { 12 | "type": "string" 13 | }, 14 | "field1": { 15 | "type": "string" 16 | }, 17 | "field2": { 18 | "type": "integer" 19 | } 20 | }, 21 | "required": [ 22 | "key1", 23 | "key2", 24 | "key3" 25 | ] 26 | } 27 | -------------------------------------------------------------------------------- /tests/test_core.py: -------------------------------------------------------------------------------- 1 | """Tests standard tap features using the built-in SDK tests library.""" 2 | 3 | from singer_sdk.testing import get_tap_test_class 4 | from tap_rest_api_msdk.tap import TapRestApiMsdk 5 | 6 | from tests.test_streams import config, json_resp, url_path 7 | 8 | 9 | # Run standard built-in tap tests from the SDK: 10 | def test_standard_tap_tests(requests_mock): 11 | """Run standard tap tests from the SDK.""" 12 | requests_mock.get(url_path(), json=json_resp()) 13 | get_tap_test_class(TapRestApiMsdk, config=config()) 14 | -------------------------------------------------------------------------------- /tests/test_streams.py: -------------------------------------------------------------------------------- 1 | """Tests stream.py features.""" 2 | 3 | from typing import Any 4 | 5 | import requests 6 | from tap_rest_api_msdk.tap import TapRestApiMsdk 7 | 8 | 9 | def config(extras: dict = None) -> dict: 10 | """Utility function giving a basic/common config for streams. 11 | 12 | Args: 13 | extras: items to add to the basic config. 14 | 15 | Returns: 16 | A complete tap config. 17 | """ 18 | contents = { 19 | "api_url": "https://example.com", 20 | "streams": [ 21 | { 22 | "name": "stream_name", 23 | "path": "/path_test", 24 | "primary_keys": ["key1", "key2"], 25 | "replication_key": "key3", 26 | "records_path": "$.records[*]", 27 | } 28 | ], 29 | } 30 | if extras: 31 | for k, v in extras.items(): 32 | contents[k] = v 33 | return contents 34 | 35 | 36 | def json_resp(extras: dict = None) -> dict: 37 | """Utility function returning a common response for mocked API calls. 38 | 39 | Args: 40 | extras: items to be added to the contents of the json response. 41 | 42 | Returns: 43 | A json object that mocks the results of an API call. 44 | """ 45 | contents = { 46 | "records": [ 47 | { 48 | "key1": "this", 49 | "key2": "that", 50 | "key3": "foo", 51 | "field1": "I", 52 | }, 53 | {"key1": "foo", "key2": "bar", "key3": "spam", "field2": 8}, 54 | ], 55 | } 56 | if extras: 57 | for k, v in extras.items(): 58 | contents[k] = v 59 | return contents 60 | 61 | 62 | def url_path(path: str = "/path_test") -> str: 63 | """Utility function returning a common url for mocked API calls. 64 | 65 | Args: 66 | path: a path to add to the end of the base url. 67 | 68 | Returns: 69 | A full url. 70 | """ 71 | return "https://example.com" + path 72 | 73 | 74 | def setup_api( 75 | requests_mock: Any, 76 | url_path: str = url_path(), 77 | json_extras: dict = None, 78 | headers_extras: dict = None, 79 | matcher: Any = None, 80 | ) -> requests.Response: 81 | """Utility function for mocking API calls. 82 | 83 | Args: 84 | requests_mock: mock object for requests. 85 | url_path: url to mack for mocking. 86 | json_extras: extra items to add to the response's results. 87 | headers_extras: extra items to add to the API call's header. 88 | matcher: a function that checks a request's input for the appropriate 89 | configuration. 90 | 91 | Returns: 92 | A mocked requests.Response object. 93 | """ 94 | headers_resp = {} 95 | if headers_extras: 96 | for k, v in headers_extras.items(): 97 | headers_resp[k] = v 98 | 99 | requests_mock.get( 100 | url_path, 101 | headers=headers_resp, 102 | json=json_resp(json_extras), 103 | additional_matcher=matcher, 104 | ) 105 | return requests.Session().get(url_path) 106 | 107 | 108 | def test_pagination_style_default(requests_mock): 109 | def first_matcher(request): 110 | return "page" not in request.url 111 | 112 | def second_matcher(request): 113 | return "page=next_page_token" in request.url 114 | 115 | requests_mock.get( 116 | url_path(), 117 | additional_matcher=first_matcher, 118 | json=json_resp({"next_page": "next_page_token"}), 119 | ) 120 | requests_mock.get(url_path(), additional_matcher=second_matcher, json=json_resp()) 121 | 122 | stream0 = TapRestApiMsdk(config=config(), parse_env_config=True).discover_streams()[ 123 | 0 124 | ] 125 | records_gen = stream0.get_records({}) 126 | records = [] 127 | for record in records_gen: 128 | records.append(record) 129 | 130 | assert records == [ 131 | json_resp()["records"][0], 132 | json_resp()["records"][1], 133 | json_resp()["records"][0], 134 | json_resp()["records"][1], 135 | ] 136 | -------------------------------------------------------------------------------- /tests/test_tap.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | from tap_rest_api_msdk.tap import TapRestApiMsdk 4 | 5 | from tests.test_streams import config, setup_api 6 | 7 | with open("tests/schema.json", "r") as f: 8 | BASIC_SCHEMA = json.load(f) 9 | 10 | 11 | def test_schema_inference(requests_mock): 12 | setup_api(requests_mock) 13 | 14 | stream0 = TapRestApiMsdk(config=config(), parse_env_config=True).discover_streams()[ 15 | 0 16 | ] 17 | 18 | assert stream0.schema == BASIC_SCHEMA 19 | 20 | 21 | def test_schema_from_file(): 22 | configs = config() 23 | configs["streams"][0]["schema"] = "tests/schema.json" 24 | 25 | s0 = TapRestApiMsdk(config=configs, parse_env_config=True).discover_streams()[0] 26 | 27 | assert s0.schema == BASIC_SCHEMA 28 | 29 | 30 | def test_schema_from_object(): 31 | configs = config() 32 | configs["streams"][0]["schema"] = BASIC_SCHEMA 33 | 34 | s0 = TapRestApiMsdk(config=configs, parse_env_config=True).discover_streams()[0] 35 | 36 | assert s0.schema == BASIC_SCHEMA 37 | 38 | 39 | def test_multiple_streams(requests_mock): 40 | setup_api(requests_mock) 41 | setup_api(requests_mock, url_path="https://example.com/path_test2") 42 | configs = config({"records_path": "$.records[*]"}) 43 | configs["streams"].append( 44 | { 45 | "name": "stream_name2", 46 | "path": "/path_test2", 47 | "primary_keys": ["key4", "key5"], 48 | "replication_key": "key6", 49 | } 50 | ) 51 | 52 | streams = TapRestApiMsdk(config=configs, parse_env_config=True).discover_streams() 53 | 54 | assert streams[0].name == "stream_name" 55 | assert streams[0].records_path == "$.records[*]" 56 | assert streams[0].path == "/path_test" 57 | assert streams[0].primary_keys == ["key1", "key2"] 58 | assert streams[0].replication_key == "key3" 59 | assert streams[1].name == "stream_name2" 60 | assert streams[1].records_path == "$.records[*]" 61 | assert streams[1].path == "/path_test2" 62 | assert streams[1].primary_keys == ["key4", "key5"] 63 | assert streams[1].replication_key == "key6" 64 | -------------------------------------------------------------------------------- /tests/test_utils.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | from tap_rest_api_msdk.utils import flatten_json 4 | 5 | 6 | def test_flatten_json(): 7 | d = { 8 | "a": 1, 9 | "b": {"a": 2, "b": {"a": 3}, "c": {"a": "bacon", "b": "yum"}}, 10 | "c": [{"foo": "bar"}, {"eggs": "spam"}], 11 | "d": [4, 5], 12 | "e.-f": 6, 13 | } 14 | ret = flatten_json(d, except_keys=["b_c"]) 15 | assert ret["a"] == 1 16 | assert ret["b_a"] == 2 17 | assert ret["b_b_a"] == 3 18 | assert ret["b_c"] == json.dumps({"a": "bacon", "b": "yum"}) 19 | assert ret["c"] == json.dumps([{"foo": "bar"}, {"eggs": "spam"}]) 20 | assert ret["d"] == json.dumps([4, 5]) 21 | assert ret["e__f"] == 6 22 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | # This file can be used to customize dox tests as well as other test frameworks like flake8 and mypy 2 | 3 | [tox] 4 | envlist = py38 5 | ; envlist = py36, py38, py39 6 | isolated_build = true 7 | 8 | [testenv] 9 | allowlist_externals = poetry 10 | 11 | commands = 12 | poetry install -v 13 | poetry run pytest 14 | poetry run black --check tap_rest_api_msdk/ tests/ 15 | poetry run isort --check tap_rest_api_msdk/ tests/ 16 | poetry run flake8 tap_rest_api_msdk/ tests/ 17 | poetry run mypy tap_rest_api_msdk/ 18 | poetry run pydocstyle tap_rest_api_msdk/ tests/ 19 | 20 | 21 | [flake8] 22 | ignore = W503, C901, ANN101 23 | max-line-length = 88 24 | per-file-ignores = 25 | # Don't require docstrings or type annotations in tests 26 | tests/*:D100,D102,D103,DAR,ANN 27 | max-complexity = 10 28 | docstring-convention = google 29 | 30 | [pydocstyle] 31 | ignore = D105,D107,D203,D213,D406,D407 32 | --------------------------------------------------------------------------------