signedly 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- signedly/__init__.py +92 -0
- signedly/api/__init__.py +14 -0
- signedly/api/api_request_logs_api.py +686 -0
- signedly/api/authentication_api.py +603 -0
- signedly/api/bulk_sending_api.py +858 -0
- signedly/api/documents_api.py +2465 -0
- signedly/api/downloads_api.py +840 -0
- signedly/api/fields_api.py +2308 -0
- signedly/api/sending_api.py +890 -0
- signedly/api/signatories_api.py +1165 -0
- signedly/api/templates_api.py +1452 -0
- signedly/api/webhooks_api.py +2582 -0
- signedly/api_client.py +798 -0
- signedly/api_response.py +21 -0
- signedly/configuration.py +596 -0
- signedly/exceptions.py +200 -0
- signedly/helpers.py +89 -0
- signedly/models/__init__.py +66 -0
- signedly/models/create_bulk_send202_response.py +105 -0
- signedly/models/create_bulk_send_request.py +101 -0
- signedly/models/create_document_fields_request_inner.py +156 -0
- signedly/models/create_document_from_template200_response.py +101 -0
- signedly/models/create_document_from_template_request.py +115 -0
- signedly/models/create_document_from_template_request_recipients_inner.py +92 -0
- signedly/models/create_signatories_request.py +100 -0
- signedly/models/create_signatories_request_signatories_inner.py +92 -0
- signedly/models/create_signatory_request.py +94 -0
- signedly/models/create_template_fields_request_inner.py +156 -0
- signedly/models/create_webhook_endpoint_request.py +103 -0
- signedly/models/delete_field_request.py +88 -0
- signedly/models/document.py +159 -0
- signedly/models/document_page.py +113 -0
- signedly/models/document_status_page.py +113 -0
- signedly/models/document_status_row.py +90 -0
- signedly/models/fill_and_send_document_request.py +116 -0
- signedly/models/fill_and_send_document_request_elements_inner.py +96 -0
- signedly/models/get_access_token_request.py +90 -0
- signedly/models/get_audit_trail_link200_response.py +88 -0
- signedly/models/get_download_status200_response.py +90 -0
- signedly/models/list_bulk_send_columns200_response_inner.py +92 -0
- signedly/models/model_field.py +202 -0
- signedly/models/page.py +102 -0
- signedly/models/refresh_access_token200_response.py +99 -0
- signedly/models/refresh_access_token_request.py +88 -0
- signedly/models/request_count_page.py +113 -0
- signedly/models/request_hit.py +93 -0
- signedly/models/request_log.py +108 -0
- signedly/models/request_log_page.py +113 -0
- signedly/models/send_document200_response.py +88 -0
- signedly/models/send_document_by_link200_response.py +90 -0
- signedly/models/send_document_by_link_request.py +91 -0
- signedly/models/send_document_request.py +102 -0
- signedly/models/signatory.py +119 -0
- signedly/models/template.py +124 -0
- signedly/models/template_field.py +202 -0
- signedly/models/template_page.py +113 -0
- signedly/models/update_document_field_by_body_request.py +158 -0
- signedly/models/update_document_field_by_body_request_items_inner.py +92 -0
- signedly/models/update_webhook_endpoint_request.py +105 -0
- signedly/models/upload.py +110 -0
- signedly/models/upload_document_for_one_signer200_response.py +90 -0
- signedly/models/upload_document_for_one_signer_request.py +96 -0
- signedly/models/upload_document_request.py +101 -0
- signedly/models/webhook_delivery.py +140 -0
- signedly/models/webhook_delivery_page.py +113 -0
- signedly/models/webhook_endpoint.py +116 -0
- signedly/models/webhook_endpoint_with_secret.py +120 -0
- signedly/py.typed +0 -0
- signedly/rest.py +258 -0
- signedly-0.1.0.dist-info/LICENSE +21 -0
- signedly-0.1.0.dist-info/METADATA +18 -0
- signedly-0.1.0.dist-info/RECORD +74 -0
- signedly-0.1.0.dist-info/WHEEL +5 -0
- signedly-0.1.0.dist-info/top_level.txt +1 -0
signedly/api_response.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""API response object."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
from typing import Optional, Generic, Mapping, TypeVar
|
|
5
|
+
from pydantic import Field, StrictInt, StrictBytes, BaseModel
|
|
6
|
+
|
|
7
|
+
T = TypeVar("T")
|
|
8
|
+
|
|
9
|
+
class ApiResponse(BaseModel, Generic[T]):
|
|
10
|
+
"""
|
|
11
|
+
API response object
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
status_code: StrictInt = Field(description="HTTP status code")
|
|
15
|
+
headers: Optional[Mapping[str, str]] = Field(None, description="HTTP headers")
|
|
16
|
+
data: T = Field(description="Deserialized data given the data type")
|
|
17
|
+
raw_data: StrictBytes = Field(description="Raw data (HTTP response body)")
|
|
18
|
+
|
|
19
|
+
model_config = {
|
|
20
|
+
"arbitrary_types_allowed": True
|
|
21
|
+
}
|
|
@@ -0,0 +1,596 @@
|
|
|
1
|
+
# coding: utf-8
|
|
2
|
+
|
|
3
|
+
"""
|
|
4
|
+
Signedly API
|
|
5
|
+
|
|
6
|
+
The Signedly REST API lets your system upload documents, add signatories and fields, send them for signing and download the signed result. Every path starts with `/ap1/`, and every request and response body is JSON unless an endpoint says otherwise (the uploads are `multipart/form-data`). ## Authentication 1. In the Signedly web app, open **Account & Settings → API** and generate a **client ID** and **client secret** for your organisation. 2. `POST /ap1/token/` with them. You get an `access_token` (valid **2 hours**) and a `refresh_token` (valid **7 days**). While both are still valid, calling `/ap1/token/` again returns the same pair. 3. Send the access token on every other call: `Authorization: Bearer <access_token>`. 4. When the access token expires, `POST /ap1/refreshtoken/` with the refresh token for a new access token. When the refresh token has expired too, call `/ap1/token/` again. `/ap1/token/` and `/ap1/refreshtoken/` allow 60 calls a minute per IP address; more answer 429. A missing, unknown or expired access token answers 403 (`\"Client not found\"` or `\"Access token expired\"`). The API acts for your **organisation's admin account**: documents you upload belong to it and appear in its Signedly web app, and you can reach only that account's documents, templates, signatories and fields. Another organisation's IDs answer 404, as if they didn't exist. ## Plans What the API allows depends on the Signedly plan of your **organisation's admin account** (Account & Settings → Account & Plan). The same rules apply to live and test keys. | What | Free | Personal Pro | Business Pro | Teams | |---|---|---|---|---| | Generate live and test keys (Account & Settings → API) | – | ✓ | ✓ | ✓ | | Every endpoint, `/ap1/token/` and `/ap1/refreshtoken/` included | – | ✓ | ✓ | ✓ | | `require_email_otp` on `POST /ap1/signatories/` and `POST /ap1/signatories/bulk/` | – | ✓ | ✓ | ✓ | | Bulk send: `GET /ap1/bulk-sends/columns/` and `POST /ap1/bulk-sends/` | – | – | – | ✓ | The API is part of the paid plans. On Free (or with no plan) every call answers 403 `\"... Your plan doesn't include API access.\"`, with live or test keys, also with a token or keys made earlier; they work again once the plan is paid. On a paid plan, a feature it doesn't include answers 400 with `\"Your plan doesn't include ...\"` and changes nothing, and `GET /ap1/bulk-sends/{id}/` still reports bulk sends already made. Live documents also need an API contract with Signedly. Without one, or with an unpaid API invoice, `POST /ap1/upload/` (except templates), `/ap1/upload_app/`, `/ap1/documents/fromtemplate/` and `/ap1/bulk-sends/` answer 402 with live keys. Test keys work without a contract (see Sandbox). ## Sending a document for signing 1. `POST /ap1/upload/` a PDF or DOCX (`type` 2). The document is prepared in the background: find it in `GET /ap1/documents/?name=<name>` (its `upload.id` is the upload's `id`), and wait until `GET /ap1/documents/{id}/pages/` lists its pages. 2. `POST /ap1/signatories/` (one) or `POST /ap1/signatories/bulk/` (several) to add the people who sign. 3. `POST /ap1/documents/fields/` to place the fields each signatory fills in. 4. Send it: - `POST /ap1/document/send/` emails every signatory a signing link (with ordered signing, only the first; each next one is emailed in turn), or - `POST /ap1/document/send_url/` sends no email and returns the first signatory's signing link, for you to show or send yourself. 5. Poll `GET /ap1/documents-status-list/` (or `GET /ap1/documents/`) until the status is 6 (Completed), then `GET /ap1/document/download-link/` for the signed PDF and `GET /ap1/document/download-audit-link/` for its audit trail. **From a template:** upload with `type` 4 and a `template_name` (or make the template in the web app), place its fields with `POST /ap1/templates/fields/`, then for each signing make a document with `POST /ap1/documents/fromtemplate/`, add its signatory, and send it. **One signer, one call:** `POST /ap1/upload_app/` uploads a PDF or DOCX for one signer and returns their signing link in `redirect_url`; the signer places their own signature. After signing they go to the `redirect_url` you sent, and the signed PDF and its audit trail are emailed to `final_email` (otherwise to your organisation's admin). ## Quick start with curl Each step uses an ID from the step before. `$API` is this server, e.g. `https://l0ads.signedly.com`. ```bash # 1. Token curl -X POST $API/ap1/token/ -H 'Content-Type: application/json' \\ -d '{\"client_id\": \"<client id>\", \"client_secret\": \"<client secret>\"}' TOKEN=<access_token from the answer> # 2. Upload a PDF (answers with the upload's id) curl -X POST $API/ap1/upload/ -H \"Authorization: Bearer $TOKEN\" \\ -F file=@nda.pdf -F name=nda-ann-lee -F type=2 # 3. Find the document, then wait until it has pages curl \"$API/ap1/documents/?name=nda-ann-lee\" -H \"Authorization: Bearer $TOKEN\" DOC=<results[0].id> curl $API/ap1/documents/$DOC/pages/ -H \"Authorization: Bearer $TOKEN\" PAGE=<[0].id> # 4. Add the signatory curl -X POST $API/ap1/signatories/ -H \"Authorization: Bearer $TOKEN\" \\ -H 'Content-Type: application/json' \\ -d '{\"document_id\": \"'$DOC'\", \"name\": \"Ann Lee\", \"email\": \"ann@example.com\"}' SIGNER=<id from the answer> # 5. Place her signature: 150 × 40 points, 72 points from the left, 640 from the top curl -X POST $API/ap1/documents/fields/ -H \"Authorization: Bearer $TOKEN\" \\ -H 'Content-Type: application/json' \\ -d '[{\"document_id\": \"'$DOC'\", \"signatory_id\": \"'$SIGNER'\", \"kind\": 2, \"label\": \"Signature\", \"placeholder\": \"Sign here\", \"page\": \"'$PAGE'\", \"page_number\": 0, \"x\": 72, \"y\": 640, \"width\": 150, \"height\": 40}]' # 6. Send it (Ann gets the signing email) curl -X POST $API/ap1/document/send/ -H \"Authorization: Bearer $TOKEN\" \\ -H 'Content-Type: application/json' \\ -d '{\"document_id\": \"'$DOC'\", \"subject\": \"Please sign the NDA\", \"message\": \"Hi Ann, please sign by Friday.\", \"expiry_date\": \"2026-12-31\"}' # 7. Poll until status is 6 (Completed), then get the signed PDF curl \"$API/ap1/documents-status-list/?document_ids=$DOC\" -H \"Authorization: Bearer $TOKEN\" curl \"$API/ap1/document/download-link/?id=$DOC\" -H \"Authorization: Bearer $TOKEN\" ``` ## Postman Import the whole API into Postman with **Import → Link** and `<this server>/swaggerap1/postman.json`. Set `client_id` and `client_secret` in the collection's **Variables**, run **Get an access token** (it saves the token for every other request), and set `document_id` when a request needs one. ## Webhooks Instead of polling, add an endpoint with `POST /ap1/webhooks/` (or in **Account & Settings → API**) and Signedly posts your organisation's document events to it: `document.sent`, `document.viewed`, `document.signed`, `document.approved`, `document.completed`, `document.rejected` and `document.expired` (all of them, or the `events` you choose). Each is a JSON `POST`: ```json {\"id\": \"5b7f…\", \"type\": \"document.signed\", \"created_at\": \"2026-10-27T09:12:00+00:00\", \"test\": false, \"data\": {\"document\": {\"id\": \"6f0c…\", \"name\": \"nda.pdf\", \"status\": 5}, \"recipient\": {\"id\": \"0b6e…\", \"email\": \"ann@example.com\", \"name\": \"Ann Lee\", \"role\": \"signer\"}}} ``` `recipient` is null for events no recipient caused (sent, completed, expired); `test` is true for documents made with your test keys. Fetch anything else, such as download links, with your access token: events never carry links. **Check every event is from Signedly.** The `Signedly-Signature` header is `t=<unix seconds>,v1=<signature>`, where the signature is the hex HMAC-SHA256 of `<t>.<raw body>` with the endpoint's secret. Refuse an event whose signature doesn't match or whose `t` is more than 5 minutes off: ```python import hashlib, hmac, time def is_from_signedly(secret, header, raw_body): parts = dict(item.split(\"=\", 1) for item in header.split(\",\")) signed = f\"{parts['t']}.{raw_body.decode()}\".encode() expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest() fresh = abs(time.time() - int(parts[\"t\"])) <= 300 return fresh and hmac.compare_digest(parts[\"v1\"], expected) ``` **Answer 2xx within 10 seconds**, then do the work. Anything else is retried after 1 and 5 minutes, then 30 minutes and 2, 5 and 10 hours (7 tries in about 18 hours). `Signedly-Event-Id` is the same on every try of an event: use it to ignore repeats. After 20 events in a row fail for good, Signedly switches the endpoint off and emails your organisation's admin; switch it on again with `PUT /ap1/webhooks/{id}/` and `\"is_active\": true`. Each endpoint's deliveries and their last answers are at `GET /ap1/webhooks/{id}/deliveries/`, and any can be sent again. ## Sandbox Build and test against the API without paying for documents: in **Account & Settings → API**, generate your **test keys**, and get a token with them at `/ap1/token/` as usual. Everything works the same, except that what you upload or make from a template with a test token is a **test document** (`is_test` on its upload): - every page of its PDF and of its audit trail says **TEST – NOT LEGALLY BINDING**; - its emails are real, with `[TEST]` at the start of the subject; - it isn't billed or counted toward your plan; - your organisation can make 50 a calendar month (templates don't count); the next upload answers 429. ## Fields Positions and sizes are in **PDF points** (1/72 inch), measured from the **top-left corner** of the page as it is displayed (rotation applied). `page_number` counts pages from 0. A field must sit wholly on its page (1 point of tolerance); otherwise it is refused with 400. A field's page and signatory can't be changed later: delete the field and add it again. ## Status values **Document `status`:** 1 Draft · 2 Signees Added · 3 Prepared · 4 Sent · 5 In Progress · 6 Completed · 7 Rejected · 8 Archived · 9 Expired. Signatories, fields and sends are only accepted while a document is 1–3 (not yet sent). **Signatory `status`:** 1 Waiting · 2 Invited · 3 Signed · 4 Viewed · 5 Rejected. ## Lists `GET /ap1/documents/`, `/ap1/documents-status-list/`, `/ap1/templates/`, `/ap1/logs/` and `/ap1/logs/hits/` are paged: pass `limit` (default 10) and `offset`, and read `count`, `next`, `previous` and `results` from the response. ## Errors | Status | Meaning | |---|---| | 400 | The request was refused, also when your plan doesn't include it (see Plans); the body says why (`{\"error\": \"...\"}`, or the name of each bad field with its messages). Nothing was changed. | | 403 | The access token is missing, unknown or expired; the client ID and secret or the refresh token were refused; the organisation's plan has no API access (Free, see Plans); or an `expiry_date` isn't in the future (`\"Invalid Date Entered\"`). | | 402 | No API contract, or an unpaid API invoice: live documents are refused (test keys keep working). | | 404 | The document, template, signatory or field doesn't exist or isn't yours. | | 429 | Too many token requests (wait a minute), or this month's 50 test documents are used. | | 5xx | Our side failed; retry later. | A send that times out may still have worked: check the document's status before sending again (a second send of a sent document answers 400). Download, view and audit links are valid for about 7 days; ask for a new one whenever you need it.
|
|
7
|
+
|
|
8
|
+
The version of the OpenAPI document: v1
|
|
9
|
+
Contact: info@signedly.com
|
|
10
|
+
Generated by OpenAPI Generator (https://openapi-generator.tech)
|
|
11
|
+
|
|
12
|
+
Do not edit the class manually.
|
|
13
|
+
""" # noqa: E501
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
import copy
|
|
17
|
+
import http.client as httplib
|
|
18
|
+
import logging
|
|
19
|
+
from logging import FileHandler
|
|
20
|
+
import multiprocessing
|
|
21
|
+
import sys
|
|
22
|
+
from typing import Any, ClassVar, Dict, List, Literal, Optional, TypedDict
|
|
23
|
+
from typing_extensions import NotRequired, Self
|
|
24
|
+
|
|
25
|
+
import urllib3
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
JSON_SCHEMA_VALIDATION_KEYWORDS = {
|
|
29
|
+
'multipleOf', 'maximum', 'exclusiveMaximum',
|
|
30
|
+
'minimum', 'exclusiveMinimum', 'maxLength',
|
|
31
|
+
'minLength', 'pattern', 'maxItems', 'minItems'
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
ServerVariablesT = Dict[str, str]
|
|
35
|
+
|
|
36
|
+
GenericAuthSetting = TypedDict(
|
|
37
|
+
"GenericAuthSetting",
|
|
38
|
+
{
|
|
39
|
+
"type": str,
|
|
40
|
+
"in": str,
|
|
41
|
+
"key": str,
|
|
42
|
+
"value": str,
|
|
43
|
+
},
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
OAuth2AuthSetting = TypedDict(
|
|
48
|
+
"OAuth2AuthSetting",
|
|
49
|
+
{
|
|
50
|
+
"type": Literal["oauth2"],
|
|
51
|
+
"in": Literal["header"],
|
|
52
|
+
"key": Literal["Authorization"],
|
|
53
|
+
"value": str,
|
|
54
|
+
},
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
APIKeyAuthSetting = TypedDict(
|
|
59
|
+
"APIKeyAuthSetting",
|
|
60
|
+
{
|
|
61
|
+
"type": Literal["api_key"],
|
|
62
|
+
"in": str,
|
|
63
|
+
"key": str,
|
|
64
|
+
"value": Optional[str],
|
|
65
|
+
},
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
BasicAuthSetting = TypedDict(
|
|
70
|
+
"BasicAuthSetting",
|
|
71
|
+
{
|
|
72
|
+
"type": Literal["basic"],
|
|
73
|
+
"in": Literal["header"],
|
|
74
|
+
"key": Literal["Authorization"],
|
|
75
|
+
"value": Optional[str],
|
|
76
|
+
},
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
BearerFormatAuthSetting = TypedDict(
|
|
81
|
+
"BearerFormatAuthSetting",
|
|
82
|
+
{
|
|
83
|
+
"type": Literal["bearer"],
|
|
84
|
+
"in": Literal["header"],
|
|
85
|
+
"format": Literal["JWT"],
|
|
86
|
+
"key": Literal["Authorization"],
|
|
87
|
+
"value": str,
|
|
88
|
+
},
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
BearerAuthSetting = TypedDict(
|
|
93
|
+
"BearerAuthSetting",
|
|
94
|
+
{
|
|
95
|
+
"type": Literal["bearer"],
|
|
96
|
+
"in": Literal["header"],
|
|
97
|
+
"key": Literal["Authorization"],
|
|
98
|
+
"value": str,
|
|
99
|
+
},
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
HTTPSignatureAuthSetting = TypedDict(
|
|
104
|
+
"HTTPSignatureAuthSetting",
|
|
105
|
+
{
|
|
106
|
+
"type": Literal["http-signature"],
|
|
107
|
+
"in": Literal["header"],
|
|
108
|
+
"key": Literal["Authorization"],
|
|
109
|
+
"value": None,
|
|
110
|
+
},
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
AuthSettings = TypedDict(
|
|
115
|
+
"AuthSettings",
|
|
116
|
+
{
|
|
117
|
+
"Bearer": APIKeyAuthSetting,
|
|
118
|
+
},
|
|
119
|
+
total=False,
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
class HostSettingVariable(TypedDict):
|
|
124
|
+
description: str
|
|
125
|
+
default_value: str
|
|
126
|
+
enum_values: List[str]
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
class HostSetting(TypedDict):
|
|
130
|
+
url: str
|
|
131
|
+
description: str
|
|
132
|
+
variables: NotRequired[Dict[str, HostSettingVariable]]
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
class Configuration:
|
|
136
|
+
"""This class contains various settings of the API client.
|
|
137
|
+
|
|
138
|
+
:param host: Base url.
|
|
139
|
+
:param ignore_operation_servers
|
|
140
|
+
Boolean to ignore operation servers for the API client.
|
|
141
|
+
Config will use `host` as the base url regardless of the operation servers.
|
|
142
|
+
:param api_key: Dict to store API key(s).
|
|
143
|
+
Each entry in the dict specifies an API key.
|
|
144
|
+
The dict key is the name of the security scheme in the OAS specification.
|
|
145
|
+
The dict value is the API key secret.
|
|
146
|
+
:param api_key_prefix: Dict to store API prefix (e.g. Bearer).
|
|
147
|
+
The dict key is the name of the security scheme in the OAS specification.
|
|
148
|
+
The dict value is an API key prefix when generating the auth data.
|
|
149
|
+
:param username: Username for HTTP basic authentication.
|
|
150
|
+
:param password: Password for HTTP basic authentication.
|
|
151
|
+
:param access_token: Access token.
|
|
152
|
+
:param server_index: Index to servers configuration.
|
|
153
|
+
:param server_variables: Mapping with string values to replace variables in
|
|
154
|
+
templated server configuration. The validation of enums is performed for
|
|
155
|
+
variables with defined enum values before.
|
|
156
|
+
:param server_operation_index: Mapping from operation ID to an index to server
|
|
157
|
+
configuration.
|
|
158
|
+
:param server_operation_variables: Mapping from operation ID to a mapping with
|
|
159
|
+
string values to replace variables in templated server configuration.
|
|
160
|
+
The validation of enums is performed for variables with defined enum
|
|
161
|
+
values before.
|
|
162
|
+
:param ssl_ca_cert: str - the path to a file of concatenated CA certificates
|
|
163
|
+
in PEM format.
|
|
164
|
+
:param retries: Number of retries for API requests.
|
|
165
|
+
|
|
166
|
+
:Example:
|
|
167
|
+
|
|
168
|
+
API Key Authentication Example.
|
|
169
|
+
Given the following security scheme in the OpenAPI specification:
|
|
170
|
+
components:
|
|
171
|
+
securitySchemes:
|
|
172
|
+
cookieAuth: # name for the security scheme
|
|
173
|
+
type: apiKey
|
|
174
|
+
in: cookie
|
|
175
|
+
name: JSESSIONID # cookie name
|
|
176
|
+
|
|
177
|
+
You can programmatically set the cookie:
|
|
178
|
+
|
|
179
|
+
conf = signedly.Configuration(
|
|
180
|
+
api_key={'cookieAuth': 'abc123'}
|
|
181
|
+
api_key_prefix={'cookieAuth': 'JSESSIONID'}
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
The following cookie will be added to the HTTP request:
|
|
185
|
+
Cookie: JSESSIONID abc123
|
|
186
|
+
"""
|
|
187
|
+
|
|
188
|
+
_default: ClassVar[Optional[Self]] = None
|
|
189
|
+
|
|
190
|
+
def __init__(
|
|
191
|
+
self,
|
|
192
|
+
host: Optional[str]=None,
|
|
193
|
+
api_key: Optional[Dict[str, str]]=None,
|
|
194
|
+
api_key_prefix: Optional[Dict[str, str]]=None,
|
|
195
|
+
username: Optional[str]=None,
|
|
196
|
+
password: Optional[str]=None,
|
|
197
|
+
access_token: Optional[str]=None,
|
|
198
|
+
server_index: Optional[int]=None,
|
|
199
|
+
server_variables: Optional[ServerVariablesT]=None,
|
|
200
|
+
server_operation_index: Optional[Dict[int, int]]=None,
|
|
201
|
+
server_operation_variables: Optional[Dict[int, ServerVariablesT]]=None,
|
|
202
|
+
ignore_operation_servers: bool=False,
|
|
203
|
+
ssl_ca_cert: Optional[str]=None,
|
|
204
|
+
retries: Optional[int] = None,
|
|
205
|
+
*,
|
|
206
|
+
debug: Optional[bool] = None,
|
|
207
|
+
) -> None:
|
|
208
|
+
"""Constructor
|
|
209
|
+
"""
|
|
210
|
+
self._base_path = "https://l0ads.signedly.com" if host is None else host
|
|
211
|
+
"""Default Base url
|
|
212
|
+
"""
|
|
213
|
+
self.server_index = 0 if server_index is None and host is None else server_index
|
|
214
|
+
self.server_operation_index = server_operation_index or {}
|
|
215
|
+
"""Default server index
|
|
216
|
+
"""
|
|
217
|
+
self.server_variables = server_variables or {}
|
|
218
|
+
self.server_operation_variables = server_operation_variables or {}
|
|
219
|
+
"""Default server variables
|
|
220
|
+
"""
|
|
221
|
+
self.ignore_operation_servers = ignore_operation_servers
|
|
222
|
+
"""Ignore operation servers
|
|
223
|
+
"""
|
|
224
|
+
self.temp_folder_path = None
|
|
225
|
+
"""Temp file folder for downloading files
|
|
226
|
+
"""
|
|
227
|
+
# Authentication Settings
|
|
228
|
+
self.api_key = {}
|
|
229
|
+
if api_key:
|
|
230
|
+
self.api_key = api_key
|
|
231
|
+
"""dict to store API key(s)
|
|
232
|
+
"""
|
|
233
|
+
self.api_key_prefix = {}
|
|
234
|
+
if api_key_prefix:
|
|
235
|
+
self.api_key_prefix = api_key_prefix
|
|
236
|
+
"""dict to store API prefix (e.g. Bearer)
|
|
237
|
+
"""
|
|
238
|
+
self.refresh_api_key_hook = None
|
|
239
|
+
"""function hook to refresh API key if expired
|
|
240
|
+
"""
|
|
241
|
+
self.username = username
|
|
242
|
+
"""Username for HTTP basic authentication
|
|
243
|
+
"""
|
|
244
|
+
self.password = password
|
|
245
|
+
"""Password for HTTP basic authentication
|
|
246
|
+
"""
|
|
247
|
+
self.access_token = access_token
|
|
248
|
+
"""Access token
|
|
249
|
+
"""
|
|
250
|
+
self.logger = {}
|
|
251
|
+
"""Logging Settings
|
|
252
|
+
"""
|
|
253
|
+
self.logger["package_logger"] = logging.getLogger("signedly")
|
|
254
|
+
self.logger["urllib3_logger"] = logging.getLogger("urllib3")
|
|
255
|
+
self.logger_format = '%(asctime)s %(levelname)s %(message)s'
|
|
256
|
+
"""Log format
|
|
257
|
+
"""
|
|
258
|
+
self.logger_stream_handler = None
|
|
259
|
+
"""Log stream handler
|
|
260
|
+
"""
|
|
261
|
+
self.logger_file_handler: Optional[FileHandler] = None
|
|
262
|
+
"""Log file handler
|
|
263
|
+
"""
|
|
264
|
+
self.logger_file = None
|
|
265
|
+
"""Debug file location
|
|
266
|
+
"""
|
|
267
|
+
if debug is not None:
|
|
268
|
+
self.debug = debug
|
|
269
|
+
else:
|
|
270
|
+
self.__debug = False
|
|
271
|
+
"""Debug switch
|
|
272
|
+
"""
|
|
273
|
+
|
|
274
|
+
self.verify_ssl = True
|
|
275
|
+
"""SSL/TLS verification
|
|
276
|
+
Set this to false to skip verifying SSL certificate when calling API
|
|
277
|
+
from https server.
|
|
278
|
+
"""
|
|
279
|
+
self.ssl_ca_cert = ssl_ca_cert
|
|
280
|
+
"""Set this to customize the certificate file to verify the peer.
|
|
281
|
+
"""
|
|
282
|
+
self.cert_file = None
|
|
283
|
+
"""client certificate file
|
|
284
|
+
"""
|
|
285
|
+
self.key_file = None
|
|
286
|
+
"""client key file
|
|
287
|
+
"""
|
|
288
|
+
self.assert_hostname = None
|
|
289
|
+
"""Set this to True/False to enable/disable SSL hostname verification.
|
|
290
|
+
"""
|
|
291
|
+
self.tls_server_name = None
|
|
292
|
+
"""SSL/TLS Server Name Indication (SNI)
|
|
293
|
+
Set this to the SNI value expected by the server.
|
|
294
|
+
"""
|
|
295
|
+
|
|
296
|
+
self.connection_pool_maxsize = multiprocessing.cpu_count() * 5
|
|
297
|
+
"""urllib3 connection pool's maximum number of connections saved
|
|
298
|
+
per pool. urllib3 uses 1 connection as default value, but this is
|
|
299
|
+
not the best value when you are making a lot of possibly parallel
|
|
300
|
+
requests to the same host, which is often the case here.
|
|
301
|
+
cpu_count * 5 is used as default value to increase performance.
|
|
302
|
+
"""
|
|
303
|
+
|
|
304
|
+
self.proxy: Optional[str] = None
|
|
305
|
+
"""Proxy URL
|
|
306
|
+
"""
|
|
307
|
+
self.proxy_headers = None
|
|
308
|
+
"""Proxy headers
|
|
309
|
+
"""
|
|
310
|
+
self.safe_chars_for_path_param = ''
|
|
311
|
+
"""Safe chars for path_param
|
|
312
|
+
"""
|
|
313
|
+
self.retries = retries
|
|
314
|
+
"""Adding retries to override urllib3 default value 3
|
|
315
|
+
"""
|
|
316
|
+
# Enable client side validation
|
|
317
|
+
self.client_side_validation = True
|
|
318
|
+
|
|
319
|
+
self.socket_options = None
|
|
320
|
+
"""Options to pass down to the underlying urllib3 socket
|
|
321
|
+
"""
|
|
322
|
+
|
|
323
|
+
self.datetime_format = "%Y-%m-%dT%H:%M:%S.%f%z"
|
|
324
|
+
"""datetime format
|
|
325
|
+
"""
|
|
326
|
+
|
|
327
|
+
self.date_format = "%Y-%m-%d"
|
|
328
|
+
"""date format
|
|
329
|
+
"""
|
|
330
|
+
|
|
331
|
+
def __deepcopy__(self, memo: Dict[int, Any]) -> Self:
|
|
332
|
+
cls = self.__class__
|
|
333
|
+
result = cls.__new__(cls)
|
|
334
|
+
memo[id(self)] = result
|
|
335
|
+
for k, v in self.__dict__.items():
|
|
336
|
+
if k not in ('logger', 'logger_file_handler'):
|
|
337
|
+
setattr(result, k, copy.deepcopy(v, memo))
|
|
338
|
+
# shallow copy of loggers
|
|
339
|
+
result.logger = copy.copy(self.logger)
|
|
340
|
+
# use setters to configure loggers
|
|
341
|
+
result.logger_file = self.logger_file
|
|
342
|
+
result.debug = self.debug
|
|
343
|
+
return result
|
|
344
|
+
|
|
345
|
+
def __setattr__(self, name: str, value: Any) -> None:
|
|
346
|
+
object.__setattr__(self, name, value)
|
|
347
|
+
|
|
348
|
+
@classmethod
|
|
349
|
+
def set_default(cls, default: Optional[Self]) -> None:
|
|
350
|
+
"""Set default instance of configuration.
|
|
351
|
+
|
|
352
|
+
It stores default configuration, which can be
|
|
353
|
+
returned by get_default_copy method.
|
|
354
|
+
|
|
355
|
+
:param default: object of Configuration
|
|
356
|
+
"""
|
|
357
|
+
cls._default = default
|
|
358
|
+
|
|
359
|
+
@classmethod
|
|
360
|
+
def get_default_copy(cls) -> Self:
|
|
361
|
+
"""Deprecated. Please use `get_default` instead.
|
|
362
|
+
|
|
363
|
+
Deprecated. Please use `get_default` instead.
|
|
364
|
+
|
|
365
|
+
:return: The configuration object.
|
|
366
|
+
"""
|
|
367
|
+
return cls.get_default()
|
|
368
|
+
|
|
369
|
+
@classmethod
|
|
370
|
+
def get_default(cls) -> Self:
|
|
371
|
+
"""Return the default configuration.
|
|
372
|
+
|
|
373
|
+
This method returns newly created, based on default constructor,
|
|
374
|
+
object of Configuration class or returns a copy of default
|
|
375
|
+
configuration.
|
|
376
|
+
|
|
377
|
+
:return: The configuration object.
|
|
378
|
+
"""
|
|
379
|
+
if cls._default is None:
|
|
380
|
+
cls._default = cls()
|
|
381
|
+
return cls._default
|
|
382
|
+
|
|
383
|
+
@property
|
|
384
|
+
def logger_file(self) -> Optional[str]:
|
|
385
|
+
"""The logger file.
|
|
386
|
+
|
|
387
|
+
If the logger_file is None, then add stream handler and remove file
|
|
388
|
+
handler. Otherwise, add file handler and remove stream handler.
|
|
389
|
+
|
|
390
|
+
:param value: The logger_file path.
|
|
391
|
+
:type: str
|
|
392
|
+
"""
|
|
393
|
+
return self.__logger_file
|
|
394
|
+
|
|
395
|
+
@logger_file.setter
|
|
396
|
+
def logger_file(self, value: Optional[str]) -> None:
|
|
397
|
+
"""The logger file.
|
|
398
|
+
|
|
399
|
+
If the logger_file is None, then add stream handler and remove file
|
|
400
|
+
handler. Otherwise, add file handler and remove stream handler.
|
|
401
|
+
|
|
402
|
+
:param value: The logger_file path.
|
|
403
|
+
:type: str
|
|
404
|
+
"""
|
|
405
|
+
self.__logger_file = value
|
|
406
|
+
if self.__logger_file:
|
|
407
|
+
# If set logging file,
|
|
408
|
+
# then add file handler and remove stream handler.
|
|
409
|
+
self.logger_file_handler = logging.FileHandler(self.__logger_file)
|
|
410
|
+
self.logger_file_handler.setFormatter(self.logger_formatter)
|
|
411
|
+
for _, logger in self.logger.items():
|
|
412
|
+
logger.addHandler(self.logger_file_handler)
|
|
413
|
+
|
|
414
|
+
@property
|
|
415
|
+
def debug(self) -> bool:
|
|
416
|
+
"""Debug status
|
|
417
|
+
|
|
418
|
+
:param value: The debug status, True or False.
|
|
419
|
+
:type: bool
|
|
420
|
+
"""
|
|
421
|
+
return self.__debug
|
|
422
|
+
|
|
423
|
+
@debug.setter
|
|
424
|
+
def debug(self, value: bool) -> None:
|
|
425
|
+
"""Debug status
|
|
426
|
+
|
|
427
|
+
:param value: The debug status, True or False.
|
|
428
|
+
:type: bool
|
|
429
|
+
"""
|
|
430
|
+
self.__debug = value
|
|
431
|
+
if self.__debug:
|
|
432
|
+
# if debug status is True, turn on debug logging
|
|
433
|
+
for _, logger in self.logger.items():
|
|
434
|
+
logger.setLevel(logging.DEBUG)
|
|
435
|
+
# turn on httplib debug
|
|
436
|
+
httplib.HTTPConnection.debuglevel = 1
|
|
437
|
+
else:
|
|
438
|
+
# if debug status is False, turn off debug logging,
|
|
439
|
+
# setting log level to default `logging.WARNING`
|
|
440
|
+
for _, logger in self.logger.items():
|
|
441
|
+
logger.setLevel(logging.WARNING)
|
|
442
|
+
# turn off httplib debug
|
|
443
|
+
httplib.HTTPConnection.debuglevel = 0
|
|
444
|
+
|
|
445
|
+
@property
|
|
446
|
+
def logger_format(self) -> str:
|
|
447
|
+
"""The logger format.
|
|
448
|
+
|
|
449
|
+
The logger_formatter will be updated when sets logger_format.
|
|
450
|
+
|
|
451
|
+
:param value: The format string.
|
|
452
|
+
:type: str
|
|
453
|
+
"""
|
|
454
|
+
return self.__logger_format
|
|
455
|
+
|
|
456
|
+
@logger_format.setter
|
|
457
|
+
def logger_format(self, value: str) -> None:
|
|
458
|
+
"""The logger format.
|
|
459
|
+
|
|
460
|
+
The logger_formatter will be updated when sets logger_format.
|
|
461
|
+
|
|
462
|
+
:param value: The format string.
|
|
463
|
+
:type: str
|
|
464
|
+
"""
|
|
465
|
+
self.__logger_format = value
|
|
466
|
+
self.logger_formatter = logging.Formatter(self.__logger_format)
|
|
467
|
+
|
|
468
|
+
def get_api_key_with_prefix(self, identifier: str, alias: Optional[str]=None) -> Optional[str]:
|
|
469
|
+
"""Gets API key (with prefix if set).
|
|
470
|
+
|
|
471
|
+
:param identifier: The identifier of apiKey.
|
|
472
|
+
:param alias: The alternative identifier of apiKey.
|
|
473
|
+
:return: The token for api key authentication.
|
|
474
|
+
"""
|
|
475
|
+
if self.refresh_api_key_hook is not None:
|
|
476
|
+
self.refresh_api_key_hook(self)
|
|
477
|
+
key = self.api_key.get(identifier, self.api_key.get(alias) if alias is not None else None)
|
|
478
|
+
if key:
|
|
479
|
+
prefix = self.api_key_prefix.get(identifier)
|
|
480
|
+
if prefix:
|
|
481
|
+
return "%s %s" % (prefix, key)
|
|
482
|
+
else:
|
|
483
|
+
return key
|
|
484
|
+
|
|
485
|
+
return None
|
|
486
|
+
|
|
487
|
+
def get_basic_auth_token(self) -> Optional[str]:
|
|
488
|
+
"""Gets HTTP basic authentication header (string).
|
|
489
|
+
|
|
490
|
+
:return: The token for basic HTTP authentication.
|
|
491
|
+
"""
|
|
492
|
+
username = ""
|
|
493
|
+
if self.username is not None:
|
|
494
|
+
username = self.username
|
|
495
|
+
password = ""
|
|
496
|
+
if self.password is not None:
|
|
497
|
+
password = self.password
|
|
498
|
+
return urllib3.util.make_headers(
|
|
499
|
+
basic_auth=username + ':' + password
|
|
500
|
+
).get('authorization')
|
|
501
|
+
|
|
502
|
+
def auth_settings(self)-> AuthSettings:
|
|
503
|
+
"""Gets Auth Settings dict for api client.
|
|
504
|
+
|
|
505
|
+
:return: The Auth Settings information dict.
|
|
506
|
+
"""
|
|
507
|
+
auth: AuthSettings = {}
|
|
508
|
+
if 'Bearer' in self.api_key:
|
|
509
|
+
auth['Bearer'] = {
|
|
510
|
+
'type': 'api_key',
|
|
511
|
+
'in': 'header',
|
|
512
|
+
'key': 'Authorization',
|
|
513
|
+
'value': self.get_api_key_with_prefix(
|
|
514
|
+
'Bearer',
|
|
515
|
+
),
|
|
516
|
+
}
|
|
517
|
+
return auth
|
|
518
|
+
|
|
519
|
+
def to_debug_report(self) -> str:
|
|
520
|
+
"""Gets the essential information for debugging.
|
|
521
|
+
|
|
522
|
+
:return: The report for debugging.
|
|
523
|
+
"""
|
|
524
|
+
return "Python SDK Debug Report:\n"\
|
|
525
|
+
"OS: {env}\n"\
|
|
526
|
+
"Python Version: {pyversion}\n"\
|
|
527
|
+
"Version of the API: v1\n"\
|
|
528
|
+
"SDK Package Version: 0.1.0".\
|
|
529
|
+
format(env=sys.platform, pyversion=sys.version)
|
|
530
|
+
|
|
531
|
+
def get_host_settings(self) -> List[HostSetting]:
|
|
532
|
+
"""Gets an array of host settings
|
|
533
|
+
|
|
534
|
+
:return: An array of host settings
|
|
535
|
+
"""
|
|
536
|
+
return [
|
|
537
|
+
{
|
|
538
|
+
'url': "https://l0ads.signedly.com",
|
|
539
|
+
'description': "No description provided",
|
|
540
|
+
}
|
|
541
|
+
]
|
|
542
|
+
|
|
543
|
+
def get_host_from_settings(
|
|
544
|
+
self,
|
|
545
|
+
index: Optional[int],
|
|
546
|
+
variables: Optional[ServerVariablesT]=None,
|
|
547
|
+
servers: Optional[List[HostSetting]]=None,
|
|
548
|
+
) -> str:
|
|
549
|
+
"""Gets host URL based on the index and variables
|
|
550
|
+
:param index: array index of the host settings
|
|
551
|
+
:param variables: hash of variable and the corresponding value
|
|
552
|
+
:param servers: an array of host settings or None
|
|
553
|
+
:return: URL based on host settings
|
|
554
|
+
"""
|
|
555
|
+
if index is None:
|
|
556
|
+
return self._base_path
|
|
557
|
+
|
|
558
|
+
variables = {} if variables is None else variables
|
|
559
|
+
servers = self.get_host_settings() if servers is None else servers
|
|
560
|
+
|
|
561
|
+
try:
|
|
562
|
+
server = servers[index]
|
|
563
|
+
except IndexError:
|
|
564
|
+
raise ValueError(
|
|
565
|
+
"Invalid index {0} when selecting the host settings. "
|
|
566
|
+
"Must be less than {1}".format(index, len(servers)))
|
|
567
|
+
|
|
568
|
+
url = server['url']
|
|
569
|
+
|
|
570
|
+
# go through variables and replace placeholders
|
|
571
|
+
for variable_name, variable in server.get('variables', {}).items():
|
|
572
|
+
used_value = variables.get(
|
|
573
|
+
variable_name, variable['default_value'])
|
|
574
|
+
|
|
575
|
+
if 'enum_values' in variable \
|
|
576
|
+
and used_value not in variable['enum_values']:
|
|
577
|
+
raise ValueError(
|
|
578
|
+
"The variable `{0}` in the host URL has invalid value "
|
|
579
|
+
"{1}. Must be {2}.".format(
|
|
580
|
+
variable_name, variables[variable_name],
|
|
581
|
+
variable['enum_values']))
|
|
582
|
+
|
|
583
|
+
url = url.replace("{" + variable_name + "}", used_value)
|
|
584
|
+
|
|
585
|
+
return url
|
|
586
|
+
|
|
587
|
+
@property
|
|
588
|
+
def host(self) -> str:
|
|
589
|
+
"""Return generated host."""
|
|
590
|
+
return self.get_host_from_settings(self.server_index, variables=self.server_variables)
|
|
591
|
+
|
|
592
|
+
@host.setter
|
|
593
|
+
def host(self, value: str) -> None:
|
|
594
|
+
"""Fix base path."""
|
|
595
|
+
self._base_path = value
|
|
596
|
+
self.server_index = None
|