From f102eb68f9b7e3c99b2ae102e1962116636375fe Mon Sep 17 00:00:00 2001 From: Jessica Matsuoka Date: Mon, 21 Apr 2025 19:13:09 +0200 Subject: [PATCH 1/4] DEVEXP-785: Numbers API - Quickstart --- .github/workflows/run_linter.yaml | 26 +++ .gitignore | 132 ++++++++++++ LICENSE | 201 ++++++++++++++++++ README.md | 9 + config.ini | 13 ++ setup.py | 12 ++ templates/__init__.py | 0 templates/client/README.md | 58 +++++ templates/client/__init__.py | 0 templates/client/src/__init__.py | 0 templates/client/src/app.py | 16 ++ templates/client/src/numbers_api/__init__.py | 0 .../src/numbers_api/numbers_quickstart.py | 7 + templates/client/src/numbers_api/snippet.py | 35 +++ templates/server/README.md | 89 ++++++++ templates/server/__init__.py | 0 templates/server/src/__init__.py | 0 .../server/src/numbers_api/controller.py | 29 +++ templates/server/src/server.py | 24 +++ templates/utils/__init__.py | 3 + templates/utils/sinch_client_helper.py | 57 +++++ 21 files changed, 711 insertions(+) create mode 100644 .github/workflows/run_linter.yaml create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 config.ini create mode 100644 setup.py create mode 100644 templates/__init__.py create mode 100644 templates/client/README.md create mode 100644 templates/client/__init__.py create mode 100644 templates/client/src/__init__.py create mode 100644 templates/client/src/app.py create mode 100644 templates/client/src/numbers_api/__init__.py create mode 100644 templates/client/src/numbers_api/numbers_quickstart.py create mode 100644 templates/client/src/numbers_api/snippet.py create mode 100644 templates/server/README.md create mode 100644 templates/server/__init__.py create mode 100644 templates/server/src/__init__.py create mode 100644 templates/server/src/numbers_api/controller.py create mode 100644 templates/server/src/server.py create mode 100644 templates/utils/__init__.py create mode 100644 templates/utils/sinch_client_helper.py diff --git a/.github/workflows/run_linter.yaml b/.github/workflows/run_linter.yaml new file mode 100644 index 0000000..265fdfd --- /dev/null +++ b/.github/workflows/run_linter.yaml @@ -0,0 +1,26 @@ +name: Test Python SDK + +on: + push: + branches: + - "main" + pull_request: + branches: [ main ] + + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - name: Set up Python + uses: actions/setup-python@v2 + with: + python-version: 3.11 + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install flake8 + - name: Lint with flake8 + run: | + flake8 */ --count --max-complexity=10 --max-line-length=120 --statistics \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e79cdc6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,132 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +.idea/ + +# Poetry +poetry.lock \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f49a4e1 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/README.md b/README.md index 6e88cd1..59ef1eb 100644 --- a/README.md +++ b/README.md @@ -2,3 +2,12 @@ This repository provides templates to help you get started with the [Sinch Python SDK](https://github.com/sinch/sinch-sdk-python). + +## Contents + + - [templates](./templates): Executable code samples with predefined placeholders. Insert your own snippets +into the designated sections to test your code using the Sinch APIs. + - client: Examples that show how to make API calls using the Sinch Client + - [Numbers API](./templates/client/src/numbers_api) + - server: Examples for handling events triggered by Sinch services. + - [Numbers API](./templates/server/src/numbers_api) \ No newline at end of file diff --git a/config.ini b/config.ini new file mode 100644 index 0000000..131a2ca --- /dev/null +++ b/config.ini @@ -0,0 +1,13 @@ +# Credentials used by Numbers API +[CREDENTIALS] +SINCH_PROJECT_ID = PROJECT_ID +SINCH_KEY_ID = SINCH_KEY_ID +SINCH_KEY_SECRET = SINCH_KEY_SECRET + +[CONFIG] +SERVER_PORT = 3001 + +[WEBHOOK] +# The secret value used for webhook calls validation +# See https://developers.sinch.com/docs/numbers/api-reference/numbers/tag/Numbers-Callbacks/ +NUMBERS_WEBHOOKS_SECRET = webhook_secret diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..e55902e --- /dev/null +++ b/setup.py @@ -0,0 +1,12 @@ +from setuptools import setup, find_packages + +setup( + name="sinch-sdk-python-quickstart", + version="0.1.0", + packages=find_packages(), + install_requires=[ + # TODO: Add 'sinch' after v2.0 release. + "flask" + ], + python_requires=">=3.9", +) \ No newline at end of file diff --git a/templates/__init__.py b/templates/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/templates/client/README.md b/templates/client/README.md new file mode 100644 index 0000000..0edd7b3 --- /dev/null +++ b/templates/client/README.md @@ -0,0 +1,58 @@ +# Client Application Using the Sinch Python SDK + +This directory provides a Python client application built with the +[Sinch Python SDK](https://github.com/sinch/sinch-sdk-python). +It allows you to integrate Sinch APIs into your Python applications easily. + +## Prerequisites + +Before you being, ensure you have: + - [Python](https://www.python.org/) installed (versions 3.9 to 3.12 recommended). + - A [Sinch account](https://dashboard.sinch.com/) with access to the APIs you want to use. + +## Configuration + +To configure the client application: + +1. **Environment Variables**: + Edit the [config.ini](config.ini) file, adding your credentials from the Sinch dashboard under the Access Keys section. + - To use [Numbers](https://developers.sinch.com/docs/numbers/) you need to fill the following variables with the values from your Sinch account: + ``` + [CREDENTIALS] + - SINCH_PROJECT_ID=Your Sinch Project ID + - SINCH_KEY_ID=Your Sinch Access Key ID + - SINCH_KEY_SECRET=Your Sinch Key Secret associated to your Sinch Access Key + ``` + +2. **API Integration**: + The application demonstrates usage via modular snippets in `client/src/numbers_api/snippet.py`, which acts as the + main integration point for testing Sinch Numbers API endpoints. Replace the existing logic with your own, based on + the desired API functionality. + + You can explore and adapt examples from [Python SDK snippets repository.](https://github.com/sinch/sinch-sdk-python-snippets) directly into the `execute(sinch_client)` function: + - Choose a snippet + - Copy only the functional logic, skipping the `SinchClient` initialization as + this is already set up in the project. + - Paste it into the `execute(sinch_client)` function in `snippet.py`. + + +## Usage + +1. Navigate to the project's root directory in your terminal. + ``` + cd /path/to/sinch-sdk-python-quickstart + ``` +2. (Recommended) Create a virtual environment: + ``` bash + python -m venv venv + source venv/bin/activate + # On Windows use `venv\Scripts\activate` + ``` +3. Install the project dependencies: + ``` + pip install -e . + ``` +4. Ensure your `config.ini` file have been updated as described above. +5. Run the application: + - `python app.py` + Or run it directly from your IDE. diff --git a/templates/client/__init__.py b/templates/client/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/templates/client/src/__init__.py b/templates/client/src/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/templates/client/src/app.py b/templates/client/src/app.py new file mode 100644 index 0000000..f0f9547 --- /dev/null +++ b/templates/client/src/app.py @@ -0,0 +1,16 @@ +from templates.client.src.numbers_api.numbers_quickstart import NumbersQuickstart +from templates.utils import get_sinch_client, load_config + + +def main(): + config = load_config() + sinch_client = get_sinch_client(config) + + try: + NumbersQuickstart(sinch_client) + except Exception as e: + print(f'Error: {e}') + + +if __name__ == '__main__': + main() diff --git a/templates/client/src/numbers_api/__init__.py b/templates/client/src/numbers_api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/templates/client/src/numbers_api/numbers_quickstart.py b/templates/client/src/numbers_api/numbers_quickstart.py new file mode 100644 index 0000000..a138a6f --- /dev/null +++ b/templates/client/src/numbers_api/numbers_quickstart.py @@ -0,0 +1,7 @@ +from templates.client.src.numbers_api.snippet import execute + + +class NumbersQuickstart: + def __init__(self, sinch_client): + self.sinch_client = sinch_client + execute(self.sinch_client) diff --git a/templates/client/src/numbers_api/snippet.py b/templates/client/src/numbers_api/snippet.py new file mode 100644 index 0000000..1727b5f --- /dev/null +++ b/templates/client/src/numbers_api/snippet.py @@ -0,0 +1,35 @@ +# Replace the code below with any snippet from: +# https://github.com/sinch/sinch-sdk-python-snippets +def execute(sinch_client): + print("Snippet execution: Numbers service") + + +# Example usage: +# Let's say you're using the snippet from snippets/available_regions/list/snippet.py: +# +# from sinch import SinchClient +# +# sinch_client = SinchClient( +# project_id="YOUR_PROJECT_ID", +# key_id="KEY_ID", +# key_secret="KEY_SECRET" +# ) +# +# available_regions = sinch_client.numbers.regions.list( +# number_types=["MOBILE"] +# ) +# +# print("Available regions:\n") +# for region in available_regions.iterator(): +# print(region) + +# You extract the logic and place it inside the `execute` function like so: +# +# def execute(sinch_client): +# available_regions = sinch_client.numbers.regions.list( +# number_types=["MOBILE"] +# ) +# +# print("Available regions:\n") +# for region in available_regions.iterator(): +# print(region) diff --git a/templates/server/README.md b/templates/server/README.md new file mode 100644 index 0000000..ef21609 --- /dev/null +++ b/templates/server/README.md @@ -0,0 +1,89 @@ +# Backend application built using Sinch Python SDK for Webhook Handling + +This directory contains a server application built with [Sinch Python SDK](https://github.com/sinch/sinch-sdk-python) +to process incoming webhooks. + +## Requirements + +- [Python 3.9+](https://www.python.org/) +- [Flask]() +- [Sinch account](https://dashboard.sinch.com/) +- [ngrok](https://ngrok.com/docs) + +## Configuration + +1. **Environment Variables**: + Edit the [config.ini](config.ini) file, adding your credentials from the Sinch dashboard under the Access Keys section. + - To use [Numbers](https://developers.sinch.com/docs/numbers/) you need to fill the following variables + with the values from your Sinch account: + ``` + - SINCH_PROJECT_ID=Your Sinch Project ID + - SINCH_KEY_ID=Your Sinch Access Key ID + - SINCH_KEY_SECRET=Your Sinch Key Secret associated to your Sinch Access Key + ``` + - Server Port + Define the port your server will listen on: + ``` + - SERVER_PORT=3001 + ``` + - Controller Settings + - Numbers controller: Set the webhook secret, which you can retrieve from the [Numbers API](https://developers.sinch.com/docs/numbers/api-reference/numbers/tag/Numbers-Callbacks/), + using the `/callbackConfiguration` endpoint: + ``` + - NUMBERS_WEBHOOK_SECRET=Your Sinch Webhook Secret + ``` + + +## Usage + +### Running the server + + +1. Navigate to the project's root directory in your terminal. + ``` + cd /path/to/sinch-sdk-python-quickstart + ``` +2. (Recommended) Create a virtual environment: + ``` bash + python -m venv venv + source venv/bin/activate # On Windows use `venv\Scripts\activate` + ``` +3. Install the project dependencies: + ``` bash + pip install -e . + ``` +4. Update the `config.ini` file with your configuration (see above). +5. Start the server: + - `python server.py` +Or run it directly from your IDE. + +### Endpoints + +When the server is up and running, the declared controllers will listen and respond to the following endpoints: + +| Service | Endpoint | +|--------------|--------------------| +| Numbers | /NumbersEvent | + + +## Using ngrok to expose your local server + +To test your webhook locally, you can tunnel requests to your local server using ngrok. + +*Note: The default port is `3001`, but this can be changed (see [Server port](#Server port) section)* + +```bash + ngrok http 3001 +``` + +You'll see output similar to this: +``` +ngrok (Ctrl+C to quit) +... +Forwarding https://adbd-79-148-170-158.ngrok-free.app -> http://localhost:3001 +``` +Use the `https` forwaring URL in your callback configuration. For example: + - Numbers: https://adbd-79-148-170-158.ngrok-free.app/NumbersEvent + +Use this value to configure the callback URLs: + - **Numbers**: Set the `callbackUrl` parameter when renting ou updating a number via the API diff --git a/templates/server/__init__.py b/templates/server/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/templates/server/src/__init__.py b/templates/server/src/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/templates/server/src/numbers_api/controller.py b/templates/server/src/numbers_api/controller.py new file mode 100644 index 0000000..0145ac4 --- /dev/null +++ b/templates/server/src/numbers_api/controller.py @@ -0,0 +1,29 @@ +from flask import request, Response + + +class NumbersController: + def __init__(self, sinch_client, webhooks_secret): + self.sinch_client = sinch_client + self.webhooks_secret = webhooks_secret + + def numbers_event(self): + headers = dict(request.headers) + body_str = request.raw_body.decode('utf-8') if request.raw_body else '' + + webhooks_service = self.sinch_client.numbers.webhooks(self.webhooks_secret) + + valid_auth = webhooks_service.validate_authentication_header( + headers=headers, + json_payload=body_str + ) + + if not valid_auth: + return Response(status=401) + else: + print('Valid authentication header') + + event = webhooks_service.parse_event(body_str) + + print(event) + + return Response(status=200) diff --git a/templates/server/src/server.py b/templates/server/src/server.py new file mode 100644 index 0000000..905884c --- /dev/null +++ b/templates/server/src/server.py @@ -0,0 +1,24 @@ +from flask import Flask, request +from templates.server.src.numbers_api.controller import NumbersController +from templates.utils import get_sinch_client, load_config + +app = Flask(__name__) + +config = load_config() +port = int(config.get("SERVER_PORT") or 3001) +webhooks_secret = config.get("NUMBERS_WEBHOOKS_SECRET") +sinch_client = get_sinch_client(config) + +numbers_controller = NumbersController(sinch_client, webhooks_secret) + + +# Middleware to capture raw body +@app.before_request +def before_request(): + request.raw_body = request.get_data() + + +app.add_url_rule('/NumbersEvent', methods=['POST'], view_func=numbers_controller.numbers_event) + +if __name__ == '__main__': + app.run(port=port) diff --git a/templates/utils/__init__.py b/templates/utils/__init__.py new file mode 100644 index 0000000..6e766fb --- /dev/null +++ b/templates/utils/__init__.py @@ -0,0 +1,3 @@ +from templates.utils.sinch_client_helper import get_sinch_client, get_property, load_config + +__all__ = ['get_sinch_client', 'get_property', 'load_config'] diff --git a/templates/utils/sinch_client_helper.py b/templates/utils/sinch_client_helper.py new file mode 100644 index 0000000..ad35962 --- /dev/null +++ b/templates/utils/sinch_client_helper.py @@ -0,0 +1,57 @@ +import os +import configparser +from pathlib import Path +from sinch import SinchClient + + +def load_config(): + """ + Load configuration from config.ini file in the root directory. + Returns a dictionary of configuration values. + """ + project_root = Path(__file__).resolve().parent.parent.parent + env_file = project_root / 'config.ini' + + if not env_file.exists(): + raise FileNotFoundError(f"Could not find config.ini file in the root directory: {env_file}") + + config = configparser.ConfigParser() + config.read(env_file) + + config_dict = {} + for section in config.sections(): + for key, value in config.items(section): + config_dict[key.upper()] = value + + return config_dict + + +def get_property(property_name: str) -> str: + """ + Get a property from environment variables. + + Args: + property_name: Name of the property to retrieve + + Returns: + str: Property value or empty string if not found + """ + return os.environ.get(property_name) or '' + + +def get_sinch_client(config) -> SinchClient: + """ + Create and return a configured SinchClient instance. + + Returns: + SinchClient: Configured Sinch client instance + """ + project_id = config.get('SINCH_PROJECT_ID') + key_id = config.get('SINCH_KEY_ID') + key_secret = config.get('SINCH_KEY_SECRET') + + return SinchClient( + project_id=project_id, + key_id=key_id, + key_secret=key_secret, + ) From c6de26f47403ecf2d5f69ec0cc850c6f0ccc888b Mon Sep 17 00:00:00 2001 From: Jessica Matsuoka Date: Wed, 23 Apr 2025 11:55:19 +0200 Subject: [PATCH 2/4] chore: include logging, update docs and config handling --- .gitignore | 1 - setup.py | 1 + templates/client/.env | 4 ++ templates/client/README.md | 4 +- templates/client/src/app.py | 5 ++- templates/client/src/numbers_api/snippet.py | 12 ++--- config.ini => templates/server/.env | 13 +++--- templates/server/README.md | 6 +-- .../server/src/numbers_api/controller.py | 6 ++- templates/server/src/server.py | 11 +++-- templates/utils/__init__.py | 4 +- templates/utils/sinch_client_helper.py | 45 +++++++------------ 12 files changed, 55 insertions(+), 57 deletions(-) create mode 100644 templates/client/.env rename config.ini => templates/server/.env (52%) diff --git a/.gitignore b/.gitignore index e79cdc6..1989419 100644 --- a/.gitignore +++ b/.gitignore @@ -93,7 +93,6 @@ celerybeat.pid *.sage.py # Environments -.env .venv env/ venv/ diff --git a/setup.py b/setup.py index e55902e..18cde92 100644 --- a/setup.py +++ b/setup.py @@ -6,6 +6,7 @@ packages=find_packages(), install_requires=[ # TODO: Add 'sinch' after v2.0 release. + "dotenv", "flask" ], python_requires=">=3.9", diff --git a/templates/client/.env b/templates/client/.env new file mode 100644 index 0000000..8f7d29f --- /dev/null +++ b/templates/client/.env @@ -0,0 +1,4 @@ +# Unified Credentials +SINCH_PROJECT_ID = PROJECT_ID +SINCH_KEY_ID = KEY_ID +SINCH_KEY_SECRET = KEY_SECRET diff --git a/templates/client/README.md b/templates/client/README.md index 0edd7b3..95ffd74 100644 --- a/templates/client/README.md +++ b/templates/client/README.md @@ -15,7 +15,7 @@ Before you being, ensure you have: To configure the client application: 1. **Environment Variables**: - Edit the [config.ini](config.ini) file, adding your credentials from the Sinch dashboard under the Access Keys section. + Edit the [.env](.env) file, adding your credentials from the Sinch dashboard under the Access Keys section. - To use [Numbers](https://developers.sinch.com/docs/numbers/) you need to fill the following variables with the values from your Sinch account: ``` [CREDENTIALS] @@ -52,7 +52,7 @@ To configure the client application: ``` pip install -e . ``` -4. Ensure your `config.ini` file have been updated as described above. +4. Ensure your `.env` file have been updated as described above. 5. Run the application: - `python app.py` Or run it directly from your IDE. diff --git a/templates/client/src/app.py b/templates/client/src/app.py index f0f9547..7efe106 100644 --- a/templates/client/src/app.py +++ b/templates/client/src/app.py @@ -3,13 +3,14 @@ def main(): - config = load_config() + config = load_config(env_dir='client') sinch_client = get_sinch_client(config) + logger = sinch_client.configuration.logger try: NumbersQuickstart(sinch_client) except Exception as e: - print(f'Error: {e}') + logger.error(f'Error: {e}') if __name__ == '__main__': diff --git a/templates/client/src/numbers_api/snippet.py b/templates/client/src/numbers_api/snippet.py index 1727b5f..e493e95 100644 --- a/templates/client/src/numbers_api/snippet.py +++ b/templates/client/src/numbers_api/snippet.py @@ -26,10 +26,10 @@ def execute(sinch_client): # You extract the logic and place it inside the `execute` function like so: # # def execute(sinch_client): -# available_regions = sinch_client.numbers.regions.list( -# number_types=["MOBILE"] -# ) +# available_regions = sinch_client.numbers.regions.list( +# number_types=["MOBILE"] +# ) # -# print("Available regions:\n") -# for region in available_regions.iterator(): -# print(region) +# print("Available regions:\n") +# for region in available_regions.iterator(): +# print(region) diff --git a/config.ini b/templates/server/.env similarity index 52% rename from config.ini rename to templates/server/.env index 131a2ca..fca37b4 100644 --- a/config.ini +++ b/templates/server/.env @@ -1,13 +1,12 @@ -# Credentials used by Numbers API -[CREDENTIALS] +# Unified Credentials SINCH_PROJECT_ID = PROJECT_ID -SINCH_KEY_ID = SINCH_KEY_ID -SINCH_KEY_SECRET = SINCH_KEY_SECRET +SINCH_KEY_ID = KEY_ID +SINCH_KEY_SECRET = KEY_SECRET -[CONFIG] +# Server Configuration SERVER_PORT = 3001 -[WEBHOOK] +# Webhook Configuration # The secret value used for webhook calls validation # See https://developers.sinch.com/docs/numbers/api-reference/numbers/tag/Numbers-Callbacks/ -NUMBERS_WEBHOOKS_SECRET = webhook_secret +NUMBERS_WEBHOOKS_SECRET = WEBHOOKS_SECRET diff --git a/templates/server/README.md b/templates/server/README.md index ef21609..25d1154 100644 --- a/templates/server/README.md +++ b/templates/server/README.md @@ -13,7 +13,7 @@ to process incoming webhooks. ## Configuration 1. **Environment Variables**: - Edit the [config.ini](config.ini) file, adding your credentials from the Sinch dashboard under the Access Keys section. + Edit the [.env](.env) file, adding your credentials from the Sinch dashboard under the Access Keys section. - To use [Numbers](https://developers.sinch.com/docs/numbers/) you need to fill the following variables with the values from your Sinch account: ``` @@ -22,7 +22,7 @@ to process incoming webhooks. - SINCH_KEY_SECRET=Your Sinch Key Secret associated to your Sinch Access Key ``` - Server Port - Define the port your server will listen on: + Define the port your server will listen on (default: 3001): ``` - SERVER_PORT=3001 ``` @@ -52,7 +52,7 @@ to process incoming webhooks. ``` bash pip install -e . ``` -4. Update the `config.ini` file with your configuration (see above). +4. Update the `.env` file with your configuration (see above). 5. Start the server: - `python server.py` Or run it directly from your IDE. diff --git a/templates/server/src/numbers_api/controller.py b/templates/server/src/numbers_api/controller.py index 0145ac4..e00dc06 100644 --- a/templates/server/src/numbers_api/controller.py +++ b/templates/server/src/numbers_api/controller.py @@ -5,6 +5,7 @@ class NumbersController: def __init__(self, sinch_client, webhooks_secret): self.sinch_client = sinch_client self.webhooks_secret = webhooks_secret + self.logger = self.sinch_client.configuration.logger def numbers_event(self): headers = dict(request.headers) @@ -18,12 +19,13 @@ def numbers_event(self): ) if not valid_auth: + self.logger.warning('Invalid authentication header') return Response(status=401) else: - print('Valid authentication header') + self.logger.info('Valid authentication header') event = webhooks_service.parse_event(body_str) - print(event) + self.logger.info(f'Received event: {event}') return Response(status=200) diff --git a/templates/server/src/server.py b/templates/server/src/server.py index 905884c..49150f0 100644 --- a/templates/server/src/server.py +++ b/templates/server/src/server.py @@ -1,14 +1,19 @@ +import logging from flask import Flask, request from templates.server.src.numbers_api.controller import NumbersController from templates.utils import get_sinch_client, load_config app = Flask(__name__) -config = load_config() -port = int(config.get("SERVER_PORT") or 3001) -webhooks_secret = config.get("NUMBERS_WEBHOOKS_SECRET") +config = load_config('server') +port = int(config.get('SERVER_PORT') or 3001) +webhooks_secret = config.get('NUMBERS_WEBHOOKS_SECRET') sinch_client = get_sinch_client(config) +# Set up logging at INFO level +logging.basicConfig() +sinch_client.configuration.logger.setLevel(logging.INFO) + numbers_controller = NumbersController(sinch_client, webhooks_secret) diff --git a/templates/utils/__init__.py b/templates/utils/__init__.py index 6e766fb..40a5b4f 100644 --- a/templates/utils/__init__.py +++ b/templates/utils/__init__.py @@ -1,3 +1,3 @@ -from templates.utils.sinch_client_helper import get_sinch_client, get_property, load_config +from templates.utils.sinch_client_helper import get_sinch_client, load_config -__all__ = ['get_sinch_client', 'get_property', 'load_config'] +__all__ = ['get_sinch_client', 'load_config'] diff --git a/templates/utils/sinch_client_helper.py b/templates/utils/sinch_client_helper.py index ad35962..b3ef6b6 100644 --- a/templates/utils/sinch_client_helper.py +++ b/templates/utils/sinch_client_helper.py @@ -1,48 +1,35 @@ -import os -import configparser from pathlib import Path from sinch import SinchClient +from dotenv import dotenv_values -def load_config(): +def load_config(env_dir: str) -> dict[str, str]: """ - Load configuration from config.ini file in the root directory. - Returns a dictionary of configuration values. + Load configuration from .env file in the specified directory. + + Args: + env_dir (str): The directory containing the .env file (relative to project root) + + Returns: + dict[str, str]: Dictionary containing configuration values """ - project_root = Path(__file__).resolve().parent.parent.parent - env_file = project_root / 'config.ini' + project_root = Path(__file__).resolve().parent.parent + env_file = project_root / env_dir / '.env' if not env_file.exists(): - raise FileNotFoundError(f"Could not find config.ini file in the root directory: {env_file}") + raise FileNotFoundError(f"Could not find .env file in directory: {env_file}") - config = configparser.ConfigParser() - config.read(env_file) - - config_dict = {} - for section in config.sections(): - for key, value in config.items(section): - config_dict[key.upper()] = value + config_dict = dotenv_values(env_file) return config_dict -def get_property(property_name: str) -> str: - """ - Get a property from environment variables. - - Args: - property_name: Name of the property to retrieve - - Returns: - str: Property value or empty string if not found - """ - return os.environ.get(property_name) or '' - - -def get_sinch_client(config) -> SinchClient: +def get_sinch_client(config: dict) -> SinchClient: """ Create and return a configured SinchClient instance. + Args: + config (dict): Dictionary containing configuration values Returns: SinchClient: Configured Sinch client instance """ From 883694cf2d6be5389400b13bdebfd95104390d95 Mon Sep 17 00:00:00 2001 From: Jessica Matsuoka Date: Fri, 25 Apr 2025 14:50:27 +0200 Subject: [PATCH 3/4] chore: handle events --- templates/client/src/app.py | 9 +++- templates/client/src/numbers_api/snippet.py | 5 ++- .../src}/sinch_client_helper.py | 13 +++--- templates/server/.env | 2 +- .../server/src/numbers_api/controller.py | 7 ++-- .../src/numbers_api/server_business_logic.py | 12 ++++++ templates/server/src/server.py | 7 ++-- templates/server/src/sinch_client_helper.py | 41 +++++++++++++++++++ templates/utils/__init__.py | 3 -- 9 files changed, 76 insertions(+), 23 deletions(-) rename templates/{utils => client/src}/sinch_client_helper.py (71%) create mode 100644 templates/server/src/numbers_api/server_business_logic.py create mode 100644 templates/server/src/sinch_client_helper.py delete mode 100644 templates/utils/__init__.py diff --git a/templates/client/src/app.py b/templates/client/src/app.py index 7efe106..4c4947d 100644 --- a/templates/client/src/app.py +++ b/templates/client/src/app.py @@ -1,10 +1,15 @@ +import logging from templates.client.src.numbers_api.numbers_quickstart import NumbersQuickstart -from templates.utils import get_sinch_client, load_config +from templates.client.src.sinch_client_helper import get_sinch_client, load_config def main(): - config = load_config(env_dir='client') + config = load_config() sinch_client = get_sinch_client(config) + + # Set up logging at the INFO level + logging.basicConfig() + sinch_client.configuration.logger.setLevel(logging.INFO) logger = sinch_client.configuration.logger try: diff --git a/templates/client/src/numbers_api/snippet.py b/templates/client/src/numbers_api/snippet.py index e493e95..b944402 100644 --- a/templates/client/src/numbers_api/snippet.py +++ b/templates/client/src/numbers_api/snippet.py @@ -1,11 +1,12 @@ # Replace the code below with any snippet from: # https://github.com/sinch/sinch-sdk-python-snippets def execute(sinch_client): - print("Snippet execution: Numbers service") + logger = sinch_client.configuration.logger + logger.info("Snippet execution: Numbers service") # Example usage: -# Let's say you're using the snippet from snippets/available_regions/list/snippet.py: +# Let's say you're using the snippet from snippets/available_regions/list/snippet.py: # # from sinch import SinchClient # diff --git a/templates/utils/sinch_client_helper.py b/templates/client/src/sinch_client_helper.py similarity index 71% rename from templates/utils/sinch_client_helper.py rename to templates/client/src/sinch_client_helper.py index b3ef6b6..6bb911d 100644 --- a/templates/utils/sinch_client_helper.py +++ b/templates/client/src/sinch_client_helper.py @@ -1,23 +1,20 @@ from pathlib import Path -from sinch import SinchClient from dotenv import dotenv_values +from sinch import SinchClient -def load_config(env_dir: str) -> dict[str, str]: +def load_config() -> dict[str, str]: """ - Load configuration from .env file in the specified directory. - - Args: - env_dir (str): The directory containing the .env file (relative to project root) + Load configuration from the .env file in the client directory. Returns: dict[str, str]: Dictionary containing configuration values """ project_root = Path(__file__).resolve().parent.parent - env_file = project_root / env_dir / '.env' + env_file = project_root / '.env' if not env_file.exists(): - raise FileNotFoundError(f"Could not find .env file in directory: {env_file}") + raise FileNotFoundError(f"Could not find .env file in client directory: {env_file}") config_dict = dotenv_values(env_file) diff --git a/templates/server/.env b/templates/server/.env index fca37b4..a83d00f 100644 --- a/templates/server/.env +++ b/templates/server/.env @@ -4,7 +4,7 @@ SINCH_KEY_ID = KEY_ID SINCH_KEY_SECRET = KEY_SECRET # Server Configuration -SERVER_PORT = 3001 +SERVER_PORT = # Webhook Configuration # The secret value used for webhook calls validation diff --git a/templates/server/src/numbers_api/controller.py b/templates/server/src/numbers_api/controller.py index e00dc06..46c1d63 100644 --- a/templates/server/src/numbers_api/controller.py +++ b/templates/server/src/numbers_api/controller.py @@ -1,4 +1,5 @@ from flask import request, Response +from templates.server.src.numbers_api.server_business_logic import handle_numbers_event class NumbersController: @@ -19,13 +20,11 @@ def numbers_event(self): ) if not valid_auth: - self.logger.warning('Invalid authentication header') + self.logger.error('Invalid authentication header') return Response(status=401) - else: - self.logger.info('Valid authentication header') event = webhooks_service.parse_event(body_str) - self.logger.info(f'Received event: {event}') + handle_numbers_event(numbers_event=event, logger=self.logger) return Response(status=200) diff --git a/templates/server/src/numbers_api/server_business_logic.py b/templates/server/src/numbers_api/server_business_logic.py new file mode 100644 index 0000000..230efb1 --- /dev/null +++ b/templates/server/src/numbers_api/server_business_logic.py @@ -0,0 +1,12 @@ +from sinch.domains.numbers.webhooks.v1.events.numbers_webhooks_event import NumbersWebhooksEvent + + +def handle_numbers_event(numbers_event: NumbersWebhooksEvent, logger): + """ + Handle a Numbers event. + Args: + numbers_event (NumbersWebhooksEvent): The Numbers event data. + logger (logging.Logger, optional): Logger instance for logging. Defaults to None. + """ + if logger: + logger.info(f'Handling Numbers event:\n{numbers_event.model_dump_json(indent=2)}') diff --git a/templates/server/src/server.py b/templates/server/src/server.py index 49150f0..6cb56c9 100644 --- a/templates/server/src/server.py +++ b/templates/server/src/server.py @@ -1,16 +1,17 @@ import logging + from flask import Flask, request from templates.server.src.numbers_api.controller import NumbersController -from templates.utils import get_sinch_client, load_config +from templates.server.src.sinch_client_helper import get_sinch_client, load_config app = Flask(__name__) -config = load_config('server') +config = load_config() port = int(config.get('SERVER_PORT') or 3001) webhooks_secret = config.get('NUMBERS_WEBHOOKS_SECRET') sinch_client = get_sinch_client(config) -# Set up logging at INFO level +# Set up logging at the INFO level logging.basicConfig() sinch_client.configuration.logger.setLevel(logging.INFO) diff --git a/templates/server/src/sinch_client_helper.py b/templates/server/src/sinch_client_helper.py new file mode 100644 index 0000000..22670bc --- /dev/null +++ b/templates/server/src/sinch_client_helper.py @@ -0,0 +1,41 @@ +from pathlib import Path +from sinch import SinchClient +from dotenv import dotenv_values + + +def load_config() -> dict[str, str]: + """ + Load configuration from the .env file in the server directory. + + Returns: + dict[str, str]: Dictionary containing configuration values + """ + project_root = Path(__file__).resolve().parent.parent + env_file = project_root / '.env' + + if not env_file.exists(): + raise FileNotFoundError(f"Could not find .env file in server directory: {env_file}") + + config_dict = dotenv_values(env_file) + + return config_dict + + +def get_sinch_client(config: dict) -> SinchClient: + """ + Create and return a configured SinchClient instance. + + Args: + config (dict): Dictionary containing configuration values + Returns: + SinchClient: Configured Sinch client instance + """ + project_id = config.get('SINCH_PROJECT_ID') + key_id = config.get('SINCH_KEY_ID') + key_secret = config.get('SINCH_KEY_SECRET') + + return SinchClient( + project_id=project_id, + key_id=key_id, + key_secret=key_secret, + ) diff --git a/templates/utils/__init__.py b/templates/utils/__init__.py deleted file mode 100644 index 40a5b4f..0000000 --- a/templates/utils/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -from templates.utils.sinch_client_helper import get_sinch_client, load_config - -__all__ = ['get_sinch_client', 'load_config'] From 4c4487fc396f8de29bf0cb8cd9396bcd22f03804 Mon Sep 17 00:00:00 2001 From: Jessica Matsuoka Date: Fri, 25 Apr 2025 18:11:47 +0200 Subject: [PATCH 4/4] chore: add relative paths --- setup.py | 13 ------ templates/client/README.md | 34 ++++++-------- templates/client/pyproject.toml | 15 ++++++ templates/client/src/app.py | 4 +- .../src/numbers_api/numbers_quickstart.py | 2 +- templates/client/src/sinch_client_helper.py | 5 +- templates/server/README.md | 46 ++++++++----------- templates/server/pyproject.toml | 16 +++++++ .../src/numbers_api/server_business_logic.py | 5 +- templates/server/src/sinch_client_helper.py | 7 ++- 10 files changed, 78 insertions(+), 69 deletions(-) delete mode 100644 setup.py create mode 100644 templates/client/pyproject.toml create mode 100644 templates/server/pyproject.toml diff --git a/setup.py b/setup.py deleted file mode 100644 index 18cde92..0000000 --- a/setup.py +++ /dev/null @@ -1,13 +0,0 @@ -from setuptools import setup, find_packages - -setup( - name="sinch-sdk-python-quickstart", - version="0.1.0", - packages=find_packages(), - install_requires=[ - # TODO: Add 'sinch' after v2.0 release. - "dotenv", - "flask" - ], - python_requires=">=3.9", -) \ No newline at end of file diff --git a/templates/client/README.md b/templates/client/README.md index 95ffd74..18278ad 100644 --- a/templates/client/README.md +++ b/templates/client/README.md @@ -6,8 +6,9 @@ It allows you to integrate Sinch APIs into your Python applications easily. ## Prerequisites -Before you being, ensure you have: +Before you begin, ensure you have: - [Python](https://www.python.org/) installed (versions 3.9 to 3.12 recommended). + - [Poetry](https://python-poetry.org/) installed. - A [Sinch account](https://dashboard.sinch.com/) with access to the APIs you want to use. ## Configuration @@ -16,23 +17,21 @@ To configure the client application: 1. **Environment Variables**: Edit the [.env](.env) file, adding your credentials from the Sinch dashboard under the Access Keys section. - - To use [Numbers](https://developers.sinch.com/docs/numbers/) you need to fill the following variables with the values from your Sinch account: - ``` - [CREDENTIALS] + - To use [Numbers](https://developers.sinch.com/docs/numbers/), you need to fill the following variables with the values from your Sinch account: + ``` - SINCH_PROJECT_ID=Your Sinch Project ID - SINCH_KEY_ID=Your Sinch Access Key ID - SINCH_KEY_SECRET=Your Sinch Key Secret associated to your Sinch Access Key ``` - 2. **API Integration**: The application demonstrates usage via modular snippets in `client/src/numbers_api/snippet.py`, which acts as the - main integration point for testing Sinch Numbers API endpoints. Replace the existing logic with your own, based on + main integration point for testing Sinch Numbers API endpoints. You can replace the existing logic with your own, based on the desired API functionality. You can explore and adapt examples from [Python SDK snippets repository.](https://github.com/sinch/sinch-sdk-python-snippets) directly into the `execute(sinch_client)` function: - Choose a snippet - - Copy only the functional logic, skipping the `SinchClient` initialization as - this is already set up in the project. + - Copy only the functional logic (skip the `SinchClient` initialization - + it's already handled in the `app.py` file). - Paste it into the `execute(sinch_client)` function in `snippet.py`. @@ -42,17 +41,12 @@ To configure the client application: ``` cd /path/to/sinch-sdk-python-quickstart ``` -2. (Recommended) Create a virtual environment: - ``` bash - python -m venv venv - source venv/bin/activate - # On Windows use `venv\Scripts\activate` - ``` -3. Install the project dependencies: +2. Install the project dependencies: ``` - pip install -e . + cd templates/client + poetry install ``` -4. Ensure your `.env` file have been updated as described above. -5. Run the application: - - `python app.py` - Or run it directly from your IDE. +3. Make sure your `.env` file has been updated as described above. +4. Run the application: + - `poetry run python src/app.py` + Or run it directly from your IDE if preferred. diff --git a/templates/client/pyproject.toml b/templates/client/pyproject.toml new file mode 100644 index 0000000..94a5113 --- /dev/null +++ b/templates/client/pyproject.toml @@ -0,0 +1,15 @@ +[tool.poetry] +name = "sinch-sdk-python-quickstart-client" +version = "0.1.0" +description = "Sinch SDK Python Quickstart Client" +readme = "README.md" +packages = [{include = "src"}] + +[tool.poetry.dependencies] +python = "^3.9" +python-dotenv = "^1.0.0" +# sinch = "^2.0.0" # Uncomment once v2.0 is released + +[build-system] +requires = ["poetry-core"] +build-backend = "poetry.core.masonry.api" diff --git a/templates/client/src/app.py b/templates/client/src/app.py index 4c4947d..17f06f8 100644 --- a/templates/client/src/app.py +++ b/templates/client/src/app.py @@ -1,6 +1,6 @@ import logging -from templates.client.src.numbers_api.numbers_quickstart import NumbersQuickstart -from templates.client.src.sinch_client_helper import get_sinch_client, load_config +from numbers_api.numbers_quickstart import NumbersQuickstart +from sinch_client_helper import get_sinch_client, load_config def main(): diff --git a/templates/client/src/numbers_api/numbers_quickstart.py b/templates/client/src/numbers_api/numbers_quickstart.py index a138a6f..bcd0bb7 100644 --- a/templates/client/src/numbers_api/numbers_quickstart.py +++ b/templates/client/src/numbers_api/numbers_quickstart.py @@ -1,4 +1,4 @@ -from templates.client.src.numbers_api.snippet import execute +from .snippet import execute class NumbersQuickstart: diff --git a/templates/client/src/sinch_client_helper.py b/templates/client/src/sinch_client_helper.py index 6bb911d..8e5a3e6 100644 --- a/templates/client/src/sinch_client_helper.py +++ b/templates/client/src/sinch_client_helper.py @@ -10,8 +10,9 @@ def load_config() -> dict[str, str]: Returns: dict[str, str]: Dictionary containing configuration values """ - project_root = Path(__file__).resolve().parent.parent - env_file = project_root / '.env' + current_dir = Path(__file__).resolve().parent + client_dir = current_dir.parent + env_file = client_dir / '.env' if not env_file.exists(): raise FileNotFoundError(f"Could not find .env file in client directory: {env_file}") diff --git a/templates/server/README.md b/templates/server/README.md index 25d1154..bb2ba87 100644 --- a/templates/server/README.md +++ b/templates/server/README.md @@ -6,23 +6,24 @@ to process incoming webhooks. ## Requirements - [Python 3.9+](https://www.python.org/) -- [Flask]() +- [Flask](https://flask.palletsprojects.com/en/stable/) - [Sinch account](https://dashboard.sinch.com/) - [ngrok](https://ngrok.com/docs) +- [Poetry](https://python-poetry.org/) ## Configuration 1. **Environment Variables**: Edit the [.env](.env) file, adding your credentials from the Sinch dashboard under the Access Keys section. - - To use [Numbers](https://developers.sinch.com/docs/numbers/) you need to fill the following variables + - To use [Numbers](https://developers.sinch.com/docs/numbers/), you need to fill the following variables with the values from your Sinch account: ``` - SINCH_PROJECT_ID=Your Sinch Project ID - SINCH_KEY_ID=Your Sinch Access Key ID - SINCH_KEY_SECRET=Your Sinch Key Secret associated to your Sinch Access Key ``` - - Server Port - Define the port your server will listen on (default: 3001): + - Server Port: + Define the port your server will listen to on (default: 3001): ``` - SERVER_PORT=3001 ``` @@ -33,44 +34,37 @@ to process incoming webhooks. - NUMBERS_WEBHOOK_SECRET=Your Sinch Webhook Secret ``` - ## Usage ### Running the server - 1. Navigate to the project's root directory in your terminal. - ``` +``` cd /path/to/sinch-sdk-python-quickstart - ``` -2. (Recommended) Create a virtual environment: - ``` bash - python -m venv venv - source venv/bin/activate # On Windows use `venv\Scripts\activate` - ``` -3. Install the project dependencies: - ``` bash - pip install -e . - ``` -4. Update the `.env` file with your configuration (see above). -5. Start the server: - - `python server.py` -Or run it directly from your IDE. +``` +2. Install the project dependencies: +``` bash + cd templates/server + poetry install +``` +3. Update the `.env` file with your configuration (see above). +4. Start the server: + - `poetry run python src/server.py` +Or run it directly from your IDE if preferred. ### Endpoints -When the server is up and running, the declared controllers will listen and respond to the following endpoints: +The server exposes the following endpoints: | Service | Endpoint | |--------------|--------------------| | Numbers | /NumbersEvent | - ## Using ngrok to expose your local server To test your webhook locally, you can tunnel requests to your local server using ngrok. -*Note: The default port is `3001`, but this can be changed (see [Server port](#Server port) section)* +*Note: The default port is `3001`, but this can be changed (see [Server port](#Configuration))* ```bash ngrok http 3001 @@ -82,8 +76,8 @@ ngrok ... Forwarding https://adbd-79-148-170-158.ngrok-free.app -> http://localhost:3001 ``` -Use the `https` forwaring URL in your callback configuration. For example: +Use the `https` forwarding URL in your callback configuration. For example: - Numbers: https://adbd-79-148-170-158.ngrok-free.app/NumbersEvent Use this value to configure the callback URLs: - - **Numbers**: Set the `callbackUrl` parameter when renting ou updating a number via the API + - **Numbers**: Set the `callbackUrl` parameter when renting or updating a number via the API diff --git a/templates/server/pyproject.toml b/templates/server/pyproject.toml new file mode 100644 index 0000000..661eec8 --- /dev/null +++ b/templates/server/pyproject.toml @@ -0,0 +1,16 @@ +[tool.poetry] +name = "sinch-sdk-python-quickstart-server" +version = "0.1.0" +description = "Sinch SDK Python Quickstart Server" +readme = "README.md" +packages = [{include = "src"}] + +[tool.poetry.dependencies] +python = "^3.9" +python-dotenv = "^1.0.0" +flask = "^3.0.0" +# sinch = "^2.0.0" # Uncomment once v2.0 is released + +[build-system] +requires = ["poetry-core"] +build-backend = "poetry.core.masonry.api" \ No newline at end of file diff --git a/templates/server/src/numbers_api/server_business_logic.py b/templates/server/src/numbers_api/server_business_logic.py index 230efb1..8008281 100644 --- a/templates/server/src/numbers_api/server_business_logic.py +++ b/templates/server/src/numbers_api/server_business_logic.py @@ -3,10 +3,9 @@ def handle_numbers_event(numbers_event: NumbersWebhooksEvent, logger): """ - Handle a Numbers event. + This method handles a Numbers event. Args: numbers_event (NumbersWebhooksEvent): The Numbers event data. logger (logging.Logger, optional): Logger instance for logging. Defaults to None. """ - if logger: - logger.info(f'Handling Numbers event:\n{numbers_event.model_dump_json(indent=2)}') + logger.info(f'Handling Numbers event:\n{numbers_event.model_dump_json(indent=2)}') diff --git a/templates/server/src/sinch_client_helper.py b/templates/server/src/sinch_client_helper.py index 22670bc..2a99ac4 100644 --- a/templates/server/src/sinch_client_helper.py +++ b/templates/server/src/sinch_client_helper.py @@ -10,8 +10,11 @@ def load_config() -> dict[str, str]: Returns: dict[str, str]: Dictionary containing configuration values """ - project_root = Path(__file__).resolve().parent.parent - env_file = project_root / '.env' + # Get the directory where this file is located + current_dir = Path(__file__).resolve().parent + # Go up one level to the server directory + server_dir = current_dir.parent + env_file = server_dir / '.env' if not env_file.exists(): raise FileNotFoundError(f"Could not find .env file in server directory: {env_file}")