From 88fcd4945f9213b37c43044d9ab6fe2066ea9618 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matou=C5=A1=20Dzivjak?= Date: Fri, 23 Oct 2026 23:24:05 +0200 Subject: [PATCH] feat!: add consistent API error handling Classify HTTP failures by status so integrations can catch authentication, permission, rate-limit, and server errors consistently across endpoints. Keep documented error details as typed bodies and preserve the original response, with decoded JSON or text for unrecognized bodies. Wrap connection failures and timeouts in SDK exceptions while retaining the original cause. Update the generator, README examples, and sync, async, and event-fetch regression coverage. BREAKING CHANGE: Documented error bodies now contain typed models or collections instead of response text. Inspect error.body directly or use error.response.text for the original text. Connection failures and timeouts now raise SDK exceptions; the original transport exception is available through error.__cause__. Refs #434. --- README.md | 32 + codegen/pkg/builder/builder.go | 4 +- codegen/pkg/builder/doc.go | 3 +- codegen/pkg/builder/doc_test.go | 6 +- codegen/pkg/builder/error_responses_test.go | 111 ++ codegen/pkg/builder/errors.go | 96 ++ .../builder/intermediate_representation.go | 14 +- codegen/pkg/builder/methods.go | 15 +- codegen/pkg/builder/out.go | 10 +- codegen/pkg/builder/transform.go | 31 +- codegen/templates/resource.py.tmpl | 36 +- sumup/_events.py | 36 +- sumup/_exceptions.py | 168 ++- sumup/checkouts/__init__.py | 8 + sumup/checkouts/resource.py | 488 ++++--- sumup/customers/__init__.py | 4 + sumup/customers/resource.py | 369 ++--- sumup/errors.py | 33 + sumup/members/resource.py | 270 ++-- sumup/memberships/resource.py | 60 +- sumup/merchants/resource.py | 118 +- sumup/payouts/__init__.py | 2 + sumup/payouts/resource.py | 71 +- sumup/readers/resource.py | 1244 +++++++++++------ sumup/receipts/resource.py | 78 +- sumup/roles/resource.py | 206 +-- sumup/tokens/resource.py | 98 +- sumup/transactions/__init__.py | 2 + sumup/transactions/resource.py | 222 +-- sumup/types/__init__.py | 12 + tests/test_api_errors.py | 441 ++++++ tests/test_events.py | 90 +- 32 files changed, 2965 insertions(+), 1413 deletions(-) create mode 100644 codegen/pkg/builder/error_responses_test.go create mode 100644 codegen/pkg/builder/errors.go create mode 100644 sumup/errors.py create mode 100644 tests/test_api_errors.py diff --git a/README.md b/README.md index 5e7ef22a..32654a52 100644 --- a/README.md +++ b/README.md @@ -78,6 +78,38 @@ For long-running applications, reuse a client across requests and call `client.c or `await client.aclose()` during shutdown, after outstanding work finishes. A closed client cannot be reused. +### Handling errors + +Catch `APIError` to handle failed requests, or use a specific exception such as +`RateLimitError` when your application needs to handle a failure differently. + +When the API returns a Problem response, `error.problem` gives you typed fields +such as `type`, `title`, and `detail`. It is `None` for other error responses. + +```python +from sumup import APIError, Sumup +from sumup.errors import APIStatusError, RateLimitError + +with Sumup() as client: + try: + checkout = client.checkouts.get("your-checkout-id") + except RateLimitError: + print("Too many requests. Try again later.") + except APIStatusError as error: + if (problem := error.problem) is not None: + print(problem.type, problem.detail) + else: + print(error) + except APIError as error: + print(error) +``` + +For errors returned by the API, `error.status` gives you the HTTP status, +`error.body` holds the full error details, and `error.response` provides the +original response, including its headers and text. + +Use the same `try`/`except` pattern with `AsyncSumup`. + ### Creating a Checkout ```python diff --git a/codegen/pkg/builder/builder.go b/codegen/pkg/builder/builder.go index 6ad8e59d..7b17a384 100644 --- a/codegen/pkg/builder/builder.go +++ b/codegen/pkg/builder/builder.go @@ -34,7 +34,8 @@ type Builder struct { pathsByTag map[string]*v3.Paths - events []EventDefinition + events []EventDefinition + errorBodyTypes []Writable templates *template.Template @@ -85,6 +86,7 @@ func (b *Builder) Load(spec *v3.Document) error { b.collectPaths() b.collectSchemas() + _, b.errorBodyTypes = b.pathsToResponseTypes(b.spec.Paths) if err := b.collectEvents(); err != nil { return err } diff --git a/codegen/pkg/builder/doc.go b/codegen/pkg/builder/doc.go index 2c6ff03a..604f1e56 100644 --- a/codegen/pkg/builder/doc.go +++ b/codegen/pkg/builder/doc.go @@ -63,6 +63,7 @@ func methodRaisesDoc(responses []Response) string { if description == "" { description = "the API returns an error response" } + description += fmt.Sprintf(" (raises %s)", response.ErrorType()) if response.IsDefault { errorDescriptions = append(errorDescriptions, description) @@ -73,7 +74,7 @@ func methodRaisesDoc(responses []Response) string { } out := new(strings.Builder) - out.WriteString("Raises:\n") + out.WriteString("Raises:\n APITimeoutError: The request timed out.\n APIConnectionError: The request failed because of a connection error.\n") if len(errorDescriptions) == 0 { out.WriteString(" APIError: Raised when the API returns an unexpected response.") return out.String() diff --git a/codegen/pkg/builder/doc_test.go b/codegen/pkg/builder/doc_test.go index 223aba49..676830f0 100644 --- a/codegen/pkg/builder/doc_test.go +++ b/codegen/pkg/builder/doc_test.go @@ -19,7 +19,7 @@ func TestMethodDocIncludesRaisesForDocumentedErrors(t *testing.T) { {Code: 401, IsErr: true, ErrDescription: "The request is not authorized."}, }) - if !strings.Contains(doc, "Raises:\n APIError:") { + if !strings.Contains(doc, " APIError:") { t.Fatalf("expected Raises section in docstring, got %q", doc) } @@ -27,7 +27,7 @@ func TestMethodDocIncludesRaisesForDocumentedErrors(t *testing.T) { t.Fatalf("expected 400 response in Raises section, got %q", doc) } - if !strings.Contains(doc, "401: The request is not authorized.") { + if !strings.Contains(doc, "401: The request is not authorized. (raises AuthenticationError)") { t.Fatalf("expected 401 response in Raises section, got %q", doc) } @@ -46,7 +46,7 @@ func TestMethodDocIncludesRaisesForUnexpectedResponsesOnly(t *testing.T) { {Code: 204}, }) - if !strings.Contains(doc, "Raises:\n APIError: Raised when the API returns an unexpected response.") { + if !strings.Contains(doc, " APIError: Raised when the API returns an unexpected response.") { t.Fatalf("expected fallback Raises section in docstring, got %q", doc) } } diff --git a/codegen/pkg/builder/error_responses_test.go b/codegen/pkg/builder/error_responses_test.go new file mode 100644 index 00000000..8e45be7f --- /dev/null +++ b/codegen/pkg/builder/error_responses_test.go @@ -0,0 +1,111 @@ +package builder + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/pb33f/libopenapi" +) + +func TestGenerateErrorResponseTypes(t *testing.T) { + t.Parallel() + + document, err := libopenapi.NewDocument([]byte(`{ + "openapi": "3.1.0", + "info": {"title": "Errors", "version": "1.0.0"}, + "paths": { + "/things": { + "get": { + "tags": ["Things"], + "operationId": "GetThing", + "responses": { + "200": {"description": "Success", "content": {"application/json": { + "schema": {"$ref": "#/components/schemas/Thing"} + }}}, + "400": {"description": "Invalid", "content": {"application/json": { + "schema": {"oneOf": [ + {"$ref": "#/components/schemas/Error"}, + {"type": "array", "items": {"$ref": "#/components/schemas/Error"}} + ]} + }, "application/problem+json": { + "schema": {"$ref": "#/components/schemas/Problem"} + }}}, + "401": {"$ref": "#/components/responses/Unauthorized"}, + "422": {"description": "Validation errors", "content": {"application/json": { + "schema": {"type": "array", "items": {"$ref": "#/components/schemas/Problem"}} + }}}, + "500": {"description": "Unknown error", "content": {"application/json": {}}} + } + } + } + }, + "components": { + "responses": { + "Unauthorized": {"description": "Unauthorized", "content": {"application/problem+json": { + "schema": {"$ref": "#/components/schemas/Problem"} + }}} + }, + "schemas": { + "Thing": {"type": "object", "properties": {"id": {"type": "string"}}}, + "Error": {"type": "object", "properties": {"message": {"type": "string"}}}, + "Problem": {"type": "object", "required": ["type"], "properties": {"type": {"type": "string"}}} + } + } +}`)) + if err != nil { + t.Fatal(err) + } + model, err := document.BuildV3Model() + if err != nil { + t.Fatal(err) + } + out := t.TempDir() + cwd, err := os.Getwd() + if err != nil { + t.Fatal(err) + } + relativeOut, err := filepath.Rel(cwd, out) + if err != nil { + t.Fatal(err) + } + generator := New(Config{Out: relativeOut}) + if err := generator.Load(&model.Model); err != nil { + t.Fatal(err) + } + if err := generator.Build(); err != nil { + t.Fatal(err) + } + + checks := map[string][]string{ + "types/__init__.py": { + "GetThingJson400Response = Error | list[Error]", + "GetThing422Response = list[Problem]", + }, + "things/resource.py": { + `content_type == "application/json"`, + `content_type == "application/problem+json"`, + `APIError.from_response("Invalid", resp, body_type=GetThingJson400Response)`, + `APIError.from_response("Invalid", resp, body_type=Problem)`, + "raises BadRequestError", + `APIError.from_response("Validation errors", resp, body_type=GetThing422Response)`, + `APIError.from_response("Unauthorized", resp, body_type=Problem)`, + `APIError.from_response("Unknown error", resp)`, + "-> Thing:", + "with _wrap_request_errors():", + }, + "things/__init__.py": {`"GetThingJson400Response"`, `"GetThing422Response"`}, + } + for filename, snippets := range checks { + data, err := os.ReadFile(filepath.Join(out, filename)) + if err != nil { + t.Fatal(err) + } + for _, snippet := range snippets { + if !strings.Contains(string(data), snippet) { + t.Errorf("%s missing %q", filename, snippet) + } + } + } +} diff --git a/codegen/pkg/builder/errors.go b/codegen/pkg/builder/errors.go new file mode 100644 index 00000000..3debf228 --- /dev/null +++ b/codegen/pkg/builder/errors.go @@ -0,0 +1,96 @@ +package builder + +import ( + "fmt" + "strings" + + v3 "github.com/pb33f/libopenapi/datamodel/high/v3" +) + +type errorResponseFormat struct { + ContentType string + Type string + content *v3.MediaType +} + +func (b *Builder) errorResponseFormats(operationName string, response *v3.Response, code string) []errorResponseFormat { + var formats []errorResponseFormat + for contentType, content := range response.Content.FromOldest() { + if contentType != "application/json" && contentType != "application/problem+json" { + continue + } + if content == nil || content.Schema == nil || content.Schema.Schema() == nil { + continue + } + formats = append(formats, errorResponseFormat{ContentType: contentType, content: content}) + } + for i := range formats { + format := &formats[i] + if format.content.Schema.IsReference() { + format.Type = b.getReferenceSchema(format.content.Schema) + continue + } + name := operationName + if len(formats) > 1 { + if format.ContentType == "application/problem+json" { + name += "Problem" + } else { + name += "Json" + } + } + format.Type = b.getResponseName(name, code, format.content) + } + return formats +} + +func errorRaise(message, bodyType string) string { + argument := "" + if bodyType != "" { + argument = ", body_type=" + bodyType + } + return fmt.Sprintf("raise APIError.from_response(%q, resp%s)", message, argument) +} + +func (response Response) ErrorStatement() string { + if len(response.Formats) == 0 { + return errorRaise(response.ErrDescription, response.Type) + } + var output strings.Builder + output.WriteString("content_type = resp.headers.get(\"Content-Type\", \"\").split(\";\", 1)[0].strip().lower()\n") + for i, format := range response.Formats { + condition := "elif" + if i == 0 { + condition = "if" + } + fmt.Fprintf(&output, "%s content_type == %q:\n\t%s\n", condition, format.ContentType, + errorRaise(response.ErrDescription, format.Type)) + } + fmt.Fprintf(&output, "else:\n\t%s", errorRaise(response.ErrDescription, "")) + return output.String() +} + +func (response Response) ErrorType() string { + switch response.Code { + case 400: + return "BadRequestError" + case 401: + return "AuthenticationError" + case 403: + return "PermissionDeniedError" + case 404: + return "NotFoundError" + case 409: + return "ConflictError" + case 422: + return "UnprocessableEntityError" + case 429: + return "RateLimitError" + } + if response.Code >= 500 && response.Code < 600 { + return "InternalServerError" + } + if response.Code >= 400 && response.Code < 500 { + return "APIStatusError" + } + return "APIError" +} diff --git a/codegen/pkg/builder/intermediate_representation.go b/codegen/pkg/builder/intermediate_representation.go index 55c34cb9..18b4a86e 100644 --- a/codegen/pkg/builder/intermediate_representation.go +++ b/codegen/pkg/builder/intermediate_representation.go @@ -79,10 +79,12 @@ type EnumDeclaration[E cmp.Ordered] struct { } type Response struct { - IsErr bool - IsDefault bool - IsUnexpected bool - Type string + IsErr bool + IsDefault bool + IsUnexpected bool + Type string + // Formats selects the parser by media type when a status has multiple formats. + Formats []errorResponseFormat Code int ErrDescription string } @@ -99,6 +101,10 @@ type TypeAlias struct { GenerateInput bool } +func (ta *TypeAlias) TypeName() string { + return ta.Name +} + func (ta *TypeAlias) String() string { buf := new(strings.Builder) if ta.RequestOnly { diff --git a/codegen/pkg/builder/methods.go b/codegen/pkg/builder/methods.go index ed95eb50..a036428d 100644 --- a/codegen/pkg/builder/methods.go +++ b/codegen/pkg/builder/methods.go @@ -214,10 +214,19 @@ func (b *Builder) operationToMethod(method, path string, o *v3.Operation) (*Meth } statusCode, _ := strconv.Atoi(strings.ReplaceAll(code, "XX", "00")) + var formats []errorResponseFormat + if !strings.HasPrefix(code, "2") { + formats = b.errorResponseFormats(operationName, resp, code) + if len(formats) == 1 { + typ = formats[0].Type + formats = nil + } + } responses = append(responses, Response{ IsErr: !strings.HasPrefix(code, "2"), IsDefault: code == "default", Type: typ, + Formats: formats, Code: statusCode, ErrDescription: strings.TrimSpace(description), }) @@ -343,16 +352,12 @@ func (b *Builder) getSuccessResponseType(o *v3.Operation) (*string, error) { } func (b *Builder) responseToType(operationName string, resp *v3.Response, code string) string { - if resp.GoLow().IsReference() { - return strcase.ToCamel(strings.TrimPrefix(resp.GoLow().GetReference(), "#/components/responses/")) + "Response" - } - if resp.Content == nil { return "" } content, ok := preferredResponseContent(resp.Content) - if !ok { + if !ok || content.Schema == nil { return "" } diff --git a/codegen/pkg/builder/out.go b/codegen/pkg/builder/out.go index c5b3414d..bf1d32ee 100644 --- a/codegen/pkg/builder/out.go +++ b/codegen/pkg/builder/out.go @@ -36,6 +36,7 @@ func (b *Builder) generateSharedTypes() error { types = append(types, generated...) } } + types = append(types, b.errorBodyTypes...) usesSecret := usesSecretType(types) typesBuf := bytes.NewBuffer(nil) @@ -125,8 +126,13 @@ func (b *Builder) generateResourceFile(tagName string, paths *v3.Paths) ([]strin paramTypes := b.pathsToParamTypes(paths) innerTypes = append(innerTypes, paramTypes...) - responseTypes := b.pathsToResponseTypes(paths) + responseTypes, errorTypes := b.pathsToResponseTypes(paths) innerTypes = append(innerTypes, responseTypes...) + for _, typ := range errorTypes { + if named, ok := typ.(Type); ok { + typeNames = append(typeNames, named.TypeName()) + } + } methods, err := b.pathsToMethods(paths) if err != nil { @@ -173,7 +179,7 @@ func (b *Builder) generateResourceFile(tagName string, paths *v3.Paths) ([]strin } resourceTypes := make([]string, 0, len(innerTypes)) - for _, t := range innerTypes { + for _, t := range append(innerTypes, errorTypes...) { if typ, ok := t.(Type); ok { if writableRequestOnly(t) { continue diff --git a/codegen/pkg/builder/transform.go b/codegen/pkg/builder/transform.go index cd503aad..2a856e62 100644 --- a/codegen/pkg/builder/transform.go +++ b/codegen/pkg/builder/transform.go @@ -123,23 +123,25 @@ func parameterFieldName(name string) string { // pathsToResponseTypes generates response types for operations. This is responsible only for inlined // schemas that are specific to the operation itself and are not references. -func (b *Builder) pathsToResponseTypes(paths *v3.Paths) []Writable { +func (b *Builder) pathsToResponseTypes(paths *v3.Paths) (successTypes, errorTypes []Writable) { if paths == nil { - return nil + return nil, nil } - responseTypes := make([]Writable, 0) for _, pathSpec := range paths.PathItems.FromOldest() { for _, opSpec := range pathSpec.GetOperations().FromOldest() { operationName := strcase.ToCamel(opSpec.OperationId) var successResponses []string for code, response := range opSpec.Responses.Codes.FromOldest() { - isSuccess := strings.HasPrefix(code, "2") - if !isSuccess { + if !strings.HasPrefix(code, "2") { + for _, format := range b.errorResponseFormats(operationName, response, code) { + if !format.content.Schema.IsReference() { + errorTypes = append(errorTypes, b.generateSchemaComponents(format.Type, format.content.Schema.Schema())...) + } + } continue } - if response.Content == nil { continue } @@ -163,20 +165,17 @@ func (b *Builder) pathsToResponseTypes(paths *v3.Paths) []Writable { name := b.getResponseName(operationName, code, content) objects := b.generateSchemaComponents(name, content.Schema.Schema()) - responseTypes = append(responseTypes, objects...) - - if strings.HasPrefix(code, "2") { - if resp, ok := objects[len(objects)-1].(*ClassDeclaration); ok { - successResponses = append(successResponses, resp.Name) - } else if resp, ok := objects[len(objects)-1].(*TypeAlias); ok { - successResponses = append(successResponses, resp.Name) - } + successTypes = append(successTypes, objects...) + if resp, ok := objects[len(objects)-1].(*ClassDeclaration); ok { + successResponses = append(successResponses, resp.Name) + } else if resp, ok := objects[len(objects)-1].(*TypeAlias); ok { + successResponses = append(successResponses, resp.Name) } } // if there are multiple success responses, we need to create a oneOf type if len(successResponses) > 1 { - responseTypes = append(responseTypes, &OneOfDeclaration{ + successTypes = append(successTypes, &OneOfDeclaration{ Name: operationName + "Response", Options: successResponses, }) @@ -184,7 +183,7 @@ func (b *Builder) pathsToResponseTypes(paths *v3.Paths) []Writable { } } - return responseTypes + return successTypes, errorTypes } // generateSchemaComponents generates types from schema reference. diff --git a/codegen/templates/resource.py.tmpl b/codegen/templates/resource.py.tmpl index b8e3cded..8b4a99c3 100644 --- a/codegen/templates/resource.py.tmpl +++ b/codegen/templates/resource.py.tmpl @@ -7,7 +7,7 @@ {{- end }} from __future__ import annotations from .._service import Resource, AsyncResource, HeaderTypes, NotGivenType, NOT_GIVEN, serialize_query_params, serialize_request_data -from .._exceptions import APIError +from .._exceptions import APIError, _wrap_request_errors {{- if .UsesSecret }} from .._secret import Secret {{- end }} @@ -53,20 +53,21 @@ class {{.Service}}Resource(Resource): {{ indent 2 .QueryInitString }} {{- end }} - resp = self._client.{{.Method}}({{.Path}}, + with _wrap_request_errors(): + resp = self._client.{{.Method}}({{.Path}}, {{- if .HasBody }} - json=serialize_request_data({{- if .HasFlattenedBody }}body_data{{- else }}body{{- end }}), + json=serialize_request_data({{- if .HasFlattenedBody }}body_data{{- else }}body{{- end }}), {{- end }} {{- if .QueryFields }} - params=serialize_query_params(query_data) if query_data else None, + params=serialize_query_params(query_data) if query_data else None, {{- end }} - headers=headers, - ) + headers=headers, + ) {{- range $i, $res := .Responses }} {{- if eq $i 0 }} if resp.status_code == {{ .Code }}: {{- if .IsErr }} - raise APIError("{{ .ErrDescription }}", status=resp.status_code, body=resp.text) +{{ indent 3 .ErrorStatement }} {{- else if .Type }} return pydantic.TypeAdapter({{ .Type }}).validate_python(resp.json()) {{- else }} @@ -75,7 +76,7 @@ class {{.Service}}Resource(Resource): {{- else }} elif resp.status_code == {{ .Code }}: {{- if .IsErr }} - raise APIError("{{ .ErrDescription }}", status=resp.status_code, body=resp.text) +{{ indent 3 .ErrorStatement }} {{- else if .Type }} return pydantic.TypeAdapter({{ .Type }}).validate_python(resp.json()) {{- else }} @@ -84,7 +85,7 @@ class {{.Service}}Resource(Resource): {{- end }} {{- end }} else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) {{end}} class Async{{.Service}}Resource(AsyncResource): @@ -111,20 +112,21 @@ class Async{{.Service}}Resource(AsyncResource): {{ indent 2 .QueryInitString }} {{- end }} - resp = await self._client.{{.Method}}({{.Path}}, + with _wrap_request_errors(): + resp = await self._client.{{.Method}}({{.Path}}, {{- if .HasBody }} - json=serialize_request_data({{- if .HasFlattenedBody }}body_data{{- else }}body{{- end }}), + json=serialize_request_data({{- if .HasFlattenedBody }}body_data{{- else }}body{{- end }}), {{- end }} {{- if .QueryFields }} - params=serialize_query_params(query_data) if query_data else None, + params=serialize_query_params(query_data) if query_data else None, {{- end }} - headers=headers, - ) + headers=headers, + ) {{- range $i, $res := .Responses }} {{- if eq $i 0 }} if resp.status_code == {{ .Code }}: {{- if .IsErr }} - raise APIError("{{ .ErrDescription }}", status=resp.status_code, body=resp.text) +{{ indent 3 .ErrorStatement }} {{- else if .Type }} return pydantic.TypeAdapter({{ .Type }}).validate_python(resp.json()) {{- else }} @@ -133,7 +135,7 @@ class Async{{.Service}}Resource(AsyncResource): {{- else }} elif resp.status_code == {{ .Code }}: {{- if .IsErr }} - raise APIError("{{ .ErrDescription }}", status=resp.status_code, body=resp.text) +{{ indent 3 .ErrorStatement }} {{- else if .Type }} return pydantic.TypeAdapter({{ .Type }}).validate_python(resp.json()) {{- else }} @@ -142,5 +144,5 @@ class Async{{.Service}}Resource(AsyncResource): {{- end }} {{- end }} else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) {{end}} diff --git a/sumup/_events.py b/sumup/_events.py index 99163836..bb9264ff 100644 --- a/sumup/_events.py +++ b/sumup/_events.py @@ -14,7 +14,7 @@ import httpx import pydantic -from ._exceptions import APIError, SumupError +from ._exceptions import APIError, SumupError, _wrap_request_errors SIGNATURE_HEADER = "X-SumUp-Webhook-Signature" """Header containing the signing timestamp and signature. Pass its complete value.""" @@ -128,11 +128,7 @@ class FetchableEvent(EventNotification, Generic[_ObjectT]): def _parse_response(self, response: httpx.Response) -> _ObjectT: if not response.is_success: - try: - body = response.json() - except ValueError: - body = response.text - raise APIError("Unable to fetch event object", status=response.status_code, body=body) + raise APIError.from_response("Unable to fetch event object", response) return cast(_ObjectT, self._response_model.model_validate_json(response.content)) def fetch_object(self) -> _ObjectT: @@ -151,19 +147,23 @@ def fetch_object(self) -> _ObjectT: Raises: EventObjectUrlError: The resource URL is invalid or uses another API origin. - APIError: The API returns a non-2xx response; status and body are available. + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. + APIStatusError: The API returns an HTTP 4xx or 5xx response. + APIError: The API returns another unexpected response. EventError: The event was not parsed with an API client. TypeError: The event belongs to AsyncSumup; use fetch_object_async(). - HTTPX transport errors and Pydantic response-validation errors propagate. + Pydantic response-validation errors propagate. """ if self._client is None: raise EventError("event notification is not bound to a SumUp client") if not isinstance(self._client, httpx.Client): raise TypeError("use fetch_object_async() with an AsyncSumup client") - response = self._client.get( - _validated_object_url(self._client, self.object.url), follow_redirects=False - ) + with _wrap_request_errors(): + response = self._client.get( + _validated_object_url(self._client, self.object.url), follow_redirects=False + ) return self._parse_response(response) async def fetch_object_async(self) -> _ObjectT: @@ -178,19 +178,23 @@ async def fetch_object_async(self) -> _ObjectT: Raises: EventObjectUrlError: The resource URL is invalid or uses another API origin. - APIError: The API returns a non-2xx response; status and body are available. + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. + APIStatusError: The API returns an HTTP 4xx or 5xx response. + APIError: The API returns another unexpected response. EventError: The event was not parsed with an API client. TypeError: The event belongs to Sumup; use fetch_object(). - HTTPX transport errors and Pydantic response-validation errors propagate. + Pydantic response-validation errors propagate. """ if self._client is None: raise EventError("event notification is not bound to a SumUp client") if not isinstance(self._client, httpx.AsyncClient): raise TypeError("use fetch_object() with a Sumup client") - response = await self._client.get( - _validated_object_url(self._client, self.object.url), follow_redirects=False - ) + with _wrap_request_errors(): + response = await self._client.get( + _validated_object_url(self._client, self.object.url), follow_redirects=False + ) return self._parse_response(response) diff --git a/sumup/_exceptions.py b/sumup/_exceptions.py index fbcafc1c..b64a45e7 100644 --- a/sumup/_exceptions.py +++ b/sumup/_exceptions.py @@ -1,25 +1,173 @@ +from __future__ import annotations + +from collections.abc import Generator +from contextlib import contextmanager + +import httpx +import pydantic + +from .types import Problem + + +def _error_message(body: object) -> str | None: + if not isinstance(body, pydantic.BaseModel): + return None + for field in ("detail", "details", "message", "error_message", "title"): + message = getattr(body, field, None) + if isinstance(message, str) and message: + return message + return _error_message(getattr(body, "errors", None)) + + class SumupError(Exception): - pass + """Base class for SumUp SDK errors.""" class APIError(SumupError): + """Base class for API response, connection, and timeout errors.""" + message: str + """A readable description of the failure.""" status: int | None body: object | None - """The API response body. - - If the API responded with a valid JSON structure then this property will be the - decoded result. + """The response body, parsed into its documented type when available. - If it isn't a valid JSON structure then this will be the raw response. + Documented JSON errors use the generated Pydantic models, including arrays and + unions. Responses with the application/problem+json media type use Problem + when no documented type is available. Other unexpected responses or bodies + that do not match their type retain decoded JSON. Invalid JSON and empty + responses are preserved as text. - If there was no response associated with this error then it will be `None`. + A JSON null response or an error constructed without a body has a value of None. """ - def __init__(self, message: str, *, status: int | None, body: object | None) -> None: - super().__init__(message) - self.message = message + response: httpx.Response | None + """The original HTTP response, or None when constructed without one.""" + + def __init__( + self, + message: str, + *, + status: int | None = None, + body: object | None = None, + response: httpx.Response | None = None, + ) -> None: + bodies = body if isinstance(body, list) else [body] + messages = [text for item in bodies if (text := _error_message(item))] + self.message = "; ".join(messages) or message + super().__init__(self.message) self.status = status self.body = body + self.response = response + + def __str__(self) -> str: + return f"HTTP {self.status}: {self.message}" if self.status is not None else self.message + + @staticmethod + def from_response( + message: str, response: httpx.Response, *, body_type: object | None = None + ) -> APIError: + """Classify the HTTP failure and preserve its documented response body.""" + content_type = response.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if body_type is None and content_type == "application/problem+json": + body_type = Problem + try: + body = response.json() + except ValueError: + body = response.text + else: + if body_type is not None: + try: + body = pydantic.TypeAdapter(body_type).validate_python(body) + except pydantic.ValidationError: + pass + if 400 <= response.status_code < 600: + error_type = _STATUS_ERRORS.get(response.status_code, APIStatusError) + if response.status_code >= 500: + error_type = InternalServerError + return error_type(message, body=body, response=response) + return APIError(message, status=response.status_code, body=body, response=response) + + +class APIStatusError(APIError): + """The API returned an HTTP 4xx or 5xx response.""" + + def __init__( + self, message: str, *, response: httpx.Response, body: object | None = None + ) -> None: + super().__init__(message, status=response.status_code, body=body, response=response) + + @property + def problem(self) -> Problem | None: + """The parsed Problem body, or None when the body has another format.""" + return self.body if isinstance(self.body, Problem) else None + + +class BadRequestError(APIStatusError): + """The API rejected the request (HTTP 400).""" + + +class AuthenticationError(APIStatusError): + """Authentication failed (HTTP 401).""" + + +class PermissionDeniedError(APIStatusError): + """The credentials do not allow this operation (HTTP 403).""" + + +class NotFoundError(APIStatusError): + """The requested resource was not found (HTTP 404).""" + + +class ConflictError(APIStatusError): + """The request conflicts with the resource's current state (HTTP 409).""" + + +class UnprocessableEntityError(APIStatusError): + """The API could not process the request (HTTP 422).""" + + +class RateLimitError(APIStatusError): + """The API's request limit was exceeded (HTTP 429).""" + + +class InternalServerError(APIStatusError): + """The API returned a server error (HTTP 5xx).""" + + +class APIConnectionError(APIError): + """The request failed because of a connection or transport error.""" + + def __init__(self, *, request: httpx.Request, message: str = "Connection error.") -> None: + super().__init__(message) + self.request = request + + +class APITimeoutError(APIConnectionError): + """The request timed out.""" + + def __init__(self, *, request: httpx.Request) -> None: + super().__init__(request=request, message="Request timed out.") + + +_STATUS_ERRORS: dict[int, type[APIStatusError]] = { + 400: BadRequestError, + 401: AuthenticationError, + 403: PermissionDeniedError, + 404: NotFoundError, + 409: ConflictError, + 422: UnprocessableEntityError, + 429: RateLimitError, +} + + +@contextmanager +def _wrap_request_errors() -> Generator[None, None, None]: + try: + yield + except httpx.TimeoutException as cause: + raise APITimeoutError(request=cause.request) from cause + except httpx.RequestError as cause: + raise APIConnectionError(request=cause.request) from cause diff --git a/sumup/checkouts/__init__.py b/sumup/checkouts/__init__.py index cbb86cac..e91a132d 100644 --- a/sumup/checkouts/__init__.py +++ b/sumup/checkouts/__init__.py @@ -28,8 +28,12 @@ from .resource import ( AsyncCheckoutsResource, CheckoutsResource, + CreateApplePaySession200Response, + CreateApplePaySession400Response, GetPaymentMethods200Response, GetPaymentMethods200ResponseAvailablePaymentMethod, + ListCheckouts200Response, + ProcessCheckout400Response, ProcessCheckoutCheckoutSuccessResponse, ProcessCheckoutCheckoutSuccessResponsePaymentInstrument, ProcessCheckoutCheckoutSuccessResponseStatus, @@ -48,6 +52,8 @@ "CheckoutSuccess", "CheckoutUpdateRequest", "CheckoutsResource", + "CreateApplePaySession200Response", + "CreateApplePaySession400Response", "Currency", "DetailsError", "EntryMode", @@ -57,12 +63,14 @@ "GetPaymentMethods200Response", "GetPaymentMethods200ResponseAvailablePaymentMethod", "HostedCheckout", + "ListCheckouts200Response", "MandatePayload", "MandateResponse", "PaymentType", "PersonalDetails", "Problem", "ProcessCheckout", + "ProcessCheckout400Response", "ProcessCheckoutCheckoutSuccessResponse", "ProcessCheckoutCheckoutSuccessResponsePaymentInstrument", "ProcessCheckoutCheckoutSuccessResponseStatus", diff --git a/sumup/checkouts/resource.py b/sumup/checkouts/resource.py index c1614ffe..2d8c19b4 100644 --- a/sumup/checkouts/resource.py +++ b/sumup/checkouts/resource.py @@ -26,7 +26,7 @@ import pydantic import typing_extensions -from .._exceptions import APIError +from .._exceptions import APIError, _wrap_request_errors from .._service import ( NOT_GIVEN, AsyncResource, @@ -50,6 +50,7 @@ CheckoutSuccess, CheckoutUpdateRequest, CheckoutUpdateRequestInput, + CreateApplePaySession400Response, Currency, CurrencyInput, DetailsError, @@ -67,6 +68,7 @@ PersonalDetailsInput, Problem, ProcessCheckout, + ProcessCheckout400Response, ProcessCheckoutInput, TransactionBase, TransactionCheckoutInfo, @@ -599,8 +601,10 @@ def list_available_payment_methods( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: The request is invalid for the submitted query parameters. + 400: The request is invalid for the submitted query parameters. (raises BadRequestError) Unexpected response statuses also raise this exception. """ query_data: dict[str, typing.Any] = {} @@ -609,21 +613,22 @@ def list_available_payment_methods( if not isinstance(currency, NotGivenType) and currency is not None: query_data["currency"] = currency - resp = self._client.get( - f"/v0.1/merchants/{merchant_code}/payment-methods", - params=serialize_query_params(query_data) if query_data else None, - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.get( + f"/v0.1/merchants/{merchant_code}/payment-methods", + params=serialize_query_params(query_data) if query_data else None, + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(GetPaymentMethods200Response).validate_python(resp.json()) elif resp.status_code == 400: - raise APIError( + raise APIError.from_response( "The request is invalid for the submitted query parameters.", - status=resp.status_code, - body=resp.text, + resp, + body_type=DetailsError, ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) def create( self, @@ -653,11 +658,13 @@ def create( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: The request body is invalid. - 401: The request is not authorized. - 403: The request isn't sufficiently authorized to create a checkout. - 409: A checkout already exists for the provided unique parameters. + 400: The request body is invalid. (raises BadRequestError) + 401: The request is not authorized. (raises AuthenticationError) + 403: The request isn't sufficiently authorized to create a checkout. (raises PermissionDeniedError) + 409: A checkout already exists for the provided unique parameters. (raises ConflictError) Unexpected response statuses also raise this exception. """ body_data: dict[str, typing.Any] = {} @@ -680,33 +687,34 @@ def create( if not isinstance(hosted_checkout, NotGivenType): body_data["hosted_checkout"] = hosted_checkout - resp = self._client.post( - f"/v0.1/checkouts", - json=serialize_request_data(body_data), - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.post( + f"/v0.1/checkouts", + json=serialize_request_data(body_data), + headers=headers, + ) if resp.status_code == 201: return pydantic.TypeAdapter(Checkout).validate_python(resp.json()) elif resp.status_code == 400: - raise APIError("The request body is invalid.", status=resp.status_code, body=resp.text) - elif resp.status_code == 401: - raise APIError( - "The request is not authorized.", status=resp.status_code, body=resp.text + raise APIError.from_response( + "The request body is invalid.", resp, body_type=ErrorExtended ) + elif resp.status_code == 401: + raise APIError.from_response("The request is not authorized.", resp, body_type=Problem) elif resp.status_code == 403: - raise APIError( + raise APIError.from_response( "The request isn't sufficiently authorized to create a checkout.", - status=resp.status_code, - body=resp.text, + resp, + body_type=ErrorForbidden, ) elif resp.status_code == 409: - raise APIError( + raise APIError.from_response( "A checkout already exists for the provided unique parameters.", - status=resp.status_code, - body=resp.text, + resp, + body_type=Error, ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) def list( self, @@ -721,27 +729,28 @@ def list( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 401: The request is not authorized. + 401: The request is not authorized. (raises AuthenticationError) Unexpected response statuses also raise this exception. """ query_data: dict[str, typing.Any] = {} if not isinstance(checkout_reference, NotGivenType) and checkout_reference is not None: query_data["checkout_reference"] = checkout_reference - resp = self._client.get( - f"/v0.1/checkouts", - params=serialize_query_params(query_data) if query_data else None, - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.get( + f"/v0.1/checkouts", + params=serialize_query_params(query_data) if query_data else None, + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(ListCheckouts200Response).validate_python(resp.json()) elif resp.status_code == 401: - raise APIError( - "The request is not authorized.", status=resp.status_code, body=resp.text - ) + raise APIError.from_response("The request is not authorized.", resp, body_type=Problem) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) def get(self, checkout_id: str, headers: HeaderTypes | None = None) -> CheckoutSuccess: """ @@ -751,27 +760,28 @@ def get(self, checkout_id: str, headers: HeaderTypes | None = None) -> CheckoutS Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 401: The request is not authorized. - 404: The requested resource does not exist. + 401: The request is not authorized. (raises AuthenticationError) + 404: The requested resource does not exist. (raises NotFoundError) Unexpected response statuses also raise this exception. """ - resp = self._client.get( - f"/v0.1/checkouts/{checkout_id}", - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.get( + f"/v0.1/checkouts/{checkout_id}", + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(CheckoutSuccess).validate_python(resp.json()) elif resp.status_code == 401: - raise APIError( - "The request is not authorized.", status=resp.status_code, body=resp.text - ) + raise APIError.from_response("The request is not authorized.", resp, body_type=Problem) elif resp.status_code == 404: - raise APIError( - "The requested resource does not exist.", status=resp.status_code, body=resp.text + raise APIError.from_response( + "The requested resource does not exist.", resp, body_type=Error ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) def update( self, @@ -794,9 +804,11 @@ def update( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 401: The request is not authorized. - 404: The requested resource does not exist. + 401: The request is not authorized. (raises AuthenticationError) + 404: The requested resource does not exist. (raises NotFoundError) Unexpected response statuses also raise this exception. """ body_data: dict[str, typing.Any] = {} @@ -813,23 +825,22 @@ def update( if not isinstance(customer_id, NotGivenType): body_data["customer_id"] = customer_id - resp = self._client.patch( - f"/v0.1/checkouts/{checkout_id}", - json=serialize_request_data(body_data), - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.patch( + f"/v0.1/checkouts/{checkout_id}", + json=serialize_request_data(body_data), + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(Checkout).validate_python(resp.json()) elif resp.status_code == 401: - raise APIError( - "The request is not authorized.", status=resp.status_code, body=resp.text - ) + raise APIError.from_response("The request is not authorized.", resp, body_type=Problem) elif resp.status_code == 404: - raise APIError( - "The requested resource does not exist.", status=resp.status_code, body=resp.text + raise APIError.from_response( + "The requested resource does not exist.", resp, body_type=Error ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) def process( self, @@ -861,11 +872,13 @@ def process( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: The request body is invalid for processing the checkout. - 401: The request is not authorized. - 404: The requested resource does not exist. - 409: The request conflicts with the current state of the resource. + 400: The request body is invalid for processing the checkout. (raises BadRequestError) + 401: The request is not authorized. (raises AuthenticationError) + 404: The requested resource does not exist. (raises NotFoundError) + 409: The request conflicts with the current state of the resource. (raises ConflictError) Unexpected response statuses also raise this exception. """ body_data: dict[str, typing.Any] = {} @@ -887,11 +900,12 @@ def process( if not isinstance(personal_details, NotGivenType): body_data["personal_details"] = personal_details - resp = self._client.put( - f"/v0.1/checkouts/{checkout_id}", - json=serialize_request_data(body_data), - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.put( + f"/v0.1/checkouts/{checkout_id}", + json=serialize_request_data(body_data), + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(ProcessCheckoutCheckoutSuccessResponse).validate_python( resp.json() @@ -899,27 +913,25 @@ def process( elif resp.status_code == 202: return pydantic.TypeAdapter(CheckoutAccepted).validate_python(resp.json()) elif resp.status_code == 400: - raise APIError( + raise APIError.from_response( "The request body is invalid for processing the checkout.", - status=resp.status_code, - body=resp.text, + resp, + body_type=ProcessCheckout400Response, ) elif resp.status_code == 401: - raise APIError( - "The request is not authorized.", status=resp.status_code, body=resp.text - ) + raise APIError.from_response("The request is not authorized.", resp, body_type=Problem) elif resp.status_code == 404: - raise APIError( - "The requested resource does not exist.", status=resp.status_code, body=resp.text + raise APIError.from_response( + "The requested resource does not exist.", resp, body_type=Error ) elif resp.status_code == 409: - raise APIError( + raise APIError.from_response( "The request conflicts with the current state of the resource.", - status=resp.status_code, - body=resp.text, + resp, + body_type=Error, ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) def deactivate(self, checkout_id: str, headers: HeaderTypes | None = None) -> Checkout: """ @@ -929,34 +941,35 @@ def deactivate(self, checkout_id: str, headers: HeaderTypes | None = None) -> Ch Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 401: The request is not authorized. - 404: The requested resource does not exist. - 409: The request conflicts with the current state of the resource. + 401: The request is not authorized. (raises AuthenticationError) + 404: The requested resource does not exist. (raises NotFoundError) + 409: The request conflicts with the current state of the resource. (raises ConflictError) Unexpected response statuses also raise this exception. """ - resp = self._client.delete( - f"/v0.1/checkouts/{checkout_id}", - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.delete( + f"/v0.1/checkouts/{checkout_id}", + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(Checkout).validate_python(resp.json()) elif resp.status_code == 401: - raise APIError( - "The request is not authorized.", status=resp.status_code, body=resp.text - ) + raise APIError.from_response("The request is not authorized.", resp, body_type=Problem) elif resp.status_code == 404: - raise APIError( - "The requested resource does not exist.", status=resp.status_code, body=resp.text + raise APIError.from_response( + "The requested resource does not exist.", resp, body_type=Error ) elif resp.status_code == 409: - raise APIError( + raise APIError.from_response( "The request conflicts with the current state of the resource.", - status=resp.status_code, - body=resp.text, + resp, + body_type=Error, ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) def create_apple_pay_session( self, checkout_id: str, *, context: str, target: str, headers: HeaderTypes | None = None @@ -974,32 +987,37 @@ def create_apple_pay_session( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: Bad Request - 404: The requested resource does not exist. + 400: Bad Request (raises BadRequestError) + 404: The requested resource does not exist. (raises NotFoundError) Unexpected response statuses also raise this exception. """ body_data: dict[str, typing.Any] = {} body_data["context"] = context body_data["target"] = target - resp = self._client.put( - f"/v0.2/checkouts/{checkout_id}/apple-pay-session", - json=serialize_request_data(body_data), - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.put( + f"/v0.2/checkouts/{checkout_id}/apple-pay-session", + json=serialize_request_data(body_data), + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(CreateApplePaySession200Response).validate_python( resp.json() ) elif resp.status_code == 400: - raise APIError("Bad Request", status=resp.status_code, body=resp.text) + raise APIError.from_response( + "Bad Request", resp, body_type=CreateApplePaySession400Response + ) elif resp.status_code == 404: - raise APIError( - "The requested resource does not exist.", status=resp.status_code, body=resp.text + raise APIError.from_response( + "The requested resource does not exist.", resp, body_type=Error ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) class AsyncCheckoutsResource(AsyncResource): @@ -1023,8 +1041,10 @@ async def list_available_payment_methods( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: The request is invalid for the submitted query parameters. + 400: The request is invalid for the submitted query parameters. (raises BadRequestError) Unexpected response statuses also raise this exception. """ query_data: dict[str, typing.Any] = {} @@ -1033,21 +1053,22 @@ async def list_available_payment_methods( if not isinstance(currency, NotGivenType) and currency is not None: query_data["currency"] = currency - resp = await self._client.get( - f"/v0.1/merchants/{merchant_code}/payment-methods", - params=serialize_query_params(query_data) if query_data else None, - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.get( + f"/v0.1/merchants/{merchant_code}/payment-methods", + params=serialize_query_params(query_data) if query_data else None, + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(GetPaymentMethods200Response).validate_python(resp.json()) elif resp.status_code == 400: - raise APIError( + raise APIError.from_response( "The request is invalid for the submitted query parameters.", - status=resp.status_code, - body=resp.text, + resp, + body_type=DetailsError, ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) async def create( self, @@ -1077,11 +1098,13 @@ async def create( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: The request body is invalid. - 401: The request is not authorized. - 403: The request isn't sufficiently authorized to create a checkout. - 409: A checkout already exists for the provided unique parameters. + 400: The request body is invalid. (raises BadRequestError) + 401: The request is not authorized. (raises AuthenticationError) + 403: The request isn't sufficiently authorized to create a checkout. (raises PermissionDeniedError) + 409: A checkout already exists for the provided unique parameters. (raises ConflictError) Unexpected response statuses also raise this exception. """ body_data: dict[str, typing.Any] = {} @@ -1104,33 +1127,34 @@ async def create( if not isinstance(hosted_checkout, NotGivenType): body_data["hosted_checkout"] = hosted_checkout - resp = await self._client.post( - f"/v0.1/checkouts", - json=serialize_request_data(body_data), - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.post( + f"/v0.1/checkouts", + json=serialize_request_data(body_data), + headers=headers, + ) if resp.status_code == 201: return pydantic.TypeAdapter(Checkout).validate_python(resp.json()) elif resp.status_code == 400: - raise APIError("The request body is invalid.", status=resp.status_code, body=resp.text) - elif resp.status_code == 401: - raise APIError( - "The request is not authorized.", status=resp.status_code, body=resp.text + raise APIError.from_response( + "The request body is invalid.", resp, body_type=ErrorExtended ) + elif resp.status_code == 401: + raise APIError.from_response("The request is not authorized.", resp, body_type=Problem) elif resp.status_code == 403: - raise APIError( + raise APIError.from_response( "The request isn't sufficiently authorized to create a checkout.", - status=resp.status_code, - body=resp.text, + resp, + body_type=ErrorForbidden, ) elif resp.status_code == 409: - raise APIError( + raise APIError.from_response( "A checkout already exists for the provided unique parameters.", - status=resp.status_code, - body=resp.text, + resp, + body_type=Error, ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) async def list( self, @@ -1145,27 +1169,28 @@ async def list( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 401: The request is not authorized. + 401: The request is not authorized. (raises AuthenticationError) Unexpected response statuses also raise this exception. """ query_data: dict[str, typing.Any] = {} if not isinstance(checkout_reference, NotGivenType) and checkout_reference is not None: query_data["checkout_reference"] = checkout_reference - resp = await self._client.get( - f"/v0.1/checkouts", - params=serialize_query_params(query_data) if query_data else None, - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.get( + f"/v0.1/checkouts", + params=serialize_query_params(query_data) if query_data else None, + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(ListCheckouts200Response).validate_python(resp.json()) elif resp.status_code == 401: - raise APIError( - "The request is not authorized.", status=resp.status_code, body=resp.text - ) + raise APIError.from_response("The request is not authorized.", resp, body_type=Problem) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) async def get(self, checkout_id: str, headers: HeaderTypes | None = None) -> CheckoutSuccess: """ @@ -1175,27 +1200,28 @@ async def get(self, checkout_id: str, headers: HeaderTypes | None = None) -> Che Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 401: The request is not authorized. - 404: The requested resource does not exist. + 401: The request is not authorized. (raises AuthenticationError) + 404: The requested resource does not exist. (raises NotFoundError) Unexpected response statuses also raise this exception. """ - resp = await self._client.get( - f"/v0.1/checkouts/{checkout_id}", - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.get( + f"/v0.1/checkouts/{checkout_id}", + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(CheckoutSuccess).validate_python(resp.json()) elif resp.status_code == 401: - raise APIError( - "The request is not authorized.", status=resp.status_code, body=resp.text - ) + raise APIError.from_response("The request is not authorized.", resp, body_type=Problem) elif resp.status_code == 404: - raise APIError( - "The requested resource does not exist.", status=resp.status_code, body=resp.text + raise APIError.from_response( + "The requested resource does not exist.", resp, body_type=Error ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) async def update( self, @@ -1218,9 +1244,11 @@ async def update( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 401: The request is not authorized. - 404: The requested resource does not exist. + 401: The request is not authorized. (raises AuthenticationError) + 404: The requested resource does not exist. (raises NotFoundError) Unexpected response statuses also raise this exception. """ body_data: dict[str, typing.Any] = {} @@ -1237,23 +1265,22 @@ async def update( if not isinstance(customer_id, NotGivenType): body_data["customer_id"] = customer_id - resp = await self._client.patch( - f"/v0.1/checkouts/{checkout_id}", - json=serialize_request_data(body_data), - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.patch( + f"/v0.1/checkouts/{checkout_id}", + json=serialize_request_data(body_data), + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(Checkout).validate_python(resp.json()) elif resp.status_code == 401: - raise APIError( - "The request is not authorized.", status=resp.status_code, body=resp.text - ) + raise APIError.from_response("The request is not authorized.", resp, body_type=Problem) elif resp.status_code == 404: - raise APIError( - "The requested resource does not exist.", status=resp.status_code, body=resp.text + raise APIError.from_response( + "The requested resource does not exist.", resp, body_type=Error ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) async def process( self, @@ -1285,11 +1312,13 @@ async def process( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: The request body is invalid for processing the checkout. - 401: The request is not authorized. - 404: The requested resource does not exist. - 409: The request conflicts with the current state of the resource. + 400: The request body is invalid for processing the checkout. (raises BadRequestError) + 401: The request is not authorized. (raises AuthenticationError) + 404: The requested resource does not exist. (raises NotFoundError) + 409: The request conflicts with the current state of the resource. (raises ConflictError) Unexpected response statuses also raise this exception. """ body_data: dict[str, typing.Any] = {} @@ -1311,11 +1340,12 @@ async def process( if not isinstance(personal_details, NotGivenType): body_data["personal_details"] = personal_details - resp = await self._client.put( - f"/v0.1/checkouts/{checkout_id}", - json=serialize_request_data(body_data), - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.put( + f"/v0.1/checkouts/{checkout_id}", + json=serialize_request_data(body_data), + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(ProcessCheckoutCheckoutSuccessResponse).validate_python( resp.json() @@ -1323,27 +1353,25 @@ async def process( elif resp.status_code == 202: return pydantic.TypeAdapter(CheckoutAccepted).validate_python(resp.json()) elif resp.status_code == 400: - raise APIError( + raise APIError.from_response( "The request body is invalid for processing the checkout.", - status=resp.status_code, - body=resp.text, + resp, + body_type=ProcessCheckout400Response, ) elif resp.status_code == 401: - raise APIError( - "The request is not authorized.", status=resp.status_code, body=resp.text - ) + raise APIError.from_response("The request is not authorized.", resp, body_type=Problem) elif resp.status_code == 404: - raise APIError( - "The requested resource does not exist.", status=resp.status_code, body=resp.text + raise APIError.from_response( + "The requested resource does not exist.", resp, body_type=Error ) elif resp.status_code == 409: - raise APIError( + raise APIError.from_response( "The request conflicts with the current state of the resource.", - status=resp.status_code, - body=resp.text, + resp, + body_type=Error, ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) async def deactivate(self, checkout_id: str, headers: HeaderTypes | None = None) -> Checkout: """ @@ -1353,34 +1381,35 @@ async def deactivate(self, checkout_id: str, headers: HeaderTypes | None = None) Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 401: The request is not authorized. - 404: The requested resource does not exist. - 409: The request conflicts with the current state of the resource. + 401: The request is not authorized. (raises AuthenticationError) + 404: The requested resource does not exist. (raises NotFoundError) + 409: The request conflicts with the current state of the resource. (raises ConflictError) Unexpected response statuses also raise this exception. """ - resp = await self._client.delete( - f"/v0.1/checkouts/{checkout_id}", - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.delete( + f"/v0.1/checkouts/{checkout_id}", + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(Checkout).validate_python(resp.json()) elif resp.status_code == 401: - raise APIError( - "The request is not authorized.", status=resp.status_code, body=resp.text - ) + raise APIError.from_response("The request is not authorized.", resp, body_type=Problem) elif resp.status_code == 404: - raise APIError( - "The requested resource does not exist.", status=resp.status_code, body=resp.text + raise APIError.from_response( + "The requested resource does not exist.", resp, body_type=Error ) elif resp.status_code == 409: - raise APIError( + raise APIError.from_response( "The request conflicts with the current state of the resource.", - status=resp.status_code, - body=resp.text, + resp, + body_type=Error, ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) async def create_apple_pay_session( self, checkout_id: str, *, context: str, target: str, headers: HeaderTypes | None = None @@ -1398,29 +1427,34 @@ async def create_apple_pay_session( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: Bad Request - 404: The requested resource does not exist. + 400: Bad Request (raises BadRequestError) + 404: The requested resource does not exist. (raises NotFoundError) Unexpected response statuses also raise this exception. """ body_data: dict[str, typing.Any] = {} body_data["context"] = context body_data["target"] = target - resp = await self._client.put( - f"/v0.2/checkouts/{checkout_id}/apple-pay-session", - json=serialize_request_data(body_data), - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.put( + f"/v0.2/checkouts/{checkout_id}/apple-pay-session", + json=serialize_request_data(body_data), + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(CreateApplePaySession200Response).validate_python( resp.json() ) elif resp.status_code == 400: - raise APIError("Bad Request", status=resp.status_code, body=resp.text) + raise APIError.from_response( + "Bad Request", resp, body_type=CreateApplePaySession400Response + ) elif resp.status_code == 404: - raise APIError( - "The requested resource does not exist.", status=resp.status_code, body=resp.text + raise APIError.from_response( + "The requested resource does not exist.", resp, body_type=Error ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) diff --git a/sumup/customers/__init__.py b/sumup/customers/__init__.py index 861a9fe6..8ab51b4c 100644 --- a/sumup/customers/__init__.py +++ b/sumup/customers/__init__.py @@ -14,19 +14,23 @@ ) from .resource import ( AsyncCustomersResource, + CreateCustomer400Response, CustomersResource, + ListPaymentInstruments200Response, ) __all__ = [ "AddressLegacy", "AsyncCustomersResource", "CardType", + "CreateCustomer400Response", "Customer", "CustomerValidationError", "CustomersResource", "Error", "ErrorExtended", "ErrorForbidden", + "ListPaymentInstruments200Response", "MandateResponse", "PaymentInstrumentResponse", "PersonalDetails", diff --git a/sumup/customers/resource.py b/sumup/customers/resource.py index 054e9b40..d94c9bf9 100644 --- a/sumup/customers/resource.py +++ b/sumup/customers/resource.py @@ -17,7 +17,7 @@ import pydantic import typing_extensions -from .._exceptions import APIError +from .._exceptions import APIError, _wrap_request_errors from .._service import ( NOT_GIVEN, AsyncResource, @@ -31,6 +31,7 @@ AddressLegacy, AddressLegacyInput, CardType, + CreateCustomer400Response, Customer, CustomerInput, CustomerValidationError, @@ -103,11 +104,13 @@ def create( Raises: - APIError: Raised when the API returns one of the documented error responses: - 400: The request body is invalid. - 401: The request is not authorized. - 403: The request is authenticated but not permitted for this operation. - 409: A customer with the provided identifier already exists. + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. + APIError: Raised when the API returns one of the documented error responses: + 400: The request body is invalid. (raises BadRequestError) + 401: The request is not authorized. (raises AuthenticationError) + 403: The request is authenticated but not permitted for this operation. (raises PermissionDeniedError) + 409: A customer with the provided identifier already exists. (raises ConflictError) Unexpected response statuses also raise this exception. """ body_data: dict[str, typing.Any] = {} @@ -115,33 +118,32 @@ def create( if not isinstance(personal_details, NotGivenType): body_data["personal_details"] = personal_details - resp = self._client.post( - f"/v0.1/customers", - json=serialize_request_data(body_data), - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.post( + f"/v0.1/customers", + json=serialize_request_data(body_data), + headers=headers, + ) if resp.status_code == 201: return pydantic.TypeAdapter(Customer).validate_python(resp.json()) elif resp.status_code == 400: - raise APIError("The request body is invalid.", status=resp.status_code, body=resp.text) - elif resp.status_code == 401: - raise APIError( - "The request is not authorized.", status=resp.status_code, body=resp.text + raise APIError.from_response( + "The request body is invalid.", resp, body_type=CreateCustomer400Response ) + elif resp.status_code == 401: + raise APIError.from_response("The request is not authorized.", resp, body_type=Problem) elif resp.status_code == 403: - raise APIError( + raise APIError.from_response( "The request is authenticated but not permitted for this operation.", - status=resp.status_code, - body=resp.text, + resp, + body_type=ErrorForbidden, ) elif resp.status_code == 409: - raise APIError( - "A customer with the provided identifier already exists.", - status=resp.status_code, - body=resp.text, + raise APIError.from_response( + "A customer with the provided identifier already exists.", resp, body_type=Error ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) def get(self, customer_id: str, headers: HeaderTypes | None = None) -> Customer: """ @@ -151,34 +153,35 @@ def get(self, customer_id: str, headers: HeaderTypes | None = None) -> Customer: Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 401: The request is not authorized. - 403: The request is authenticated but not permitted for this operation. - 404: The requested resource does not exist. + 401: The request is not authorized. (raises AuthenticationError) + 403: The request is authenticated but not permitted for this operation. (raises PermissionDeniedError) + 404: The requested resource does not exist. (raises NotFoundError) Unexpected response statuses also raise this exception. """ - resp = self._client.get( - f"/v0.1/customers/{customer_id}", - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.get( + f"/v0.1/customers/{customer_id}", + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(Customer).validate_python(resp.json()) elif resp.status_code == 401: - raise APIError( - "The request is not authorized.", status=resp.status_code, body=resp.text - ) + raise APIError.from_response("The request is not authorized.", resp, body_type=Problem) elif resp.status_code == 403: - raise APIError( + raise APIError.from_response( "The request is authenticated but not permitted for this operation.", - status=resp.status_code, - body=resp.text, + resp, + body_type=ErrorForbidden, ) elif resp.status_code == 404: - raise APIError( - "The requested resource does not exist.", status=resp.status_code, body=resp.text + raise APIError.from_response( + "The requested resource does not exist.", resp, body_type=Error ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) def update( self, @@ -196,39 +199,40 @@ def update( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 401: The request is not authorized. - 403: The request is authenticated but not permitted for this operation. - 404: The requested resource does not exist. + 401: The request is not authorized. (raises AuthenticationError) + 403: The request is authenticated but not permitted for this operation. (raises PermissionDeniedError) + 404: The requested resource does not exist. (raises NotFoundError) Unexpected response statuses also raise this exception. """ body_data: dict[str, typing.Any] = {} if not isinstance(personal_details, NotGivenType): body_data["personal_details"] = personal_details - resp = self._client.put( - f"/v0.1/customers/{customer_id}", - json=serialize_request_data(body_data), - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.put( + f"/v0.1/customers/{customer_id}", + json=serialize_request_data(body_data), + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(Customer).validate_python(resp.json()) elif resp.status_code == 401: - raise APIError( - "The request is not authorized.", status=resp.status_code, body=resp.text - ) + raise APIError.from_response("The request is not authorized.", resp, body_type=Problem) elif resp.status_code == 403: - raise APIError( + raise APIError.from_response( "The request is authenticated but not permitted for this operation.", - status=resp.status_code, - body=resp.text, + resp, + body_type=ErrorForbidden, ) elif resp.status_code == 404: - raise APIError( - "The requested resource does not exist.", status=resp.status_code, body=resp.text + raise APIError.from_response( + "The requested resource does not exist.", resp, body_type=Error ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) def list_payment_instruments( self, customer_id: str, headers: HeaderTypes | None = None @@ -240,36 +244,37 @@ def list_payment_instruments( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 401: The request is not authorized. - 403: The request is authenticated but not permitted for this operation. - 404: The requested resource does not exist. + 401: The request is not authorized. (raises AuthenticationError) + 403: The request is authenticated but not permitted for this operation. (raises PermissionDeniedError) + 404: The requested resource does not exist. (raises NotFoundError) Unexpected response statuses also raise this exception. """ - resp = self._client.get( - f"/v0.1/customers/{customer_id}/payment-instruments", - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.get( + f"/v0.1/customers/{customer_id}/payment-instruments", + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(ListPaymentInstruments200Response).validate_python( resp.json() ) elif resp.status_code == 401: - raise APIError( - "The request is not authorized.", status=resp.status_code, body=resp.text - ) + raise APIError.from_response("The request is not authorized.", resp, body_type=Problem) elif resp.status_code == 403: - raise APIError( + raise APIError.from_response( "The request is authenticated but not permitted for this operation.", - status=resp.status_code, - body=resp.text, + resp, + body_type=ErrorForbidden, ) elif resp.status_code == 404: - raise APIError( - "The requested resource does not exist.", status=resp.status_code, body=resp.text + raise APIError.from_response( + "The requested resource does not exist.", resp, body_type=Error ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) def deactivate_payment_instrument( self, customer_id: str, token: str, headers: HeaderTypes | None = None @@ -281,37 +286,38 @@ def deactivate_payment_instrument( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: The request is invalid. - 401: The request is not authorized. - 403: The request is authenticated but not permitted for this operation. - 404: The requested resource does not exist. + 400: The request is invalid. (raises BadRequestError) + 401: The request is not authorized. (raises AuthenticationError) + 403: The request is authenticated but not permitted for this operation. (raises PermissionDeniedError) + 404: The requested resource does not exist. (raises NotFoundError) Unexpected response statuses also raise this exception. """ - resp = self._client.delete( - f"/v0.1/customers/{customer_id}/payment-instruments/{token}", - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.delete( + f"/v0.1/customers/{customer_id}/payment-instruments/{token}", + headers=headers, + ) if resp.status_code == 204: return elif resp.status_code == 400: - raise APIError("The request is invalid.", status=resp.status_code, body=resp.text) + raise APIError.from_response("The request is invalid.", resp, body_type=Error) elif resp.status_code == 401: - raise APIError( - "The request is not authorized.", status=resp.status_code, body=resp.text - ) + raise APIError.from_response("The request is not authorized.", resp, body_type=Problem) elif resp.status_code == 403: - raise APIError( + raise APIError.from_response( "The request is authenticated but not permitted for this operation.", - status=resp.status_code, - body=resp.text, + resp, + body_type=ErrorForbidden, ) elif resp.status_code == 404: - raise APIError( - "The requested resource does not exist.", status=resp.status_code, body=resp.text + raise APIError.from_response( + "The requested resource does not exist.", resp, body_type=Error ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) class AsyncCustomersResource(AsyncResource): @@ -334,11 +340,13 @@ async def create( Raises: - APIError: Raised when the API returns one of the documented error responses: - 400: The request body is invalid. - 401: The request is not authorized. - 403: The request is authenticated but not permitted for this operation. - 409: A customer with the provided identifier already exists. + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. + APIError: Raised when the API returns one of the documented error responses: + 400: The request body is invalid. (raises BadRequestError) + 401: The request is not authorized. (raises AuthenticationError) + 403: The request is authenticated but not permitted for this operation. (raises PermissionDeniedError) + 409: A customer with the provided identifier already exists. (raises ConflictError) Unexpected response statuses also raise this exception. """ body_data: dict[str, typing.Any] = {} @@ -346,33 +354,32 @@ async def create( if not isinstance(personal_details, NotGivenType): body_data["personal_details"] = personal_details - resp = await self._client.post( - f"/v0.1/customers", - json=serialize_request_data(body_data), - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.post( + f"/v0.1/customers", + json=serialize_request_data(body_data), + headers=headers, + ) if resp.status_code == 201: return pydantic.TypeAdapter(Customer).validate_python(resp.json()) elif resp.status_code == 400: - raise APIError("The request body is invalid.", status=resp.status_code, body=resp.text) - elif resp.status_code == 401: - raise APIError( - "The request is not authorized.", status=resp.status_code, body=resp.text + raise APIError.from_response( + "The request body is invalid.", resp, body_type=CreateCustomer400Response ) + elif resp.status_code == 401: + raise APIError.from_response("The request is not authorized.", resp, body_type=Problem) elif resp.status_code == 403: - raise APIError( + raise APIError.from_response( "The request is authenticated but not permitted for this operation.", - status=resp.status_code, - body=resp.text, + resp, + body_type=ErrorForbidden, ) elif resp.status_code == 409: - raise APIError( - "A customer with the provided identifier already exists.", - status=resp.status_code, - body=resp.text, + raise APIError.from_response( + "A customer with the provided identifier already exists.", resp, body_type=Error ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) async def get(self, customer_id: str, headers: HeaderTypes | None = None) -> Customer: """ @@ -382,34 +389,35 @@ async def get(self, customer_id: str, headers: HeaderTypes | None = None) -> Cus Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 401: The request is not authorized. - 403: The request is authenticated but not permitted for this operation. - 404: The requested resource does not exist. + 401: The request is not authorized. (raises AuthenticationError) + 403: The request is authenticated but not permitted for this operation. (raises PermissionDeniedError) + 404: The requested resource does not exist. (raises NotFoundError) Unexpected response statuses also raise this exception. """ - resp = await self._client.get( - f"/v0.1/customers/{customer_id}", - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.get( + f"/v0.1/customers/{customer_id}", + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(Customer).validate_python(resp.json()) elif resp.status_code == 401: - raise APIError( - "The request is not authorized.", status=resp.status_code, body=resp.text - ) + raise APIError.from_response("The request is not authorized.", resp, body_type=Problem) elif resp.status_code == 403: - raise APIError( + raise APIError.from_response( "The request is authenticated but not permitted for this operation.", - status=resp.status_code, - body=resp.text, + resp, + body_type=ErrorForbidden, ) elif resp.status_code == 404: - raise APIError( - "The requested resource does not exist.", status=resp.status_code, body=resp.text + raise APIError.from_response( + "The requested resource does not exist.", resp, body_type=Error ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) async def update( self, @@ -427,39 +435,40 @@ async def update( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 401: The request is not authorized. - 403: The request is authenticated but not permitted for this operation. - 404: The requested resource does not exist. + 401: The request is not authorized. (raises AuthenticationError) + 403: The request is authenticated but not permitted for this operation. (raises PermissionDeniedError) + 404: The requested resource does not exist. (raises NotFoundError) Unexpected response statuses also raise this exception. """ body_data: dict[str, typing.Any] = {} if not isinstance(personal_details, NotGivenType): body_data["personal_details"] = personal_details - resp = await self._client.put( - f"/v0.1/customers/{customer_id}", - json=serialize_request_data(body_data), - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.put( + f"/v0.1/customers/{customer_id}", + json=serialize_request_data(body_data), + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(Customer).validate_python(resp.json()) elif resp.status_code == 401: - raise APIError( - "The request is not authorized.", status=resp.status_code, body=resp.text - ) + raise APIError.from_response("The request is not authorized.", resp, body_type=Problem) elif resp.status_code == 403: - raise APIError( + raise APIError.from_response( "The request is authenticated but not permitted for this operation.", - status=resp.status_code, - body=resp.text, + resp, + body_type=ErrorForbidden, ) elif resp.status_code == 404: - raise APIError( - "The requested resource does not exist.", status=resp.status_code, body=resp.text + raise APIError.from_response( + "The requested resource does not exist.", resp, body_type=Error ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) async def list_payment_instruments( self, customer_id: str, headers: HeaderTypes | None = None @@ -471,36 +480,37 @@ async def list_payment_instruments( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 401: The request is not authorized. - 403: The request is authenticated but not permitted for this operation. - 404: The requested resource does not exist. + 401: The request is not authorized. (raises AuthenticationError) + 403: The request is authenticated but not permitted for this operation. (raises PermissionDeniedError) + 404: The requested resource does not exist. (raises NotFoundError) Unexpected response statuses also raise this exception. """ - resp = await self._client.get( - f"/v0.1/customers/{customer_id}/payment-instruments", - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.get( + f"/v0.1/customers/{customer_id}/payment-instruments", + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(ListPaymentInstruments200Response).validate_python( resp.json() ) elif resp.status_code == 401: - raise APIError( - "The request is not authorized.", status=resp.status_code, body=resp.text - ) + raise APIError.from_response("The request is not authorized.", resp, body_type=Problem) elif resp.status_code == 403: - raise APIError( + raise APIError.from_response( "The request is authenticated but not permitted for this operation.", - status=resp.status_code, - body=resp.text, + resp, + body_type=ErrorForbidden, ) elif resp.status_code == 404: - raise APIError( - "The requested resource does not exist.", status=resp.status_code, body=resp.text + raise APIError.from_response( + "The requested resource does not exist.", resp, body_type=Error ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) async def deactivate_payment_instrument( self, customer_id: str, token: str, headers: HeaderTypes | None = None @@ -512,34 +522,35 @@ async def deactivate_payment_instrument( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: The request is invalid. - 401: The request is not authorized. - 403: The request is authenticated but not permitted for this operation. - 404: The requested resource does not exist. + 400: The request is invalid. (raises BadRequestError) + 401: The request is not authorized. (raises AuthenticationError) + 403: The request is authenticated but not permitted for this operation. (raises PermissionDeniedError) + 404: The requested resource does not exist. (raises NotFoundError) Unexpected response statuses also raise this exception. """ - resp = await self._client.delete( - f"/v0.1/customers/{customer_id}/payment-instruments/{token}", - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.delete( + f"/v0.1/customers/{customer_id}/payment-instruments/{token}", + headers=headers, + ) if resp.status_code == 204: return elif resp.status_code == 400: - raise APIError("The request is invalid.", status=resp.status_code, body=resp.text) + raise APIError.from_response("The request is invalid.", resp, body_type=Error) elif resp.status_code == 401: - raise APIError( - "The request is not authorized.", status=resp.status_code, body=resp.text - ) + raise APIError.from_response("The request is not authorized.", resp, body_type=Problem) elif resp.status_code == 403: - raise APIError( + raise APIError.from_response( "The request is authenticated but not permitted for this operation.", - status=resp.status_code, - body=resp.text, + resp, + body_type=ErrorForbidden, ) elif resp.status_code == 404: - raise APIError( - "The requested resource does not exist.", status=resp.status_code, body=resp.text + raise APIError.from_response( + "The requested resource does not exist.", resp, body_type=Error ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) diff --git a/sumup/errors.py b/sumup/errors.py new file mode 100644 index 00000000..6667b961 --- /dev/null +++ b/sumup/errors.py @@ -0,0 +1,33 @@ +"""Exceptions raised by the SumUp SDK.""" + +from ._exceptions import ( + APIConnectionError, + APIError, + APIStatusError, + APITimeoutError, + AuthenticationError, + BadRequestError, + ConflictError, + InternalServerError, + NotFoundError, + PermissionDeniedError, + RateLimitError, + SumupError, + UnprocessableEntityError, +) + +__all__ = [ + "APIConnectionError", + "APIError", + "APIStatusError", + "APITimeoutError", + "AuthenticationError", + "BadRequestError", + "ConflictError", + "InternalServerError", + "NotFoundError", + "PermissionDeniedError", + "RateLimitError", + "SumupError", + "UnprocessableEntityError", +] diff --git a/sumup/members/resource.py b/sumup/members/resource.py index ee6a04d7..6bc82c5d 100644 --- a/sumup/members/resource.py +++ b/sumup/members/resource.py @@ -1,5 +1,5 @@ # Code generated by `py-sdk-gen`. DO NOT EDIT. -# ruff: noqa: F401, F541 +# ruff: noqa: F401 """ Endpoints to manage account members. Members are users that have membership within merchant accounts. """ @@ -13,7 +13,7 @@ import pydantic import typing_extensions -from .._exceptions import APIError +from .._exceptions import APIError, _wrap_request_errors from .._secret import Secret from .._service import ( NOT_GIVEN, @@ -196,8 +196,10 @@ def list( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 404: Merchant not found. + 404: Merchant not found. (raises NotFoundError) Unexpected response statuses also raise this exception. """ query_data: dict[str, typing.Any] = {} @@ -216,17 +218,18 @@ def list( if not isinstance(roles, NotGivenType) and roles is not None: query_data["roles"] = list(roles) - resp = self._client.get( - f"/v0.1/merchants/{merchant_code}/members", - params=serialize_query_params(query_data) if query_data else None, - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.get( + f"/v0.1/merchants/{merchant_code}/members", + params=serialize_query_params(query_data) if query_data else None, + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(ListMerchantMembers200Response).validate_python(resp.json()) elif resp.status_code == 404: - raise APIError("Merchant not found.", status=resp.status_code, body=resp.text) + raise APIError.from_response("Merchant not found.", resp, body_type=Problem) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) def create( self, @@ -251,10 +254,12 @@ def create( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: Invalid request. - 404: Merchant not found. - 429: Too many invitations were sent to that user and the rate limit was exceeded. The Retry-After headerindicates when the client can retry. + 400: Invalid request. (raises BadRequestError) + 404: Merchant not found. (raises NotFoundError) + 429: Too many invitations were sent to that user and the rate limit was exceeded. The Retry-After headerindicates when the client can retry. (raises RateLimitError) Unexpected response statuses also raise this exception. """ body_data: dict[str, typing.Any] = {} @@ -271,25 +276,26 @@ def create( if not isinstance(attributes, NotGivenType): body_data["attributes"] = attributes - resp = self._client.post( - f"/v0.1/merchants/{merchant_code}/members", - json=serialize_request_data(body_data), - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.post( + f"/v0.1/merchants/{merchant_code}/members", + json=serialize_request_data(body_data), + headers=headers, + ) if resp.status_code == 201: return pydantic.TypeAdapter(Member).validate_python(resp.json()) elif resp.status_code == 400: - raise APIError("Invalid request.", status=resp.status_code, body=resp.text) + raise APIError.from_response("Invalid request.", resp, body_type=Problem) elif resp.status_code == 404: - raise APIError("Merchant not found.", status=resp.status_code, body=resp.text) + raise APIError.from_response("Merchant not found.", resp, body_type=Problem) elif resp.status_code == 429: - raise APIError( + raise APIError.from_response( "Too many invitations were sent to that user and the rate limit was exceeded. The Retry-After header indicates when the client can retry.", - status=resp.status_code, - body=resp.text, + resp, + body_type=Problem, ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) def get(self, merchant_code: str, member_id: str, headers: HeaderTypes | None = None) -> Member: """ @@ -299,20 +305,23 @@ def get(self, merchant_code: str, member_id: str, headers: HeaderTypes | None = Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 404: Merchant or member not found. + 404: Merchant or member not found. (raises NotFoundError) Unexpected response statuses also raise this exception. """ - resp = self._client.get( - f"/v0.1/merchants/{merchant_code}/members/{member_id}", - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.get( + f"/v0.1/merchants/{merchant_code}/members/{member_id}", + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(Member).validate_python(resp.json()) elif resp.status_code == 404: - raise APIError("Merchant or member not found.", status=resp.status_code, body=resp.text) + raise APIError.from_response("Merchant or member not found.", resp, body_type=Problem) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) def update( self, @@ -335,11 +344,13 @@ def update( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: Cannot set password or nickname for an invited user. - 403: Cannot change password for managed user. Password was already used before. - 404: Merchant or member not found. - 409: Cannot update member as some data conflict with existing members. + 400: Cannot set password or nickname for an invited user. (raises BadRequestError) + 403: Cannot change password for managed user. Password was already used before. (raises PermissionDeniedError) + 404: Merchant or member not found. (raises NotFoundError) + 409: Cannot update member as some data conflict with existing members. (raises ConflictError) Unexpected response statuses also raise this exception. """ body_data: dict[str, typing.Any] = {} @@ -352,35 +363,34 @@ def update( if not isinstance(user, NotGivenType): body_data["user"] = user - resp = self._client.put( - f"/v0.1/merchants/{merchant_code}/members/{member_id}", - json=serialize_request_data(body_data), - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.put( + f"/v0.1/merchants/{merchant_code}/members/{member_id}", + json=serialize_request_data(body_data), + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(Member).validate_python(resp.json()) elif resp.status_code == 400: - raise APIError( - "Cannot set password or nickname for an invited user.", - status=resp.status_code, - body=resp.text, + raise APIError.from_response( + "Cannot set password or nickname for an invited user.", resp, body_type=Problem ) elif resp.status_code == 403: - raise APIError( + raise APIError.from_response( "Cannot change password for managed user. Password was already used before.", - status=resp.status_code, - body=resp.text, + resp, + body_type=Problem, ) elif resp.status_code == 404: - raise APIError("Merchant or member not found.", status=resp.status_code, body=resp.text) + raise APIError.from_response("Merchant or member not found.", resp, body_type=Problem) elif resp.status_code == 409: - raise APIError( + raise APIError.from_response( "Cannot update member as some data conflict with existing members.", - status=resp.status_code, - body=resp.text, + resp, + body_type=Problem, ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) def delete(self, merchant_code: str, member_id: str, headers: HeaderTypes | None = None): """ @@ -390,25 +400,26 @@ def delete(self, merchant_code: str, member_id: str, headers: HeaderTypes | None Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 403: Member deletion was forbidden. - 404: Merchant or member not found. + 403: Member deletion was forbidden. (raises PermissionDeniedError) + 404: Merchant or member not found. (raises NotFoundError) Unexpected response statuses also raise this exception. """ - resp = self._client.delete( - f"/v0.1/merchants/{merchant_code}/members/{member_id}", - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.delete( + f"/v0.1/merchants/{merchant_code}/members/{member_id}", + headers=headers, + ) if resp.status_code == 200: return elif resp.status_code == 403: - raise APIError( - "Member deletion was forbidden.", status=resp.status_code, body=resp.text - ) + raise APIError.from_response("Member deletion was forbidden.", resp, body_type=Problem) elif resp.status_code == 404: - raise APIError("Merchant or member not found.", status=resp.status_code, body=resp.text) + raise APIError.from_response("Merchant or member not found.", resp, body_type=Problem) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) class AsyncMembersResource(AsyncResource): @@ -437,8 +448,10 @@ async def list( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 404: Merchant not found. + 404: Merchant not found. (raises NotFoundError) Unexpected response statuses also raise this exception. """ query_data: dict[str, typing.Any] = {} @@ -457,17 +470,18 @@ async def list( if not isinstance(roles, NotGivenType) and roles is not None: query_data["roles"] = list(roles) - resp = await self._client.get( - f"/v0.1/merchants/{merchant_code}/members", - params=serialize_query_params(query_data) if query_data else None, - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.get( + f"/v0.1/merchants/{merchant_code}/members", + params=serialize_query_params(query_data) if query_data else None, + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(ListMerchantMembers200Response).validate_python(resp.json()) elif resp.status_code == 404: - raise APIError("Merchant not found.", status=resp.status_code, body=resp.text) + raise APIError.from_response("Merchant not found.", resp, body_type=Problem) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) async def create( self, @@ -492,10 +506,12 @@ async def create( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: Invalid request. - 404: Merchant not found. - 429: Too many invitations were sent to that user and the rate limit was exceeded. The Retry-After headerindicates when the client can retry. + 400: Invalid request. (raises BadRequestError) + 404: Merchant not found. (raises NotFoundError) + 429: Too many invitations were sent to that user and the rate limit was exceeded. The Retry-After headerindicates when the client can retry. (raises RateLimitError) Unexpected response statuses also raise this exception. """ body_data: dict[str, typing.Any] = {} @@ -512,25 +528,26 @@ async def create( if not isinstance(attributes, NotGivenType): body_data["attributes"] = attributes - resp = await self._client.post( - f"/v0.1/merchants/{merchant_code}/members", - json=serialize_request_data(body_data), - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.post( + f"/v0.1/merchants/{merchant_code}/members", + json=serialize_request_data(body_data), + headers=headers, + ) if resp.status_code == 201: return pydantic.TypeAdapter(Member).validate_python(resp.json()) elif resp.status_code == 400: - raise APIError("Invalid request.", status=resp.status_code, body=resp.text) + raise APIError.from_response("Invalid request.", resp, body_type=Problem) elif resp.status_code == 404: - raise APIError("Merchant not found.", status=resp.status_code, body=resp.text) + raise APIError.from_response("Merchant not found.", resp, body_type=Problem) elif resp.status_code == 429: - raise APIError( + raise APIError.from_response( "Too many invitations were sent to that user and the rate limit was exceeded. The Retry-After header indicates when the client can retry.", - status=resp.status_code, - body=resp.text, + resp, + body_type=Problem, ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) async def get( self, merchant_code: str, member_id: str, headers: HeaderTypes | None = None @@ -542,20 +559,23 @@ async def get( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 404: Merchant or member not found. + 404: Merchant or member not found. (raises NotFoundError) Unexpected response statuses also raise this exception. """ - resp = await self._client.get( - f"/v0.1/merchants/{merchant_code}/members/{member_id}", - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.get( + f"/v0.1/merchants/{merchant_code}/members/{member_id}", + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(Member).validate_python(resp.json()) elif resp.status_code == 404: - raise APIError("Merchant or member not found.", status=resp.status_code, body=resp.text) + raise APIError.from_response("Merchant or member not found.", resp, body_type=Problem) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) async def update( self, @@ -578,11 +598,13 @@ async def update( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: Cannot set password or nickname for an invited user. - 403: Cannot change password for managed user. Password was already used before. - 404: Merchant or member not found. - 409: Cannot update member as some data conflict with existing members. + 400: Cannot set password or nickname for an invited user. (raises BadRequestError) + 403: Cannot change password for managed user. Password was already used before. (raises PermissionDeniedError) + 404: Merchant or member not found. (raises NotFoundError) + 409: Cannot update member as some data conflict with existing members. (raises ConflictError) Unexpected response statuses also raise this exception. """ body_data: dict[str, typing.Any] = {} @@ -595,35 +617,34 @@ async def update( if not isinstance(user, NotGivenType): body_data["user"] = user - resp = await self._client.put( - f"/v0.1/merchants/{merchant_code}/members/{member_id}", - json=serialize_request_data(body_data), - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.put( + f"/v0.1/merchants/{merchant_code}/members/{member_id}", + json=serialize_request_data(body_data), + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(Member).validate_python(resp.json()) elif resp.status_code == 400: - raise APIError( - "Cannot set password or nickname for an invited user.", - status=resp.status_code, - body=resp.text, + raise APIError.from_response( + "Cannot set password or nickname for an invited user.", resp, body_type=Problem ) elif resp.status_code == 403: - raise APIError( + raise APIError.from_response( "Cannot change password for managed user. Password was already used before.", - status=resp.status_code, - body=resp.text, + resp, + body_type=Problem, ) elif resp.status_code == 404: - raise APIError("Merchant or member not found.", status=resp.status_code, body=resp.text) + raise APIError.from_response("Merchant or member not found.", resp, body_type=Problem) elif resp.status_code == 409: - raise APIError( + raise APIError.from_response( "Cannot update member as some data conflict with existing members.", - status=resp.status_code, - body=resp.text, + resp, + body_type=Problem, ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) async def delete(self, merchant_code: str, member_id: str, headers: HeaderTypes | None = None): """ @@ -633,22 +654,23 @@ async def delete(self, merchant_code: str, member_id: str, headers: HeaderTypes Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 403: Member deletion was forbidden. - 404: Merchant or member not found. + 403: Member deletion was forbidden. (raises PermissionDeniedError) + 404: Merchant or member not found. (raises NotFoundError) Unexpected response statuses also raise this exception. """ - resp = await self._client.delete( - f"/v0.1/merchants/{merchant_code}/members/{member_id}", - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.delete( + f"/v0.1/merchants/{merchant_code}/members/{member_id}", + headers=headers, + ) if resp.status_code == 200: return elif resp.status_code == 403: - raise APIError( - "Member deletion was forbidden.", status=resp.status_code, body=resp.text - ) + raise APIError.from_response("Member deletion was forbidden.", resp, body_type=Problem) elif resp.status_code == 404: - raise APIError("Merchant or member not found.", status=resp.status_code, body=resp.text) + raise APIError.from_response("Merchant or member not found.", resp, body_type=Problem) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) diff --git a/sumup/memberships/resource.py b/sumup/memberships/resource.py index 85e96aae..8929d6c8 100644 --- a/sumup/memberships/resource.py +++ b/sumup/memberships/resource.py @@ -13,7 +13,7 @@ import pydantic import typing_extensions -from .._exceptions import APIError +from .._exceptions import APIError, _wrap_request_errors from .._service import ( NOT_GIVEN, AsyncResource, @@ -76,9 +76,11 @@ def list( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: Invalid query parameter combination. - 401: Authentication failed or missing required scope. + 400: Invalid query parameter combination. (raises BadRequestError) + 401: Authentication failed or missing required scope. (raises AuthenticationError) Unexpected response statuses also raise this exception. """ query_data: dict[str, typing.Any] = {} @@ -108,25 +110,24 @@ def list( if not isinstance(roles, NotGivenType) and roles is not None: query_data["roles"] = list(roles) - resp = self._client.get( - f"/v0.1/memberships", - params=serialize_query_params(query_data) if query_data else None, - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.get( + f"/v0.1/memberships", + params=serialize_query_params(query_data) if query_data else None, + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(ListMemberships200Response).validate_python(resp.json()) elif resp.status_code == 400: - raise APIError( - "Invalid query parameter combination.", status=resp.status_code, body=resp.text + raise APIError.from_response( + "Invalid query parameter combination.", resp, body_type=Problem ) elif resp.status_code == 401: - raise APIError( - "Authentication failed or missing required scope.", - status=resp.status_code, - body=resp.text, + raise APIError.from_response( + "Authentication failed or missing required scope.", resp, body_type=Problem ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) class AsyncMembershipsResource(AsyncResource): @@ -158,9 +159,11 @@ async def list( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: Invalid query parameter combination. - 401: Authentication failed or missing required scope. + 400: Invalid query parameter combination. (raises BadRequestError) + 401: Authentication failed or missing required scope. (raises AuthenticationError) Unexpected response statuses also raise this exception. """ query_data: dict[str, typing.Any] = {} @@ -190,22 +193,21 @@ async def list( if not isinstance(roles, NotGivenType) and roles is not None: query_data["roles"] = list(roles) - resp = await self._client.get( - f"/v0.1/memberships", - params=serialize_query_params(query_data) if query_data else None, - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.get( + f"/v0.1/memberships", + params=serialize_query_params(query_data) if query_data else None, + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(ListMemberships200Response).validate_python(resp.json()) elif resp.status_code == 400: - raise APIError( - "Invalid query parameter combination.", status=resp.status_code, body=resp.text + raise APIError.from_response( + "Invalid query parameter combination.", resp, body_type=Problem ) elif resp.status_code == 401: - raise APIError( - "Authentication failed or missing required scope.", - status=resp.status_code, - body=resp.text, + raise APIError.from_response( + "Authentication failed or missing required scope.", resp, body_type=Problem ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) diff --git a/sumup/merchants/resource.py b/sumup/merchants/resource.py index 8dbca6e6..8b197dec 100644 --- a/sumup/merchants/resource.py +++ b/sumup/merchants/resource.py @@ -1,5 +1,5 @@ # Code generated by `py-sdk-gen`. DO NOT EDIT. -# ruff: noqa: F401, F541 +# ruff: noqa: F401 """ A Merchant represents a single business which can use SumUp products like payment processing. """ @@ -13,7 +13,7 @@ import pydantic import typing_extensions -from .._exceptions import APIError +from .._exceptions import APIError, _wrap_request_errors from .._service import ( NOT_GIVEN, AsyncResource, @@ -66,22 +66,25 @@ def get(self, merchant_code: str, headers: HeaderTypes | None = None) -> Merchan Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 404: The requested Merchant does not exist. + 404: The requested Merchant does not exist. (raises NotFoundError) Unexpected response statuses also raise this exception. """ - resp = self._client.get( - f"/v1/merchants/{merchant_code}", - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.get( + f"/v1/merchants/{merchant_code}", + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(Merchant).validate_python(resp.json()) elif resp.status_code == 404: - raise APIError( - "The requested Merchant does not exist.", status=resp.status_code, body=resp.text + raise APIError.from_response( + "The requested Merchant does not exist.", resp, body_type=Problem ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) def list_persons( self, merchant_code: str, headers: HeaderTypes | None = None @@ -95,22 +98,25 @@ def list_persons( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 404: The requested Merchant does not exist. + 404: The requested Merchant does not exist. (raises NotFoundError) Unexpected response statuses also raise this exception. """ - resp = self._client.get( - f"/v1/merchants/{merchant_code}/persons", - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.get( + f"/v1/merchants/{merchant_code}/persons", + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(ListPersonsResponseBody).validate_python(resp.json()) elif resp.status_code == 404: - raise APIError( - "The requested Merchant does not exist.", status=resp.status_code, body=resp.text + raise APIError.from_response( + "The requested Merchant does not exist.", resp, body_type=Problem ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) def get_person( self, merchant_code: str, person_id: str, headers: HeaderTypes | None = None @@ -124,22 +130,25 @@ def get_person( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 404: The requested Person does not exist. + 404: The requested Person does not exist. (raises NotFoundError) Unexpected response statuses also raise this exception. """ - resp = self._client.get( - f"/v1/merchants/{merchant_code}/persons/{person_id}", - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.get( + f"/v1/merchants/{merchant_code}/persons/{person_id}", + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(Person).validate_python(resp.json()) elif resp.status_code == 404: - raise APIError( - "The requested Person does not exist.", status=resp.status_code, body=resp.text + raise APIError.from_response( + "The requested Person does not exist.", resp, body_type=Problem ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) class AsyncMerchantsResource(AsyncResource): @@ -158,22 +167,25 @@ async def get(self, merchant_code: str, headers: HeaderTypes | None = None) -> M Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 404: The requested Merchant does not exist. + 404: The requested Merchant does not exist. (raises NotFoundError) Unexpected response statuses also raise this exception. """ - resp = await self._client.get( - f"/v1/merchants/{merchant_code}", - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.get( + f"/v1/merchants/{merchant_code}", + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(Merchant).validate_python(resp.json()) elif resp.status_code == 404: - raise APIError( - "The requested Merchant does not exist.", status=resp.status_code, body=resp.text + raise APIError.from_response( + "The requested Merchant does not exist.", resp, body_type=Problem ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) async def list_persons( self, merchant_code: str, headers: HeaderTypes | None = None @@ -187,22 +199,25 @@ async def list_persons( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 404: The requested Merchant does not exist. + 404: The requested Merchant does not exist. (raises NotFoundError) Unexpected response statuses also raise this exception. """ - resp = await self._client.get( - f"/v1/merchants/{merchant_code}/persons", - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.get( + f"/v1/merchants/{merchant_code}/persons", + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(ListPersonsResponseBody).validate_python(resp.json()) elif resp.status_code == 404: - raise APIError( - "The requested Merchant does not exist.", status=resp.status_code, body=resp.text + raise APIError.from_response( + "The requested Merchant does not exist.", resp, body_type=Problem ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) async def get_person( self, merchant_code: str, person_id: str, headers: HeaderTypes | None = None @@ -216,19 +231,22 @@ async def get_person( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 404: The requested Person does not exist. + 404: The requested Person does not exist. (raises NotFoundError) Unexpected response statuses also raise this exception. """ - resp = await self._client.get( - f"/v1/merchants/{merchant_code}/persons/{person_id}", - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.get( + f"/v1/merchants/{merchant_code}/persons/{person_id}", + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(Person).validate_python(resp.json()) elif resp.status_code == 404: - raise APIError( - "The requested Person does not exist.", status=resp.status_code, body=resp.text + raise APIError.from_response( + "The requested Person does not exist.", resp, body_type=Problem ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) diff --git a/sumup/payouts/__init__.py b/sumup/payouts/__init__.py index 46a21f6c..f228deca 100644 --- a/sumup/payouts/__init__.py +++ b/sumup/payouts/__init__.py @@ -8,6 +8,7 @@ ) from .resource import ( AsyncPayoutsResource, + ListPayoutsV1400Response, PayoutsResource, ) @@ -17,6 +18,7 @@ "ErrorExtended", "FinancialPayout", "FinancialPayouts", + "ListPayoutsV1400Response", "PayoutsResource", "Problem", ] diff --git a/sumup/payouts/resource.py b/sumup/payouts/resource.py index 78dea3b6..d5b6f81a 100644 --- a/sumup/payouts/resource.py +++ b/sumup/payouts/resource.py @@ -1,5 +1,5 @@ # Code generated by `py-sdk-gen`. DO NOT EDIT. -# ruff: noqa: F401, F541 +# ruff: noqa: F401 """ The Payouts model will allow you to track funds you’ve received from SumUp. @@ -15,7 +15,7 @@ import pydantic import typing_extensions -from .._exceptions import APIError +from .._exceptions import APIError, _wrap_request_errors from .._service import ( NOT_GIVEN, AsyncResource, @@ -25,7 +25,14 @@ serialize_query_params, serialize_request_data, ) -from ..types import Error, ErrorExtended, FinancialPayout, FinancialPayouts, Problem +from ..types import ( + Error, + ErrorExtended, + FinancialPayout, + FinancialPayouts, + ListPayoutsV1400Response, + Problem, +) ListPayoutsV1ParamsFormatInput = typing.Literal["csv", "json"] | str @@ -62,9 +69,11 @@ def list( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: The request is invalid for the submitted query parameters. - 401: The request is not authorized. + 400: The request is invalid for the submitted query parameters. (raises BadRequestError) + 401: The request is not authorized. (raises AuthenticationError) Unexpected response statuses also raise this exception. """ query_data: dict[str, typing.Any] = {} @@ -77,25 +86,24 @@ def list( if not isinstance(order, NotGivenType) and order is not None: query_data["order"] = order - resp = self._client.get( - f"/v1.0/merchants/{merchant_code}/payouts", - params=serialize_query_params(query_data) if query_data else None, - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.get( + f"/v1.0/merchants/{merchant_code}/payouts", + params=serialize_query_params(query_data) if query_data else None, + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(FinancialPayouts).validate_python(resp.json()) elif resp.status_code == 400: - raise APIError( + raise APIError.from_response( "The request is invalid for the submitted query parameters.", - status=resp.status_code, - body=resp.text, + resp, + body_type=ListPayoutsV1400Response, ) elif resp.status_code == 401: - raise APIError( - "The request is not authorized.", status=resp.status_code, body=resp.text - ) + raise APIError.from_response("The request is not authorized.", resp, body_type=Problem) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) class AsyncPayoutsResource(AsyncResource): @@ -128,9 +136,11 @@ async def list( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: The request is invalid for the submitted query parameters. - 401: The request is not authorized. + 400: The request is invalid for the submitted query parameters. (raises BadRequestError) + 401: The request is not authorized. (raises AuthenticationError) Unexpected response statuses also raise this exception. """ query_data: dict[str, typing.Any] = {} @@ -143,22 +153,21 @@ async def list( if not isinstance(order, NotGivenType) and order is not None: query_data["order"] = order - resp = await self._client.get( - f"/v1.0/merchants/{merchant_code}/payouts", - params=serialize_query_params(query_data) if query_data else None, - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.get( + f"/v1.0/merchants/{merchant_code}/payouts", + params=serialize_query_params(query_data) if query_data else None, + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(FinancialPayouts).validate_python(resp.json()) elif resp.status_code == 400: - raise APIError( + raise APIError.from_response( "The request is invalid for the submitted query parameters.", - status=resp.status_code, - body=resp.text, + resp, + body_type=ListPayoutsV1400Response, ) elif resp.status_code == 401: - raise APIError( - "The request is not authorized.", status=resp.status_code, body=resp.text - ) + raise APIError.from_response("The request is not authorized.", resp, body_type=Problem) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) diff --git a/sumup/readers/resource.py b/sumup/readers/resource.py index 28870dcd..dad9b497 100644 --- a/sumup/readers/resource.py +++ b/sumup/readers/resource.py @@ -1,5 +1,5 @@ # Code generated by `py-sdk-gen`. DO NOT EDIT. -# ruff: noqa: F401, F541 +# ruff: noqa: F401 """ A reader represents a device that accepts payments. You can use the SumUp Solo to accept in-person payments. """ @@ -13,7 +13,7 @@ import pydantic import typing_extensions -from .._exceptions import APIError +from .._exceptions import APIError, _wrap_request_errors from .._secret import Secret from .._service import ( NOT_GIVEN, @@ -418,11 +418,13 @@ def create_go_checkout( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: The request is invalid. - 401: Authentication failed or missing required scope. - 404: The requested Reader resource does not exist. - 422: The request could not be processed as it violates a business rule. + 400: The request is invalid. (raises BadRequestError) + 401: Authentication failed or missing required scope. (raises AuthenticationError) + 404: The requested Reader resource does not exist. (raises NotFoundError) + 422: The request could not be processed as it violates a business rule. (raises UnprocessableEntityError) Unexpected response statuses also raise this exception. """ body_data: dict[str, typing.Any] = {} @@ -433,35 +435,32 @@ def create_go_checkout( body_data["tip_amount"] = tip_amount body_data["total_amount"] = total_amount - resp = self._client.post( - f"/v0/merchants/{merchant_code}/readers/{reader_id}/go-checkout", - json=serialize_request_data(body_data), - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.post( + f"/v0/merchants/{merchant_code}/readers/{reader_id}/go-checkout", + json=serialize_request_data(body_data), + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(ReaderPaymentResponse).validate_python(resp.json()) elif resp.status_code == 400: - raise APIError("The request is invalid.", status=resp.status_code, body=resp.text) + raise APIError.from_response("The request is invalid.", resp, body_type=Problem) elif resp.status_code == 401: - raise APIError( - "Authentication failed or missing required scope.", - status=resp.status_code, - body=resp.text, + raise APIError.from_response( + "Authentication failed or missing required scope.", resp, body_type=Problem ) elif resp.status_code == 404: - raise APIError( - "The requested Reader resource does not exist.", - status=resp.status_code, - body=resp.text, + raise APIError.from_response( + "The requested Reader resource does not exist.", resp, body_type=Problem ) elif resp.status_code == 422: - raise APIError( + raise APIError.from_response( "The request could not be processed as it violates a business rule.", - status=resp.status_code, - body=resp.text, + resp, + body_type=Problem, ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) def list( self, merchant_code: str, headers: HeaderTypes | None = None @@ -473,24 +472,25 @@ def list( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 401: Authentication failed or missing required scope. + 401: Authentication failed or missing required scope. (raises AuthenticationError) Unexpected response statuses also raise this exception. """ - resp = self._client.get( - f"/v0.1/merchants/{merchant_code}/readers", - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.get( + f"/v0.1/merchants/{merchant_code}/readers", + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(ListReaders200Response).validate_python(resp.json()) elif resp.status_code == 401: - raise APIError( - "Authentication failed or missing required scope.", - status=resp.status_code, - body=resp.text, + raise APIError.from_response( + "Authentication failed or missing required scope.", resp, body_type=Problem ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) def create( self, @@ -508,10 +508,12 @@ def create( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: The request is invalid. - 404: There's no pending reader for the submitted pairing code. - 409: The Reader is not in a pending state. + 400: The request is invalid. (raises BadRequestError) + 404: There's no pending reader for the submitted pairing code. (raises NotFoundError) + 409: The Reader is not in a pending state. (raises ConflictError) Unexpected response statuses also raise this exception. """ body_data: dict[str, typing.Any] = {} @@ -520,27 +522,26 @@ def create( if not isinstance(metadata, NotGivenType): body_data["metadata"] = metadata - resp = self._client.post( - f"/v0.1/merchants/{merchant_code}/readers", - json=serialize_request_data(body_data), - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.post( + f"/v0.1/merchants/{merchant_code}/readers", + json=serialize_request_data(body_data), + headers=headers, + ) if resp.status_code == 201: return pydantic.TypeAdapter(Reader).validate_python(resp.json()) elif resp.status_code == 400: - raise APIError("The request is invalid.", status=resp.status_code, body=resp.text) + raise APIError.from_response("The request is invalid.", resp, body_type=Problem) elif resp.status_code == 404: - raise APIError( - "There's no pending reader for the submitted pairing code.", - status=resp.status_code, - body=resp.text, + raise APIError.from_response( + "There's no pending reader for the submitted pairing code.", resp, body_type=Problem ) elif resp.status_code == 409: - raise APIError( - "The Reader is not in a pending state.", status=resp.status_code, body=resp.text + raise APIError.from_response( + "The Reader is not in a pending state.", resp, body_type=Problem ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) def get( self, merchant_code: str, reader_id: ReaderId, headers: HeaderTypes | None = None @@ -552,24 +553,25 @@ def get( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 404: The requested Reader resource does not exist. + 404: The requested Reader resource does not exist. (raises NotFoundError) Unexpected response statuses also raise this exception. """ - resp = self._client.get( - f"/v0.1/merchants/{merchant_code}/readers/{reader_id}", - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.get( + f"/v0.1/merchants/{merchant_code}/readers/{reader_id}", + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(Reader).validate_python(resp.json()) elif resp.status_code == 404: - raise APIError( - "The requested Reader resource does not exist.", - status=resp.status_code, - body=resp.text, + raise APIError.from_response( + "The requested Reader resource does not exist.", resp, body_type=Problem ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) def delete(self, merchant_code: str, reader_id: ReaderId, headers: HeaderTypes | None = None): """ @@ -579,24 +581,25 @@ def delete(self, merchant_code: str, reader_id: ReaderId, headers: HeaderTypes | Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 404: The requested Reader resource does not exist. + 404: The requested Reader resource does not exist. (raises NotFoundError) Unexpected response statuses also raise this exception. """ - resp = self._client.delete( - f"/v0.1/merchants/{merchant_code}/readers/{reader_id}", - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.delete( + f"/v0.1/merchants/{merchant_code}/readers/{reader_id}", + headers=headers, + ) if resp.status_code == 200: return elif resp.status_code == 404: - raise APIError( - "The requested Reader resource does not exist.", - status=resp.status_code, - body=resp.text, + raise APIError.from_response( + "The requested Reader resource does not exist.", resp, body_type=Problem ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) def update( self, @@ -616,9 +619,11 @@ def update( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 403: The request isn't sufficiently authorized to modify the reader. - 404: The requested Reader resource does not exist. + 403: The request isn't sufficiently authorized to modify the reader. (raises PermissionDeniedError) + 404: The requested Reader resource does not exist. (raises NotFoundError) Unexpected response statuses also raise this exception. """ body_data: dict[str, typing.Any] = {} @@ -627,27 +632,26 @@ def update( if not isinstance(metadata, NotGivenType): body_data["metadata"] = metadata - resp = self._client.patch( - f"/v0.1/merchants/{merchant_code}/readers/{reader_id}", - json=serialize_request_data(body_data), - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.patch( + f"/v0.1/merchants/{merchant_code}/readers/{reader_id}", + json=serialize_request_data(body_data), + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(Reader).validate_python(resp.json()) elif resp.status_code == 403: - raise APIError( + raise APIError.from_response( "The request isn't sufficiently authorized to modify the reader.", - status=resp.status_code, - body=resp.text, + resp, + body_type=Problem, ) elif resp.status_code == 404: - raise APIError( - "The requested Reader resource does not exist.", - status=resp.status_code, - body=resp.text, + raise APIError.from_response( + "The requested Reader resource does not exist.", resp, body_type=Problem ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) def create_checkout( self, @@ -688,11 +692,13 @@ def create_checkout( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: Response when given params (or one of them) are invalid - 401: Unauthorized - 404: Response when given reader is not found - 422: Response when given params (or one of them) are invalid + 400: Response when given params (or one of them) are invalid (raises BadRequestError) + 401: Unauthorized (raises AuthenticationError) + 404: Response when given reader is not found (raises NotFoundError) + 422: Response when given params (or one of them) are invalid (raises UnprocessableEntityError) Unexpected response statuses also raise this exception. """ body_data: dict[str, typing.Any] = {} @@ -716,33 +722,74 @@ def create_checkout( body_data["tip_timeout"] = tip_timeout body_data["total_amount"] = total_amount - resp = self._client.post( - f"/v0.1/merchants/{merchant_code}/readers/{reader_id}/checkout", - json=serialize_request_data(body_data), - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.post( + f"/v0.1/merchants/{merchant_code}/readers/{reader_id}/checkout", + json=serialize_request_data(body_data), + headers=headers, + ) if resp.status_code == 201: return pydantic.TypeAdapter(CreateReaderCheckoutResponse).validate_python(resp.json()) elif resp.status_code == 400: - raise APIError( - "Response when given params (or one of them) are invalid", - status=resp.status_code, - body=resp.text, - ) + content_type = resp.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type == "application/json": + raise APIError.from_response( + "Response when given params (or one of them) are invalid", + resp, + body_type=CreateReaderCheckoutError, + ) + elif content_type == "application/problem+json": + raise APIError.from_response( + "Response when given params (or one of them) are invalid", + resp, + body_type=Problem, + ) + else: + raise APIError.from_response( + "Response when given params (or one of them) are invalid", resp + ) elif resp.status_code == 401: - raise APIError("Unauthorized", status=resp.status_code, body=resp.text) + content_type = resp.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type == "application/json": + raise APIError.from_response( + "Unauthorized", resp, body_type=CreateReaderCheckoutError + ) + elif content_type == "application/problem+json": + raise APIError.from_response("Unauthorized", resp, body_type=Problem) + else: + raise APIError.from_response("Unauthorized", resp) elif resp.status_code == 404: - raise APIError( - "Response when given reader is not found", status=resp.status_code, body=resp.text - ) + content_type = resp.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type == "application/json": + raise APIError.from_response( + "Response when given reader is not found", resp, body_type=NotFound + ) + elif content_type == "application/problem+json": + raise APIError.from_response( + "Response when given reader is not found", resp, body_type=Problem + ) + else: + raise APIError.from_response("Response when given reader is not found", resp) elif resp.status_code == 422: - raise APIError( - "Response when given params (or one of them) are invalid", - status=resp.status_code, - body=resp.text, - ) + content_type = resp.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type == "application/json": + raise APIError.from_response( + "Response when given params (or one of them) are invalid", + resp, + body_type=CreateReaderCheckoutUnprocessableEntity, + ) + elif content_type == "application/problem+json": + raise APIError.from_response( + "Response when given params (or one of them) are invalid", + resp, + body_type=Problem, + ) + else: + raise APIError.from_response( + "Response when given params (or one of them) are invalid", resp + ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) def get_status( self, merchant_code: str, reader_id: str, headers: HeaderTypes | None = None @@ -773,36 +820,67 @@ def get_status( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: Response when given params (or one of them) are invalid - 401: Response when given merchant's token is invalid - 404: Response when given reader is not found + 400: Response when given params (or one of them) are invalid (raises BadRequestError) + 401: Response when given merchant's token is invalid (raises AuthenticationError) + 404: Response when given reader is not found (raises NotFoundError) Unexpected response statuses also raise this exception. """ - resp = self._client.get( - f"/v0.1/merchants/{merchant_code}/readers/{reader_id}/status", - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.get( + f"/v0.1/merchants/{merchant_code}/readers/{reader_id}/status", + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(StatusResponse).validate_python(resp.json()) elif resp.status_code == 400: - raise APIError( - "Response when given params (or one of them) are invalid", - status=resp.status_code, - body=resp.text, - ) + content_type = resp.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type == "application/json": + raise APIError.from_response( + "Response when given params (or one of them) are invalid", + resp, + body_type=BadRequest, + ) + elif content_type == "application/problem+json": + raise APIError.from_response( + "Response when given params (or one of them) are invalid", + resp, + body_type=Problem, + ) + else: + raise APIError.from_response( + "Response when given params (or one of them) are invalid", resp + ) elif resp.status_code == 401: - raise APIError( - "Response when given merchant's token is invalid", - status=resp.status_code, - body=resp.text, - ) + content_type = resp.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type == "application/json": + raise APIError.from_response( + "Response when given merchant's token is invalid", resp, body_type=Unauthorized + ) + elif content_type == "application/problem+json": + raise APIError.from_response( + "Response when given merchant's token is invalid", resp, body_type=Problem + ) + else: + raise APIError.from_response( + "Response when given merchant's token is invalid", resp + ) elif resp.status_code == 404: - raise APIError( - "Response when given reader is not found", status=resp.status_code, body=resp.text - ) + content_type = resp.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type == "application/json": + raise APIError.from_response( + "Response when given reader is not found", resp, body_type=NotFound + ) + elif content_type == "application/problem+json": + raise APIError.from_response( + "Response when given reader is not found", resp, body_type=Problem + ) + else: + raise APIError.from_response("Response when given reader is not found", resp) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) def get_reader_settings( self, merchant_code: str, reader_id: str, headers: HeaderTypes | None = None @@ -821,34 +899,70 @@ def get_reader_settings( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 401: Unauthorized - 404: The reader was not found, or it is offline and has no saved settings. - 422: The reader model is not supported, or the reader could not return its settings. + 401: Unauthorized (raises AuthenticationError) + 404: The reader was not found, or it is offline and has no saved settings. (raises NotFoundError) + 422: The reader model is not supported, or the reader could not return its settings. (raises UnprocessableEntityError) Unexpected response statuses also raise this exception. """ - resp = self._client.get( - f"/v0.1/merchants/{merchant_code}/readers/{reader_id}/settings", - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.get( + f"/v0.1/merchants/{merchant_code}/readers/{reader_id}/settings", + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(GetReaderSettingsResponse).validate_python(resp.json()) elif resp.status_code == 401: - raise APIError("Unauthorized", status=resp.status_code, body=resp.text) + content_type = resp.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type == "application/json": + raise APIError.from_response( + "Unauthorized", resp, body_type=UpdateReaderSettingsError + ) + elif content_type == "application/problem+json": + raise APIError.from_response("Unauthorized", resp, body_type=Problem) + else: + raise APIError.from_response("Unauthorized", resp) elif resp.status_code == 404: - raise APIError( - "The reader was not found, or it is offline and has no saved settings.", - status=resp.status_code, - body=resp.text, - ) + content_type = resp.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type == "application/json": + raise APIError.from_response( + "The reader was not found, or it is offline and has no saved settings.", + resp, + body_type=NotFound, + ) + elif content_type == "application/problem+json": + raise APIError.from_response( + "The reader was not found, or it is offline and has no saved settings.", + resp, + body_type=Problem, + ) + else: + raise APIError.from_response( + "The reader was not found, or it is offline and has no saved settings.", resp + ) elif resp.status_code == 422: - raise APIError( - "The reader model is not supported, or the reader could not return its settings.", - status=resp.status_code, - body=resp.text, - ) + content_type = resp.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type == "application/json": + raise APIError.from_response( + "The reader model is not supported, or the reader could not return its settings.", + resp, + body_type=UpdateReaderSettingsUnprocessableEntity, + ) + elif content_type == "application/problem+json": + raise APIError.from_response( + "The reader model is not supported, or the reader could not return its settings.", + resp, + body_type=Problem, + ) + else: + raise APIError.from_response( + "The reader model is not supported, or the reader could not return its settings.", + resp, + ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) def update_reader_settings( self, @@ -874,39 +988,77 @@ def update_reader_settings( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: The request body is malformed. - 401: Unauthorized - 404: The reader was not found. - 422: The settings are invalid, the reader is offline, the reader model is not supported, or the readercould not apply the update. + 400: The request body is malformed. (raises BadRequestError) + 401: Unauthorized (raises AuthenticationError) + 404: The reader was not found. (raises NotFoundError) + 422: The settings are invalid, the reader is offline, the reader model is not supported, or the readercould not apply the update. (raises UnprocessableEntityError) Unexpected response statuses also raise this exception. """ body_data: dict[str, typing.Any] = {} body_data["menu_lock"] = menu_lock - resp = self._client.patch( - f"/v0.1/merchants/{merchant_code}/readers/{reader_id}/settings", - json=serialize_request_data(body_data), - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.patch( + f"/v0.1/merchants/{merchant_code}/readers/{reader_id}/settings", + json=serialize_request_data(body_data), + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(UpdateReaderSettingsResponse).validate_python(resp.json()) elif resp.status_code == 400: - raise APIError( - "The request body is malformed.", status=resp.status_code, body=resp.text - ) + content_type = resp.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type == "application/json": + raise APIError.from_response( + "The request body is malformed.", resp, body_type=UpdateReaderSettingsError + ) + elif content_type == "application/problem+json": + raise APIError.from_response( + "The request body is malformed.", resp, body_type=Problem + ) + else: + raise APIError.from_response("The request body is malformed.", resp) elif resp.status_code == 401: - raise APIError("Unauthorized", status=resp.status_code, body=resp.text) + content_type = resp.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type == "application/json": + raise APIError.from_response( + "Unauthorized", resp, body_type=UpdateReaderSettingsError + ) + elif content_type == "application/problem+json": + raise APIError.from_response("Unauthorized", resp, body_type=Problem) + else: + raise APIError.from_response("Unauthorized", resp) elif resp.status_code == 404: - raise APIError("The reader was not found.", status=resp.status_code, body=resp.text) + content_type = resp.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type == "application/json": + raise APIError.from_response("The reader was not found.", resp, body_type=NotFound) + elif content_type == "application/problem+json": + raise APIError.from_response("The reader was not found.", resp, body_type=Problem) + else: + raise APIError.from_response("The reader was not found.", resp) elif resp.status_code == 422: - raise APIError( - "The settings are invalid, the reader is offline, the reader model is not supported, or the reader could not apply the update.", - status=resp.status_code, - body=resp.text, - ) + content_type = resp.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type == "application/json": + raise APIError.from_response( + "The settings are invalid, the reader is offline, the reader model is not supported, or the reader could not apply the update.", + resp, + body_type=UpdateReaderSettingsUnprocessableEntity, + ) + elif content_type == "application/problem+json": + raise APIError.from_response( + "The settings are invalid, the reader is offline, the reader model is not supported, or the reader could not apply the update.", + resp, + body_type=Problem, + ) + else: + raise APIError.from_response( + "The settings are invalid, the reader is offline, the reader model is not supported, or the reader could not apply the update.", + resp, + ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) def terminate_checkout( self, merchant_code: str, reader_id: str, headers: HeaderTypes | None = None @@ -932,39 +1084,82 @@ def terminate_checkout( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: Response when given params (or one of them) are invalid - 401: Unauthorized - 404: Response when given reader is not found - 422: Response when given params (or one of them) are invalid + 400: Response when given params (or one of them) are invalid (raises BadRequestError) + 401: Unauthorized (raises AuthenticationError) + 404: Response when given reader is not found (raises NotFoundError) + 422: Response when given params (or one of them) are invalid (raises UnprocessableEntityError) Unexpected response statuses also raise this exception. """ - resp = self._client.post( - f"/v0.1/merchants/{merchant_code}/readers/{reader_id}/terminate", - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.post( + f"/v0.1/merchants/{merchant_code}/readers/{reader_id}/terminate", + headers=headers, + ) if resp.status_code == 202: return elif resp.status_code == 400: - raise APIError( - "Response when given params (or one of them) are invalid", - status=resp.status_code, - body=resp.text, - ) + content_type = resp.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type == "application/json": + raise APIError.from_response( + "Response when given params (or one of them) are invalid", + resp, + body_type=CreateReaderTerminateError, + ) + elif content_type == "application/problem+json": + raise APIError.from_response( + "Response when given params (or one of them) are invalid", + resp, + body_type=Problem, + ) + else: + raise APIError.from_response( + "Response when given params (or one of them) are invalid", resp + ) elif resp.status_code == 401: - raise APIError("Unauthorized", status=resp.status_code, body=resp.text) + content_type = resp.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type == "application/json": + raise APIError.from_response( + "Unauthorized", resp, body_type=CreateReaderTerminateError + ) + elif content_type == "application/problem+json": + raise APIError.from_response("Unauthorized", resp, body_type=Problem) + else: + raise APIError.from_response("Unauthorized", resp) elif resp.status_code == 404: - raise APIError( - "Response when given reader is not found", status=resp.status_code, body=resp.text - ) + content_type = resp.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type == "application/json": + raise APIError.from_response( + "Response when given reader is not found", resp, body_type=NotFound + ) + elif content_type == "application/problem+json": + raise APIError.from_response( + "Response when given reader is not found", resp, body_type=Problem + ) + else: + raise APIError.from_response("Response when given reader is not found", resp) elif resp.status_code == 422: - raise APIError( - "Response when given params (or one of them) are invalid", - status=resp.status_code, - body=resp.text, - ) + content_type = resp.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type == "application/json": + raise APIError.from_response( + "Response when given params (or one of them) are invalid", + resp, + body_type=CreateReaderTerminateUnprocessableEntity, + ) + elif content_type == "application/problem+json": + raise APIError.from_response( + "Response when given params (or one of them) are invalid", + resp, + body_type=Problem, + ) + else: + raise APIError.from_response( + "Response when given params (or one of them) are invalid", resp + ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) def get_checkout( self, @@ -981,27 +1176,46 @@ def get_checkout( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 401: Unauthorized - 404: Response when given reader or checkout is not found + 401: Unauthorized (raises AuthenticationError) + 404: Response when given reader or checkout is not found (raises NotFoundError) Unexpected response statuses also raise this exception. """ - resp = self._client.get( - f"/v0.1/merchants/{merchant_code}/readers/{reader_id}/checkout/{checkout_id}", - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.get( + f"/v0.1/merchants/{merchant_code}/readers/{reader_id}/checkout/{checkout_id}", + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(GetReaderCheckoutResponse).validate_python(resp.json()) elif resp.status_code == 401: - raise APIError("Unauthorized", status=resp.status_code, body=resp.text) + content_type = resp.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type == "application/json": + raise APIError.from_response( + "Unauthorized", resp, body_type=CreateReaderCheckoutError + ) + elif content_type == "application/problem+json": + raise APIError.from_response("Unauthorized", resp, body_type=Problem) + else: + raise APIError.from_response("Unauthorized", resp) elif resp.status_code == 404: - raise APIError( - "Response when given reader or checkout is not found", - status=resp.status_code, - body=resp.text, - ) + content_type = resp.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type == "application/json": + raise APIError.from_response( + "Response when given reader or checkout is not found", resp, body_type=NotFound + ) + elif content_type == "application/problem+json": + raise APIError.from_response( + "Response when given reader or checkout is not found", resp, body_type=Problem + ) + else: + raise APIError.from_response( + "Response when given reader or checkout is not found", resp + ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) class AsyncReadersResource(AsyncResource): @@ -1030,11 +1244,13 @@ async def create_go_checkout( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: The request is invalid. - 401: Authentication failed or missing required scope. - 404: The requested Reader resource does not exist. - 422: The request could not be processed as it violates a business rule. + 400: The request is invalid. (raises BadRequestError) + 401: Authentication failed or missing required scope. (raises AuthenticationError) + 404: The requested Reader resource does not exist. (raises NotFoundError) + 422: The request could not be processed as it violates a business rule. (raises UnprocessableEntityError) Unexpected response statuses also raise this exception. """ body_data: dict[str, typing.Any] = {} @@ -1045,35 +1261,32 @@ async def create_go_checkout( body_data["tip_amount"] = tip_amount body_data["total_amount"] = total_amount - resp = await self._client.post( - f"/v0/merchants/{merchant_code}/readers/{reader_id}/go-checkout", - json=serialize_request_data(body_data), - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.post( + f"/v0/merchants/{merchant_code}/readers/{reader_id}/go-checkout", + json=serialize_request_data(body_data), + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(ReaderPaymentResponse).validate_python(resp.json()) elif resp.status_code == 400: - raise APIError("The request is invalid.", status=resp.status_code, body=resp.text) + raise APIError.from_response("The request is invalid.", resp, body_type=Problem) elif resp.status_code == 401: - raise APIError( - "Authentication failed or missing required scope.", - status=resp.status_code, - body=resp.text, + raise APIError.from_response( + "Authentication failed or missing required scope.", resp, body_type=Problem ) elif resp.status_code == 404: - raise APIError( - "The requested Reader resource does not exist.", - status=resp.status_code, - body=resp.text, + raise APIError.from_response( + "The requested Reader resource does not exist.", resp, body_type=Problem ) elif resp.status_code == 422: - raise APIError( + raise APIError.from_response( "The request could not be processed as it violates a business rule.", - status=resp.status_code, - body=resp.text, + resp, + body_type=Problem, ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) async def list( self, merchant_code: str, headers: HeaderTypes | None = None @@ -1085,24 +1298,25 @@ async def list( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 401: Authentication failed or missing required scope. + 401: Authentication failed or missing required scope. (raises AuthenticationError) Unexpected response statuses also raise this exception. """ - resp = await self._client.get( - f"/v0.1/merchants/{merchant_code}/readers", - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.get( + f"/v0.1/merchants/{merchant_code}/readers", + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(ListReaders200Response).validate_python(resp.json()) elif resp.status_code == 401: - raise APIError( - "Authentication failed or missing required scope.", - status=resp.status_code, - body=resp.text, + raise APIError.from_response( + "Authentication failed or missing required scope.", resp, body_type=Problem ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) async def create( self, @@ -1120,10 +1334,12 @@ async def create( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: The request is invalid. - 404: There's no pending reader for the submitted pairing code. - 409: The Reader is not in a pending state. + 400: The request is invalid. (raises BadRequestError) + 404: There's no pending reader for the submitted pairing code. (raises NotFoundError) + 409: The Reader is not in a pending state. (raises ConflictError) Unexpected response statuses also raise this exception. """ body_data: dict[str, typing.Any] = {} @@ -1132,27 +1348,26 @@ async def create( if not isinstance(metadata, NotGivenType): body_data["metadata"] = metadata - resp = await self._client.post( - f"/v0.1/merchants/{merchant_code}/readers", - json=serialize_request_data(body_data), - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.post( + f"/v0.1/merchants/{merchant_code}/readers", + json=serialize_request_data(body_data), + headers=headers, + ) if resp.status_code == 201: return pydantic.TypeAdapter(Reader).validate_python(resp.json()) elif resp.status_code == 400: - raise APIError("The request is invalid.", status=resp.status_code, body=resp.text) + raise APIError.from_response("The request is invalid.", resp, body_type=Problem) elif resp.status_code == 404: - raise APIError( - "There's no pending reader for the submitted pairing code.", - status=resp.status_code, - body=resp.text, + raise APIError.from_response( + "There's no pending reader for the submitted pairing code.", resp, body_type=Problem ) elif resp.status_code == 409: - raise APIError( - "The Reader is not in a pending state.", status=resp.status_code, body=resp.text + raise APIError.from_response( + "The Reader is not in a pending state.", resp, body_type=Problem ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) async def get( self, merchant_code: str, reader_id: ReaderId, headers: HeaderTypes | None = None @@ -1164,24 +1379,25 @@ async def get( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 404: The requested Reader resource does not exist. + 404: The requested Reader resource does not exist. (raises NotFoundError) Unexpected response statuses also raise this exception. """ - resp = await self._client.get( - f"/v0.1/merchants/{merchant_code}/readers/{reader_id}", - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.get( + f"/v0.1/merchants/{merchant_code}/readers/{reader_id}", + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(Reader).validate_python(resp.json()) elif resp.status_code == 404: - raise APIError( - "The requested Reader resource does not exist.", - status=resp.status_code, - body=resp.text, + raise APIError.from_response( + "The requested Reader resource does not exist.", resp, body_type=Problem ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) async def delete( self, merchant_code: str, reader_id: ReaderId, headers: HeaderTypes | None = None @@ -1193,24 +1409,25 @@ async def delete( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 404: The requested Reader resource does not exist. + 404: The requested Reader resource does not exist. (raises NotFoundError) Unexpected response statuses also raise this exception. """ - resp = await self._client.delete( - f"/v0.1/merchants/{merchant_code}/readers/{reader_id}", - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.delete( + f"/v0.1/merchants/{merchant_code}/readers/{reader_id}", + headers=headers, + ) if resp.status_code == 200: return elif resp.status_code == 404: - raise APIError( - "The requested Reader resource does not exist.", - status=resp.status_code, - body=resp.text, + raise APIError.from_response( + "The requested Reader resource does not exist.", resp, body_type=Problem ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) async def update( self, @@ -1230,9 +1447,11 @@ async def update( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 403: The request isn't sufficiently authorized to modify the reader. - 404: The requested Reader resource does not exist. + 403: The request isn't sufficiently authorized to modify the reader. (raises PermissionDeniedError) + 404: The requested Reader resource does not exist. (raises NotFoundError) Unexpected response statuses also raise this exception. """ body_data: dict[str, typing.Any] = {} @@ -1241,27 +1460,26 @@ async def update( if not isinstance(metadata, NotGivenType): body_data["metadata"] = metadata - resp = await self._client.patch( - f"/v0.1/merchants/{merchant_code}/readers/{reader_id}", - json=serialize_request_data(body_data), - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.patch( + f"/v0.1/merchants/{merchant_code}/readers/{reader_id}", + json=serialize_request_data(body_data), + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(Reader).validate_python(resp.json()) elif resp.status_code == 403: - raise APIError( + raise APIError.from_response( "The request isn't sufficiently authorized to modify the reader.", - status=resp.status_code, - body=resp.text, + resp, + body_type=Problem, ) elif resp.status_code == 404: - raise APIError( - "The requested Reader resource does not exist.", - status=resp.status_code, - body=resp.text, + raise APIError.from_response( + "The requested Reader resource does not exist.", resp, body_type=Problem ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) async def create_checkout( self, @@ -1302,11 +1520,13 @@ async def create_checkout( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: Response when given params (or one of them) are invalid - 401: Unauthorized - 404: Response when given reader is not found - 422: Response when given params (or one of them) are invalid + 400: Response when given params (or one of them) are invalid (raises BadRequestError) + 401: Unauthorized (raises AuthenticationError) + 404: Response when given reader is not found (raises NotFoundError) + 422: Response when given params (or one of them) are invalid (raises UnprocessableEntityError) Unexpected response statuses also raise this exception. """ body_data: dict[str, typing.Any] = {} @@ -1330,33 +1550,74 @@ async def create_checkout( body_data["tip_timeout"] = tip_timeout body_data["total_amount"] = total_amount - resp = await self._client.post( - f"/v0.1/merchants/{merchant_code}/readers/{reader_id}/checkout", - json=serialize_request_data(body_data), - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.post( + f"/v0.1/merchants/{merchant_code}/readers/{reader_id}/checkout", + json=serialize_request_data(body_data), + headers=headers, + ) if resp.status_code == 201: return pydantic.TypeAdapter(CreateReaderCheckoutResponse).validate_python(resp.json()) elif resp.status_code == 400: - raise APIError( - "Response when given params (or one of them) are invalid", - status=resp.status_code, - body=resp.text, - ) + content_type = resp.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type == "application/json": + raise APIError.from_response( + "Response when given params (or one of them) are invalid", + resp, + body_type=CreateReaderCheckoutError, + ) + elif content_type == "application/problem+json": + raise APIError.from_response( + "Response when given params (or one of them) are invalid", + resp, + body_type=Problem, + ) + else: + raise APIError.from_response( + "Response when given params (or one of them) are invalid", resp + ) elif resp.status_code == 401: - raise APIError("Unauthorized", status=resp.status_code, body=resp.text) + content_type = resp.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type == "application/json": + raise APIError.from_response( + "Unauthorized", resp, body_type=CreateReaderCheckoutError + ) + elif content_type == "application/problem+json": + raise APIError.from_response("Unauthorized", resp, body_type=Problem) + else: + raise APIError.from_response("Unauthorized", resp) elif resp.status_code == 404: - raise APIError( - "Response when given reader is not found", status=resp.status_code, body=resp.text - ) + content_type = resp.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type == "application/json": + raise APIError.from_response( + "Response when given reader is not found", resp, body_type=NotFound + ) + elif content_type == "application/problem+json": + raise APIError.from_response( + "Response when given reader is not found", resp, body_type=Problem + ) + else: + raise APIError.from_response("Response when given reader is not found", resp) elif resp.status_code == 422: - raise APIError( - "Response when given params (or one of them) are invalid", - status=resp.status_code, - body=resp.text, - ) + content_type = resp.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type == "application/json": + raise APIError.from_response( + "Response when given params (or one of them) are invalid", + resp, + body_type=CreateReaderCheckoutUnprocessableEntity, + ) + elif content_type == "application/problem+json": + raise APIError.from_response( + "Response when given params (or one of them) are invalid", + resp, + body_type=Problem, + ) + else: + raise APIError.from_response( + "Response when given params (or one of them) are invalid", resp + ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) async def get_status( self, merchant_code: str, reader_id: str, headers: HeaderTypes | None = None @@ -1387,36 +1648,67 @@ async def get_status( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: Response when given params (or one of them) are invalid - 401: Response when given merchant's token is invalid - 404: Response when given reader is not found + 400: Response when given params (or one of them) are invalid (raises BadRequestError) + 401: Response when given merchant's token is invalid (raises AuthenticationError) + 404: Response when given reader is not found (raises NotFoundError) Unexpected response statuses also raise this exception. """ - resp = await self._client.get( - f"/v0.1/merchants/{merchant_code}/readers/{reader_id}/status", - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.get( + f"/v0.1/merchants/{merchant_code}/readers/{reader_id}/status", + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(StatusResponse).validate_python(resp.json()) elif resp.status_code == 400: - raise APIError( - "Response when given params (or one of them) are invalid", - status=resp.status_code, - body=resp.text, - ) + content_type = resp.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type == "application/json": + raise APIError.from_response( + "Response when given params (or one of them) are invalid", + resp, + body_type=BadRequest, + ) + elif content_type == "application/problem+json": + raise APIError.from_response( + "Response when given params (or one of them) are invalid", + resp, + body_type=Problem, + ) + else: + raise APIError.from_response( + "Response when given params (or one of them) are invalid", resp + ) elif resp.status_code == 401: - raise APIError( - "Response when given merchant's token is invalid", - status=resp.status_code, - body=resp.text, - ) + content_type = resp.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type == "application/json": + raise APIError.from_response( + "Response when given merchant's token is invalid", resp, body_type=Unauthorized + ) + elif content_type == "application/problem+json": + raise APIError.from_response( + "Response when given merchant's token is invalid", resp, body_type=Problem + ) + else: + raise APIError.from_response( + "Response when given merchant's token is invalid", resp + ) elif resp.status_code == 404: - raise APIError( - "Response when given reader is not found", status=resp.status_code, body=resp.text - ) + content_type = resp.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type == "application/json": + raise APIError.from_response( + "Response when given reader is not found", resp, body_type=NotFound + ) + elif content_type == "application/problem+json": + raise APIError.from_response( + "Response when given reader is not found", resp, body_type=Problem + ) + else: + raise APIError.from_response("Response when given reader is not found", resp) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) async def get_reader_settings( self, merchant_code: str, reader_id: str, headers: HeaderTypes | None = None @@ -1435,34 +1727,70 @@ async def get_reader_settings( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 401: Unauthorized - 404: The reader was not found, or it is offline and has no saved settings. - 422: The reader model is not supported, or the reader could not return its settings. + 401: Unauthorized (raises AuthenticationError) + 404: The reader was not found, or it is offline and has no saved settings. (raises NotFoundError) + 422: The reader model is not supported, or the reader could not return its settings. (raises UnprocessableEntityError) Unexpected response statuses also raise this exception. """ - resp = await self._client.get( - f"/v0.1/merchants/{merchant_code}/readers/{reader_id}/settings", - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.get( + f"/v0.1/merchants/{merchant_code}/readers/{reader_id}/settings", + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(GetReaderSettingsResponse).validate_python(resp.json()) elif resp.status_code == 401: - raise APIError("Unauthorized", status=resp.status_code, body=resp.text) + content_type = resp.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type == "application/json": + raise APIError.from_response( + "Unauthorized", resp, body_type=UpdateReaderSettingsError + ) + elif content_type == "application/problem+json": + raise APIError.from_response("Unauthorized", resp, body_type=Problem) + else: + raise APIError.from_response("Unauthorized", resp) elif resp.status_code == 404: - raise APIError( - "The reader was not found, or it is offline and has no saved settings.", - status=resp.status_code, - body=resp.text, - ) + content_type = resp.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type == "application/json": + raise APIError.from_response( + "The reader was not found, or it is offline and has no saved settings.", + resp, + body_type=NotFound, + ) + elif content_type == "application/problem+json": + raise APIError.from_response( + "The reader was not found, or it is offline and has no saved settings.", + resp, + body_type=Problem, + ) + else: + raise APIError.from_response( + "The reader was not found, or it is offline and has no saved settings.", resp + ) elif resp.status_code == 422: - raise APIError( - "The reader model is not supported, or the reader could not return its settings.", - status=resp.status_code, - body=resp.text, - ) + content_type = resp.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type == "application/json": + raise APIError.from_response( + "The reader model is not supported, or the reader could not return its settings.", + resp, + body_type=UpdateReaderSettingsUnprocessableEntity, + ) + elif content_type == "application/problem+json": + raise APIError.from_response( + "The reader model is not supported, or the reader could not return its settings.", + resp, + body_type=Problem, + ) + else: + raise APIError.from_response( + "The reader model is not supported, or the reader could not return its settings.", + resp, + ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) async def update_reader_settings( self, @@ -1488,39 +1816,77 @@ async def update_reader_settings( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: The request body is malformed. - 401: Unauthorized - 404: The reader was not found. - 422: The settings are invalid, the reader is offline, the reader model is not supported, or the readercould not apply the update. + 400: The request body is malformed. (raises BadRequestError) + 401: Unauthorized (raises AuthenticationError) + 404: The reader was not found. (raises NotFoundError) + 422: The settings are invalid, the reader is offline, the reader model is not supported, or the readercould not apply the update. (raises UnprocessableEntityError) Unexpected response statuses also raise this exception. """ body_data: dict[str, typing.Any] = {} body_data["menu_lock"] = menu_lock - resp = await self._client.patch( - f"/v0.1/merchants/{merchant_code}/readers/{reader_id}/settings", - json=serialize_request_data(body_data), - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.patch( + f"/v0.1/merchants/{merchant_code}/readers/{reader_id}/settings", + json=serialize_request_data(body_data), + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(UpdateReaderSettingsResponse).validate_python(resp.json()) elif resp.status_code == 400: - raise APIError( - "The request body is malformed.", status=resp.status_code, body=resp.text - ) + content_type = resp.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type == "application/json": + raise APIError.from_response( + "The request body is malformed.", resp, body_type=UpdateReaderSettingsError + ) + elif content_type == "application/problem+json": + raise APIError.from_response( + "The request body is malformed.", resp, body_type=Problem + ) + else: + raise APIError.from_response("The request body is malformed.", resp) elif resp.status_code == 401: - raise APIError("Unauthorized", status=resp.status_code, body=resp.text) + content_type = resp.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type == "application/json": + raise APIError.from_response( + "Unauthorized", resp, body_type=UpdateReaderSettingsError + ) + elif content_type == "application/problem+json": + raise APIError.from_response("Unauthorized", resp, body_type=Problem) + else: + raise APIError.from_response("Unauthorized", resp) elif resp.status_code == 404: - raise APIError("The reader was not found.", status=resp.status_code, body=resp.text) + content_type = resp.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type == "application/json": + raise APIError.from_response("The reader was not found.", resp, body_type=NotFound) + elif content_type == "application/problem+json": + raise APIError.from_response("The reader was not found.", resp, body_type=Problem) + else: + raise APIError.from_response("The reader was not found.", resp) elif resp.status_code == 422: - raise APIError( - "The settings are invalid, the reader is offline, the reader model is not supported, or the reader could not apply the update.", - status=resp.status_code, - body=resp.text, - ) + content_type = resp.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type == "application/json": + raise APIError.from_response( + "The settings are invalid, the reader is offline, the reader model is not supported, or the reader could not apply the update.", + resp, + body_type=UpdateReaderSettingsUnprocessableEntity, + ) + elif content_type == "application/problem+json": + raise APIError.from_response( + "The settings are invalid, the reader is offline, the reader model is not supported, or the reader could not apply the update.", + resp, + body_type=Problem, + ) + else: + raise APIError.from_response( + "The settings are invalid, the reader is offline, the reader model is not supported, or the reader could not apply the update.", + resp, + ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) async def terminate_checkout( self, merchant_code: str, reader_id: str, headers: HeaderTypes | None = None @@ -1546,39 +1912,82 @@ async def terminate_checkout( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: Response when given params (or one of them) are invalid - 401: Unauthorized - 404: Response when given reader is not found - 422: Response when given params (or one of them) are invalid + 400: Response when given params (or one of them) are invalid (raises BadRequestError) + 401: Unauthorized (raises AuthenticationError) + 404: Response when given reader is not found (raises NotFoundError) + 422: Response when given params (or one of them) are invalid (raises UnprocessableEntityError) Unexpected response statuses also raise this exception. """ - resp = await self._client.post( - f"/v0.1/merchants/{merchant_code}/readers/{reader_id}/terminate", - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.post( + f"/v0.1/merchants/{merchant_code}/readers/{reader_id}/terminate", + headers=headers, + ) if resp.status_code == 202: return elif resp.status_code == 400: - raise APIError( - "Response when given params (or one of them) are invalid", - status=resp.status_code, - body=resp.text, - ) + content_type = resp.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type == "application/json": + raise APIError.from_response( + "Response when given params (or one of them) are invalid", + resp, + body_type=CreateReaderTerminateError, + ) + elif content_type == "application/problem+json": + raise APIError.from_response( + "Response when given params (or one of them) are invalid", + resp, + body_type=Problem, + ) + else: + raise APIError.from_response( + "Response when given params (or one of them) are invalid", resp + ) elif resp.status_code == 401: - raise APIError("Unauthorized", status=resp.status_code, body=resp.text) + content_type = resp.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type == "application/json": + raise APIError.from_response( + "Unauthorized", resp, body_type=CreateReaderTerminateError + ) + elif content_type == "application/problem+json": + raise APIError.from_response("Unauthorized", resp, body_type=Problem) + else: + raise APIError.from_response("Unauthorized", resp) elif resp.status_code == 404: - raise APIError( - "Response when given reader is not found", status=resp.status_code, body=resp.text - ) + content_type = resp.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type == "application/json": + raise APIError.from_response( + "Response when given reader is not found", resp, body_type=NotFound + ) + elif content_type == "application/problem+json": + raise APIError.from_response( + "Response when given reader is not found", resp, body_type=Problem + ) + else: + raise APIError.from_response("Response when given reader is not found", resp) elif resp.status_code == 422: - raise APIError( - "Response when given params (or one of them) are invalid", - status=resp.status_code, - body=resp.text, - ) + content_type = resp.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type == "application/json": + raise APIError.from_response( + "Response when given params (or one of them) are invalid", + resp, + body_type=CreateReaderTerminateUnprocessableEntity, + ) + elif content_type == "application/problem+json": + raise APIError.from_response( + "Response when given params (or one of them) are invalid", + resp, + body_type=Problem, + ) + else: + raise APIError.from_response( + "Response when given params (or one of them) are invalid", resp + ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) async def get_checkout( self, @@ -1595,24 +2004,43 @@ async def get_checkout( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 401: Unauthorized - 404: Response when given reader or checkout is not found + 401: Unauthorized (raises AuthenticationError) + 404: Response when given reader or checkout is not found (raises NotFoundError) Unexpected response statuses also raise this exception. """ - resp = await self._client.get( - f"/v0.1/merchants/{merchant_code}/readers/{reader_id}/checkout/{checkout_id}", - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.get( + f"/v0.1/merchants/{merchant_code}/readers/{reader_id}/checkout/{checkout_id}", + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(GetReaderCheckoutResponse).validate_python(resp.json()) elif resp.status_code == 401: - raise APIError("Unauthorized", status=resp.status_code, body=resp.text) + content_type = resp.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type == "application/json": + raise APIError.from_response( + "Unauthorized", resp, body_type=CreateReaderCheckoutError + ) + elif content_type == "application/problem+json": + raise APIError.from_response("Unauthorized", resp, body_type=Problem) + else: + raise APIError.from_response("Unauthorized", resp) elif resp.status_code == 404: - raise APIError( - "Response when given reader or checkout is not found", - status=resp.status_code, - body=resp.text, - ) + content_type = resp.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type == "application/json": + raise APIError.from_response( + "Response when given reader or checkout is not found", resp, body_type=NotFound + ) + elif content_type == "application/problem+json": + raise APIError.from_response( + "Response when given reader or checkout is not found", resp, body_type=Problem + ) + else: + raise APIError.from_response( + "Response when given reader or checkout is not found", resp + ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) diff --git a/sumup/receipts/resource.py b/sumup/receipts/resource.py index c3ad4248..f2bbeef6 100644 --- a/sumup/receipts/resource.py +++ b/sumup/receipts/resource.py @@ -1,5 +1,5 @@ # Code generated by `py-sdk-gen`. DO NOT EDIT. -# ruff: noqa: F401, F541 +# ruff: noqa: F401 """ Retrieve structured receipt data for a transaction, including payment, merchant, and acquirer details. Use this data to display a receipt in your application. The response is JSON, rather than a rendered receipt document. """ @@ -13,7 +13,7 @@ import pydantic import typing_extensions -from .._exceptions import APIError +from .._exceptions import APIError, _wrap_request_errors from .._service import ( NOT_GIVEN, AsyncResource, @@ -60,10 +60,12 @@ def get( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: The request is invalid for the submitted parameters. - 401: The request is not authorized. - 404: The requested transaction event does not exist for the provided transaction. + 400: The request is invalid for the submitted parameters. (raises BadRequestError) + 401: The request is not authorized. (raises AuthenticationError) + 404: The requested transaction event does not exist for the provided transaction. (raises NotFoundError) Unexpected response statuses also raise this exception. """ query_data: dict[str, typing.Any] = {} @@ -71,31 +73,28 @@ def get( if not isinstance(tx_event_id, NotGivenType) and tx_event_id is not None: query_data["tx_event_id"] = tx_event_id - resp = self._client.get( - f"/v1.1/receipts/{transaction_id}", - params=serialize_query_params(query_data) if query_data else None, - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.get( + f"/v1.1/receipts/{transaction_id}", + params=serialize_query_params(query_data) if query_data else None, + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(Receipt).validate_python(resp.json()) elif resp.status_code == 400: - raise APIError( - "The request is invalid for the submitted parameters.", - status=resp.status_code, - body=resp.text, + raise APIError.from_response( + "The request is invalid for the submitted parameters.", resp, body_type=Error ) elif resp.status_code == 401: - raise APIError( - "The request is not authorized.", status=resp.status_code, body=resp.text - ) + raise APIError.from_response("The request is not authorized.", resp, body_type=Problem) elif resp.status_code == 404: - raise APIError( + raise APIError.from_response( "The requested transaction event does not exist for the provided transaction.", - status=resp.status_code, - body=resp.text, + resp, + body_type=Error, ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) class AsyncReceiptsResource(AsyncResource): @@ -119,10 +118,12 @@ async def get( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: The request is invalid for the submitted parameters. - 401: The request is not authorized. - 404: The requested transaction event does not exist for the provided transaction. + 400: The request is invalid for the submitted parameters. (raises BadRequestError) + 401: The request is not authorized. (raises AuthenticationError) + 404: The requested transaction event does not exist for the provided transaction. (raises NotFoundError) Unexpected response statuses also raise this exception. """ query_data: dict[str, typing.Any] = {} @@ -130,28 +131,25 @@ async def get( if not isinstance(tx_event_id, NotGivenType) and tx_event_id is not None: query_data["tx_event_id"] = tx_event_id - resp = await self._client.get( - f"/v1.1/receipts/{transaction_id}", - params=serialize_query_params(query_data) if query_data else None, - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.get( + f"/v1.1/receipts/{transaction_id}", + params=serialize_query_params(query_data) if query_data else None, + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(Receipt).validate_python(resp.json()) elif resp.status_code == 400: - raise APIError( - "The request is invalid for the submitted parameters.", - status=resp.status_code, - body=resp.text, + raise APIError.from_response( + "The request is invalid for the submitted parameters.", resp, body_type=Error ) elif resp.status_code == 401: - raise APIError( - "The request is not authorized.", status=resp.status_code, body=resp.text - ) + raise APIError.from_response("The request is not authorized.", resp, body_type=Problem) elif resp.status_code == 404: - raise APIError( + raise APIError.from_response( "The requested transaction event does not exist for the provided transaction.", - status=resp.status_code, - body=resp.text, + resp, + body_type=Error, ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) diff --git a/sumup/roles/resource.py b/sumup/roles/resource.py index fac7086c..59ed5b62 100644 --- a/sumup/roles/resource.py +++ b/sumup/roles/resource.py @@ -1,5 +1,5 @@ # Code generated by `py-sdk-gen`. DO NOT EDIT. -# ruff: noqa: F401, F541 +# ruff: noqa: F401 """ Endpoints to manage custom roles. Custom roles allow you to tailor roles from individual permissions to match your needs. Once created, you can assign your custom roles to your merchant account members using the memberships. """ @@ -13,7 +13,7 @@ import pydantic import typing_extensions -from .._exceptions import APIError +from .._exceptions import APIError, _wrap_request_errors from .._service import ( NOT_GIVEN, AsyncResource, @@ -100,20 +100,23 @@ def list( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 404: Merchant not found. + 404: Merchant not found. (raises NotFoundError) Unexpected response statuses also raise this exception. """ - resp = self._client.get( - f"/v0.1/merchants/{merchant_code}/roles", - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.get( + f"/v0.1/merchants/{merchant_code}/roles", + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(ListMerchantRoles200Response).validate_python(resp.json()) elif resp.status_code == 404: - raise APIError("Merchant not found.", status=resp.status_code, body=resp.text) + raise APIError.from_response("Merchant not found.", resp, body_type=Problem) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) def create( self, @@ -132,9 +135,11 @@ def create( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: Invalid request. - 404: Merchant not found. + 400: Invalid request. (raises BadRequestError) + 404: Merchant not found. (raises NotFoundError) Unexpected response statuses also raise this exception. """ body_data: dict[str, typing.Any] = {} @@ -145,19 +150,20 @@ def create( if not isinstance(description, NotGivenType): body_data["description"] = description - resp = self._client.post( - f"/v0.1/merchants/{merchant_code}/roles", - json=serialize_request_data(body_data), - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.post( + f"/v0.1/merchants/{merchant_code}/roles", + json=serialize_request_data(body_data), + headers=headers, + ) if resp.status_code == 201: return pydantic.TypeAdapter(Role).validate_python(resp.json()) elif resp.status_code == 400: - raise APIError("Invalid request.", status=resp.status_code, body=resp.text) + raise APIError.from_response("Invalid request.", resp, body_type=Problem) elif resp.status_code == 404: - raise APIError("Merchant not found.", status=resp.status_code, body=resp.text) + raise APIError.from_response("Merchant not found.", resp, body_type=Problem) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) def get(self, merchant_code: str, role_id: str, headers: HeaderTypes | None = None) -> Role: """ @@ -167,20 +173,23 @@ def get(self, merchant_code: str, role_id: str, headers: HeaderTypes | None = No Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 404: Merchant or role not found. + 404: Merchant or role not found. (raises NotFoundError) Unexpected response statuses also raise this exception. """ - resp = self._client.get( - f"/v0.1/merchants/{merchant_code}/roles/{role_id}", - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.get( + f"/v0.1/merchants/{merchant_code}/roles/{role_id}", + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(Role).validate_python(resp.json()) elif resp.status_code == 404: - raise APIError("Merchant or role not found.", status=resp.status_code, body=resp.text) + raise APIError.from_response("Merchant or role not found.", resp, body_type=Problem) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) def delete(self, merchant_code: str, role_id: str, headers: HeaderTypes | None = None): """ @@ -190,23 +199,26 @@ def delete(self, merchant_code: str, role_id: str, headers: HeaderTypes | None = Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: Invalid request. - 404: Merchant not found. + 400: Invalid request. (raises BadRequestError) + 404: Merchant not found. (raises NotFoundError) Unexpected response statuses also raise this exception. """ - resp = self._client.delete( - f"/v0.1/merchants/{merchant_code}/roles/{role_id}", - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.delete( + f"/v0.1/merchants/{merchant_code}/roles/{role_id}", + headers=headers, + ) if resp.status_code == 200: return elif resp.status_code == 400: - raise APIError("Invalid request.", status=resp.status_code, body=resp.text) + raise APIError.from_response("Invalid request.", resp, body_type=Problem) elif resp.status_code == 404: - raise APIError("Merchant not found.", status=resp.status_code, body=resp.text) + raise APIError.from_response("Merchant not found.", resp, body_type=Problem) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) def update( self, @@ -227,9 +239,11 @@ def update( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: Invalid request. - 404: Merchant not found. + 400: Invalid request. (raises BadRequestError) + 404: Merchant not found. (raises NotFoundError) Unexpected response statuses also raise this exception. """ body_data: dict[str, typing.Any] = {} @@ -240,19 +254,20 @@ def update( if not isinstance(description, NotGivenType): body_data["description"] = description - resp = self._client.patch( - f"/v0.1/merchants/{merchant_code}/roles/{role_id}", - json=serialize_request_data(body_data), - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.patch( + f"/v0.1/merchants/{merchant_code}/roles/{role_id}", + json=serialize_request_data(body_data), + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(Role).validate_python(resp.json()) elif resp.status_code == 400: - raise APIError("Invalid request.", status=resp.status_code, body=resp.text) + raise APIError.from_response("Invalid request.", resp, body_type=Problem) elif resp.status_code == 404: - raise APIError("Merchant not found.", status=resp.status_code, body=resp.text) + raise APIError.from_response("Merchant not found.", resp, body_type=Problem) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) class AsyncRolesResource(AsyncResource): @@ -271,20 +286,23 @@ async def list( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 404: Merchant not found. + 404: Merchant not found. (raises NotFoundError) Unexpected response statuses also raise this exception. """ - resp = await self._client.get( - f"/v0.1/merchants/{merchant_code}/roles", - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.get( + f"/v0.1/merchants/{merchant_code}/roles", + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(ListMerchantRoles200Response).validate_python(resp.json()) elif resp.status_code == 404: - raise APIError("Merchant not found.", status=resp.status_code, body=resp.text) + raise APIError.from_response("Merchant not found.", resp, body_type=Problem) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) async def create( self, @@ -303,9 +321,11 @@ async def create( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: Invalid request. - 404: Merchant not found. + 400: Invalid request. (raises BadRequestError) + 404: Merchant not found. (raises NotFoundError) Unexpected response statuses also raise this exception. """ body_data: dict[str, typing.Any] = {} @@ -316,19 +336,20 @@ async def create( if not isinstance(description, NotGivenType): body_data["description"] = description - resp = await self._client.post( - f"/v0.1/merchants/{merchant_code}/roles", - json=serialize_request_data(body_data), - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.post( + f"/v0.1/merchants/{merchant_code}/roles", + json=serialize_request_data(body_data), + headers=headers, + ) if resp.status_code == 201: return pydantic.TypeAdapter(Role).validate_python(resp.json()) elif resp.status_code == 400: - raise APIError("Invalid request.", status=resp.status_code, body=resp.text) + raise APIError.from_response("Invalid request.", resp, body_type=Problem) elif resp.status_code == 404: - raise APIError("Merchant not found.", status=resp.status_code, body=resp.text) + raise APIError.from_response("Merchant not found.", resp, body_type=Problem) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) async def get( self, merchant_code: str, role_id: str, headers: HeaderTypes | None = None @@ -340,20 +361,23 @@ async def get( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 404: Merchant or role not found. + 404: Merchant or role not found. (raises NotFoundError) Unexpected response statuses also raise this exception. """ - resp = await self._client.get( - f"/v0.1/merchants/{merchant_code}/roles/{role_id}", - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.get( + f"/v0.1/merchants/{merchant_code}/roles/{role_id}", + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(Role).validate_python(resp.json()) elif resp.status_code == 404: - raise APIError("Merchant or role not found.", status=resp.status_code, body=resp.text) + raise APIError.from_response("Merchant or role not found.", resp, body_type=Problem) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) async def delete(self, merchant_code: str, role_id: str, headers: HeaderTypes | None = None): """ @@ -363,23 +387,26 @@ async def delete(self, merchant_code: str, role_id: str, headers: HeaderTypes | Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: Invalid request. - 404: Merchant not found. + 400: Invalid request. (raises BadRequestError) + 404: Merchant not found. (raises NotFoundError) Unexpected response statuses also raise this exception. """ - resp = await self._client.delete( - f"/v0.1/merchants/{merchant_code}/roles/{role_id}", - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.delete( + f"/v0.1/merchants/{merchant_code}/roles/{role_id}", + headers=headers, + ) if resp.status_code == 200: return elif resp.status_code == 400: - raise APIError("Invalid request.", status=resp.status_code, body=resp.text) + raise APIError.from_response("Invalid request.", resp, body_type=Problem) elif resp.status_code == 404: - raise APIError("Merchant not found.", status=resp.status_code, body=resp.text) + raise APIError.from_response("Merchant not found.", resp, body_type=Problem) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) async def update( self, @@ -400,9 +427,11 @@ async def update( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: Invalid request. - 404: Merchant not found. + 400: Invalid request. (raises BadRequestError) + 404: Merchant not found. (raises NotFoundError) Unexpected response statuses also raise this exception. """ body_data: dict[str, typing.Any] = {} @@ -413,16 +442,17 @@ async def update( if not isinstance(description, NotGivenType): body_data["description"] = description - resp = await self._client.patch( - f"/v0.1/merchants/{merchant_code}/roles/{role_id}", - json=serialize_request_data(body_data), - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.patch( + f"/v0.1/merchants/{merchant_code}/roles/{role_id}", + json=serialize_request_data(body_data), + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(Role).validate_python(resp.json()) elif resp.status_code == 400: - raise APIError("Invalid request.", status=resp.status_code, body=resp.text) + raise APIError.from_response("Invalid request.", resp, body_type=Problem) elif resp.status_code == 404: - raise APIError("Merchant not found.", status=resp.status_code, body=resp.text) + raise APIError.from_response("Merchant not found.", resp, body_type=Problem) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) diff --git a/sumup/tokens/resource.py b/sumup/tokens/resource.py index bad4bbf4..a33101ee 100644 --- a/sumup/tokens/resource.py +++ b/sumup/tokens/resource.py @@ -1,5 +1,5 @@ # Code generated by `py-sdk-gen`. DO NOT EDIT. -# ruff: noqa: F401, F541 +# ruff: noqa: F401 """ Merchant tokens let your application accept card-present payments with SumUp SDKs that support token-based authentication. Use them when you want users to sign in to your application with your own authentication, then accept payments for a SumUp merchant account. @@ -19,7 +19,7 @@ import pydantic import typing_extensions -from .._exceptions import APIError +from .._exceptions import APIError, _wrap_request_errors from .._service import ( NOT_GIVEN, AsyncResource, @@ -73,42 +73,49 @@ def create( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: The request body is invalid or contains unsupported or duplicate actions. - 401: Authentication is missing, invalid, or expired. - 403: The authenticated identity does not have permission to create tokens for this merchant account. + 400: The request body is invalid or contains unsupported or duplicate actions. (raises BadRequestError) + 401: Authentication is missing, invalid, or expired. (raises AuthenticationError) + 403: The authenticated identity does not have permission to create tokens for this merchant account. (raisesPermissionDeniedError) Unexpected response statuses also raise this exception. """ body_data: dict[str, typing.Any] = {} body_data["actions"] = list(actions) - resp = self._client.post( - f"/v0.1/merchants/{merchant_code}/tokens", - json=serialize_request_data(body_data), - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.post( + f"/v0.1/merchants/{merchant_code}/tokens", + json=serialize_request_data(body_data), + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(Token).validate_python(resp.json()) elif resp.status_code == 400: - raise APIError( + raise APIError.from_response( "The request body is invalid or contains unsupported or duplicate actions.", - status=resp.status_code, - body=resp.text, + resp, + body_type=Problem, ) elif resp.status_code == 401: - raise APIError( - "Authentication is missing, invalid, or expired.", - status=resp.status_code, - body=resp.text, - ) + content_type = resp.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type == "application/json" or content_type == "application/problem+json": + raise APIError.from_response( + "Authentication is missing, invalid, or expired.", resp, body_type=Problem + ) + else: + raise APIError.from_response( + "Authentication is missing, invalid, or expired.", resp + ) elif resp.status_code == 403: - raise APIError( + raise APIError.from_response( "The authenticated identity does not have permission to create tokens for this merchant account.", - status=resp.status_code, - body=resp.text, + resp, + body_type=Problem, ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) class AsyncTokensResource(AsyncResource): @@ -135,39 +142,46 @@ async def create( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: The request body is invalid or contains unsupported or duplicate actions. - 401: Authentication is missing, invalid, or expired. - 403: The authenticated identity does not have permission to create tokens for this merchant account. + 400: The request body is invalid or contains unsupported or duplicate actions. (raises BadRequestError) + 401: Authentication is missing, invalid, or expired. (raises AuthenticationError) + 403: The authenticated identity does not have permission to create tokens for this merchant account. (raisesPermissionDeniedError) Unexpected response statuses also raise this exception. """ body_data: dict[str, typing.Any] = {} body_data["actions"] = list(actions) - resp = await self._client.post( - f"/v0.1/merchants/{merchant_code}/tokens", - json=serialize_request_data(body_data), - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.post( + f"/v0.1/merchants/{merchant_code}/tokens", + json=serialize_request_data(body_data), + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(Token).validate_python(resp.json()) elif resp.status_code == 400: - raise APIError( + raise APIError.from_response( "The request body is invalid or contains unsupported or duplicate actions.", - status=resp.status_code, - body=resp.text, + resp, + body_type=Problem, ) elif resp.status_code == 401: - raise APIError( - "Authentication is missing, invalid, or expired.", - status=resp.status_code, - body=resp.text, - ) + content_type = resp.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type == "application/json" or content_type == "application/problem+json": + raise APIError.from_response( + "Authentication is missing, invalid, or expired.", resp, body_type=Problem + ) + else: + raise APIError.from_response( + "Authentication is missing, invalid, or expired.", resp + ) elif resp.status_code == 403: - raise APIError( + raise APIError.from_response( "The authenticated identity does not have permission to create tokens for this merchant account.", - status=resp.status_code, - body=resp.text, + resp, + body_type=Problem, ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) diff --git a/sumup/transactions/__init__.py b/sumup/transactions/__init__.py index b5197a21..992f6989 100644 --- a/sumup/transactions/__init__.py +++ b/sumup/transactions/__init__.py @@ -31,6 +31,7 @@ from .resource import ( AsyncTransactionsResource, ListTransactionsV21200Response, + RefundTransaction201Response, TransactionsResource, ) @@ -52,6 +53,7 @@ "PaymentType", "Problem", "Product", + "RefundTransaction201Response", "TransactionBase", "TransactionCheckoutInfo", "TransactionEvent", diff --git a/sumup/transactions/resource.py b/sumup/transactions/resource.py index 06aef6d2..2d53f88d 100644 --- a/sumup/transactions/resource.py +++ b/sumup/transactions/resource.py @@ -1,5 +1,5 @@ # Code generated by `py-sdk-gen`. DO NOT EDIT. -# ruff: noqa: F401, F541 +# ruff: noqa: F401 """ Transactions represent completed or attempted payment operations processed for a merchant account. A transaction contains the core payment result, such as the amount, currency, payment method, creation time, and current high-level status. @@ -30,7 +30,7 @@ import pydantic import typing_extensions -from .._exceptions import APIError +from .._exceptions import APIError, _wrap_request_errors from .._service import ( NOT_GIVEN, AsyncResource, @@ -141,55 +141,56 @@ def refund( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: The refund request is invalid. - 403: The request is authenticated but not permitted for this operation. - 404: The requested transaction does not exist or does not belong to the merchant. - 409: The transaction cannot be refunded due to business constraints. - 422: The refund could not be processed by the payment processor. + 400: The refund request is invalid. (raises BadRequestError) + 403: The request is authenticated but not permitted for this operation. (raises PermissionDeniedError) + 404: The requested transaction does not exist or does not belong to the merchant. (raises NotFoundError) + 409: The transaction cannot be refunded due to business constraints. (raises ConflictError) + 422: The refund could not be processed by the payment processor. (raises UnprocessableEntityError) Unexpected response statuses also raise this exception. """ body_data: dict[str, typing.Any] = {} if not isinstance(amount, NotGivenType): body_data["amount"] = amount - resp = self._client.post( - f"/v1.0/merchants/{merchant_code}/payments/{transaction_id}/refunds", - json=serialize_request_data(body_data), - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.post( + f"/v1.0/merchants/{merchant_code}/payments/{transaction_id}/refunds", + json=serialize_request_data(body_data), + headers=headers, + ) if resp.status_code == 201: return pydantic.TypeAdapter(RefundTransaction201Response).validate_python(resp.json()) elif resp.status_code == 400: - raise APIError( - "The refund request is invalid.", status=resp.status_code, body=resp.text - ) + raise APIError.from_response("The refund request is invalid.", resp, body_type=Problem) elif resp.status_code == 403: - raise APIError( + raise APIError.from_response( "The request is authenticated but not permitted for this operation.", - status=resp.status_code, - body=resp.text, + resp, + body_type=Problem, ) elif resp.status_code == 404: - raise APIError( + raise APIError.from_response( "The requested transaction does not exist or does not belong to the merchant.", - status=resp.status_code, - body=resp.text, + resp, + body_type=Problem, ) elif resp.status_code == 409: - raise APIError( + raise APIError.from_response( "The transaction cannot be refunded due to business constraints.", - status=resp.status_code, - body=resp.text, + resp, + body_type=Problem, ) elif resp.status_code == 422: - raise APIError( + raise APIError.from_response( "The refund could not be processed by the payment processor.", - status=resp.status_code, - body=resp.text, + resp, + body_type=Problem, ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) def get( self, @@ -212,9 +213,11 @@ def get( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 401: The request is not authorized. - 404: The requested resource does not exist. + 401: The request is not authorized. (raises AuthenticationError) + 404: The requested resource does not exist. (raises NotFoundError) Unexpected response statuses also raise this exception. """ query_data: dict[str, typing.Any] = {} @@ -233,23 +236,22 @@ def get( ): query_data["client_transaction_id"] = client_transaction_id - resp = self._client.get( - f"/v2.1/merchants/{merchant_code}/transactions", - params=serialize_query_params(query_data) if query_data else None, - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.get( + f"/v2.1/merchants/{merchant_code}/transactions", + params=serialize_query_params(query_data) if query_data else None, + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(TransactionFull).validate_python(resp.json()) elif resp.status_code == 401: - raise APIError( - "The request is not authorized.", status=resp.status_code, body=resp.text - ) + raise APIError.from_response("The request is not authorized.", resp, body_type=Problem) elif resp.status_code == 404: - raise APIError( - "The requested resource does not exist.", status=resp.status_code, body=resp.text + raise APIError.from_response( + "The requested resource does not exist.", resp, body_type=Error ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) def list( self, @@ -279,9 +281,11 @@ def list( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: The request is invalid for the submitted query parameters. - 401: The request is not authorized. + 400: The request is invalid for the submitted query parameters. (raises BadRequestError) + 401: The request is not authorized. (raises AuthenticationError) Unexpected response statuses also raise this exception. """ query_data: dict[str, typing.Any] = {} @@ -312,25 +316,22 @@ def list( if not isinstance(oldest_ref, NotGivenType) and oldest_ref is not None: query_data["oldest_ref"] = oldest_ref - resp = self._client.get( - f"/v2.1/merchants/{merchant_code}/transactions/history", - params=serialize_query_params(query_data) if query_data else None, - headers=headers, - ) + with _wrap_request_errors(): + resp = self._client.get( + f"/v2.1/merchants/{merchant_code}/transactions/history", + params=serialize_query_params(query_data) if query_data else None, + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(ListTransactionsV21200Response).validate_python(resp.json()) elif resp.status_code == 400: - raise APIError( - "The request is invalid for the submitted query parameters.", - status=resp.status_code, - body=resp.text, + raise APIError.from_response( + "The request is invalid for the submitted query parameters.", resp, body_type=Error ) elif resp.status_code == 401: - raise APIError( - "The request is not authorized.", status=resp.status_code, body=resp.text - ) + raise APIError.from_response("The request is not authorized.", resp, body_type=Problem) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) class AsyncTransactionsResource(AsyncResource): @@ -356,55 +357,56 @@ async def refund( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: The refund request is invalid. - 403: The request is authenticated but not permitted for this operation. - 404: The requested transaction does not exist or does not belong to the merchant. - 409: The transaction cannot be refunded due to business constraints. - 422: The refund could not be processed by the payment processor. + 400: The refund request is invalid. (raises BadRequestError) + 403: The request is authenticated but not permitted for this operation. (raises PermissionDeniedError) + 404: The requested transaction does not exist or does not belong to the merchant. (raises NotFoundError) + 409: The transaction cannot be refunded due to business constraints. (raises ConflictError) + 422: The refund could not be processed by the payment processor. (raises UnprocessableEntityError) Unexpected response statuses also raise this exception. """ body_data: dict[str, typing.Any] = {} if not isinstance(amount, NotGivenType): body_data["amount"] = amount - resp = await self._client.post( - f"/v1.0/merchants/{merchant_code}/payments/{transaction_id}/refunds", - json=serialize_request_data(body_data), - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.post( + f"/v1.0/merchants/{merchant_code}/payments/{transaction_id}/refunds", + json=serialize_request_data(body_data), + headers=headers, + ) if resp.status_code == 201: return pydantic.TypeAdapter(RefundTransaction201Response).validate_python(resp.json()) elif resp.status_code == 400: - raise APIError( - "The refund request is invalid.", status=resp.status_code, body=resp.text - ) + raise APIError.from_response("The refund request is invalid.", resp, body_type=Problem) elif resp.status_code == 403: - raise APIError( + raise APIError.from_response( "The request is authenticated but not permitted for this operation.", - status=resp.status_code, - body=resp.text, + resp, + body_type=Problem, ) elif resp.status_code == 404: - raise APIError( + raise APIError.from_response( "The requested transaction does not exist or does not belong to the merchant.", - status=resp.status_code, - body=resp.text, + resp, + body_type=Problem, ) elif resp.status_code == 409: - raise APIError( + raise APIError.from_response( "The transaction cannot be refunded due to business constraints.", - status=resp.status_code, - body=resp.text, + resp, + body_type=Problem, ) elif resp.status_code == 422: - raise APIError( + raise APIError.from_response( "The refund could not be processed by the payment processor.", - status=resp.status_code, - body=resp.text, + resp, + body_type=Problem, ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) async def get( self, @@ -427,9 +429,11 @@ async def get( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 401: The request is not authorized. - 404: The requested resource does not exist. + 401: The request is not authorized. (raises AuthenticationError) + 404: The requested resource does not exist. (raises NotFoundError) Unexpected response statuses also raise this exception. """ query_data: dict[str, typing.Any] = {} @@ -448,23 +452,22 @@ async def get( ): query_data["client_transaction_id"] = client_transaction_id - resp = await self._client.get( - f"/v2.1/merchants/{merchant_code}/transactions", - params=serialize_query_params(query_data) if query_data else None, - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.get( + f"/v2.1/merchants/{merchant_code}/transactions", + params=serialize_query_params(query_data) if query_data else None, + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(TransactionFull).validate_python(resp.json()) elif resp.status_code == 401: - raise APIError( - "The request is not authorized.", status=resp.status_code, body=resp.text - ) + raise APIError.from_response("The request is not authorized.", resp, body_type=Problem) elif resp.status_code == 404: - raise APIError( - "The requested resource does not exist.", status=resp.status_code, body=resp.text + raise APIError.from_response( + "The requested resource does not exist.", resp, body_type=Error ) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) async def list( self, @@ -494,9 +497,11 @@ async def list( Raises: + APITimeoutError: The request timed out. + APIConnectionError: The request failed because of a connection error. APIError: Raised when the API returns one of the documented error responses: - 400: The request is invalid for the submitted query parameters. - 401: The request is not authorized. + 400: The request is invalid for the submitted query parameters. (raises BadRequestError) + 401: The request is not authorized. (raises AuthenticationError) Unexpected response statuses also raise this exception. """ query_data: dict[str, typing.Any] = {} @@ -527,22 +532,19 @@ async def list( if not isinstance(oldest_ref, NotGivenType) and oldest_ref is not None: query_data["oldest_ref"] = oldest_ref - resp = await self._client.get( - f"/v2.1/merchants/{merchant_code}/transactions/history", - params=serialize_query_params(query_data) if query_data else None, - headers=headers, - ) + with _wrap_request_errors(): + resp = await self._client.get( + f"/v2.1/merchants/{merchant_code}/transactions/history", + params=serialize_query_params(query_data) if query_data else None, + headers=headers, + ) if resp.status_code == 200: return pydantic.TypeAdapter(ListTransactionsV21200Response).validate_python(resp.json()) elif resp.status_code == 400: - raise APIError( - "The request is invalid for the submitted query parameters.", - status=resp.status_code, - body=resp.text, + raise APIError.from_response( + "The request is invalid for the submitted query parameters.", resp, body_type=Error ) elif resp.status_code == 401: - raise APIError( - "The request is not authorized.", status=resp.status_code, body=resp.text - ) + raise APIError.from_response("The request is not authorized.", resp, body_type=Problem) else: - raise APIError(f"Unexpected response", status=resp.status_code, body=resp.text) + raise APIError.from_response("Unexpected response", resp) diff --git a/sumup/types/__init__.py b/sumup/types/__init__.py index d2a54556..022c1186 100644 --- a/sumup/types/__init__.py +++ b/sumup/types/__init__.py @@ -5450,3 +5450,15 @@ class UpdateReaderSettingsUnprocessableEntity(pydantic.BaseModel): """ errors: UpdateReaderSettingsUnprocessableEntityErrors + + +ProcessCheckout400Response = ErrorExtended | list[ErrorExtended] + +CreateApplePaySession400Response = Error | list[Error] + +CreateCustomer400Response = ErrorExtended | CustomerValidationError + +ListPayoutsV1400Response = list[ErrorExtended] +""" +ListPayoutsV1400Response is a schema definition. +""" diff --git a/tests/test_api_errors.py b/tests/test_api_errors.py new file mode 100644 index 00000000..a7a1b6ee --- /dev/null +++ b/tests/test_api_errors.py @@ -0,0 +1,441 @@ +import asyncio +import datetime + +import httpx +import pytest + +from sumup import APIError, errors +from sumup.checkouts import AsyncCheckoutsResource, CheckoutsResource +from sumup.payouts import ListPayoutsV1400Response +from sumup.readers import AsyncReadersResource, ReadersResource +from sumup.types import ( + CustomerValidationError, + DetailsError, + Error, + ErrorExtended, + ErrorForbidden, + Problem, + Unauthorized, +) + + +@pytest.mark.parametrize( + "content,expected_body", + [ + pytest.param( + b'{"error_code":"INVALID_QUERY","extra":{"field":"amount"}}', + {"error_code": "INVALID_QUERY", "extra": {"field": "amount"}}, + id="object", + ), + pytest.param(b'[{"error_code":"INVALID"}]', [{"error_code": "INVALID"}], id="array"), + pytest.param( + b'"{\\"error_code\\":\\"INVALID\\"}"', '{"error_code":"INVALID"}', id="string" + ), + pytest.param(b"0", 0, id="number"), + pytest.param(b"false", False, id="boolean"), + pytest.param(b"null", None, id="null"), + pytest.param(b"Service unavailable", "Service unavailable", id="text"), + pytest.param(b"Bad gateway", "Bad gateway", id="html"), + pytest.param(b'{"error_code":', '{"error_code":', id="malformed-json"), + pytest.param(b"", "", id="empty"), + ], +) +def test_api_error_from_response(content, expected_body): + response = httpx.Response(400, content=content, headers={"X-Request-ID": "request-123"}) + + error = APIError.from_response("Request failed", response) + + assert str(error) == "HTTP 400: Request failed" + assert error.message == "Request failed" + assert error.status == 400 + assert error.body == expected_body + assert error.response is response + assert error.response.content == content + assert error.response.headers["X-Request-ID"] == "request-123" + + +@pytest.mark.parametrize("body", ['{"error_code":"INVALID"}', {"error_code": "INVALID"}, None]) +def test_api_error_constructor_preserves_body(body): + error = APIError("Request failed", status=None, body=body) + + assert error.body is body + assert error.status is None + assert error.response is None + + +def test_api_error_from_response_uses_documented_type(): + response = httpx.Response( + 401, + json={ + "type": "https://developer.sumup.com/problem/unauthorized", + "title": "Unauthorized", + "trace_id": "trace-123", + }, + ) + + error = APIError.from_response("Request failed", response, body_type=Problem) + + assert isinstance(error, errors.AuthenticationError) + assert isinstance(error.body, Problem) + assert error.problem is error.body + assert error.body.title == "Unauthorized" + assert error.body.additional_properties["trace_id"] == "trace-123" + assert error.status == 401 + assert error.response is response + + +@pytest.mark.parametrize("body", [None, Error(message="Invalid request"), {"type": "about:blank"}]) +def test_problem_property_returns_none_for_other_bodies(body): + error = errors.BadRequestError("Request failed", response=httpx.Response(400), body=body) + + assert error.problem is None + assert error.body is body + + +@pytest.mark.parametrize( + "content,expected_body", + [ + (b'{"detail":"Missing problem type"}', {"detail": "Missing problem type"}), + (b"Service unavailable", "Service unavailable"), + ], +) +def test_invalid_typed_body_preserves_api_error(content, expected_body): + response = httpx.Response(401, content=content) + + error = APIError.from_response("Request failed", response, body_type=Problem) + + assert type(error) is errors.AuthenticationError + assert error.body == expected_body + assert error.status == 401 + assert error.response is response + + +@pytest.mark.parametrize( + "content_type", + ["application/problem+json", "Application/Problem+JSON; charset=utf-8"], +) +def test_api_error_recognizes_problem_content_type(content_type): + response = httpx.Response( + 404, + headers={"Content-Type": content_type}, + json={"type": "https://developer.sumup.com/problem/not-found", "detail": "Reader missing"}, + ) + + error = APIError.from_response("Request failed", response) + + assert isinstance(error, errors.NotFoundError) + assert isinstance(error.body, Problem) + assert error.body.detail == "Reader missing" + assert error.response is response + + +def test_problem_content_type_does_not_override_documented_type(): + response = httpx.Response( + 400, + headers={"Content-Type": "application/problem+json"}, + json={"error_code": "INVALID", "message": "Invalid amount"}, + ) + + error = APIError.from_response("Request failed", response, body_type=Error) + + assert isinstance(error.body, Error) + assert error.body.message == "Invalid amount" + + +@pytest.mark.parametrize( + "body,status,expected", + [ + pytest.param( + Problem(type="about:blank", title="Unauthorized", detail="Access token expired"), + 401, + "HTTP 401: Access token expired", + id="problem-detail", + ), + pytest.param( + Problem(type="about:blank", title="Unauthorized"), + 401, + "HTTP 401: Unauthorized", + id="problem-title", + ), + pytest.param(Error(message="Invalid amount"), 400, "HTTP 400: Invalid amount", id="error"), + pytest.param( + DetailsError(title="Invalid currency", details="Currency XX is not supported"), + 400, + "HTTP 400: Currency XX is not supported", + id="details-error", + ), + pytest.param( + ErrorForbidden(error_message="Missing scope"), + 403, + "HTTP 403: Missing scope", + id="error-message", + ), + pytest.param( + [ErrorExtended(message="Invalid amount"), ErrorExtended(message="Invalid currency")], + 400, + "HTTP 400: Invalid amount; Invalid currency", + id="array", + ), + pytest.param(None, 502, "HTTP 502: Request failed", id="fallback"), + pytest.param(None, None, "Request failed", id="no-response"), + ], +) +def test_api_error_string_uses_server_message(body, status, expected): + error = APIError("Request failed", status=status, body=body) + + assert str(error) == expected + assert error.message == expected.removeprefix(f"HTTP {status}: ") + + +@pytest.mark.parametrize("use_async", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize( + "status,content,expected_body,message,error_type", + [ + pytest.param( + 404, + b'{"error_code":"NOT_FOUND"}', + Error(error_code="NOT_FOUND"), + "The requested resource does not exist.", + errors.NotFoundError, + id="documented-error", + ), + pytest.param( + 401, + b'{"type":"https://developer.sumup.com/problem/unauthorized","title":"Unauthorized"}', + Problem(type="https://developer.sumup.com/problem/unauthorized", title="Unauthorized"), + "Unauthorized", + errors.AuthenticationError, + id="problem", + ), + pytest.param( + 502, + b"Bad gateway", + "Bad gateway", + "Unexpected response", + errors.InternalServerError, + id="unexpected-error", + ), + ], +) +def test_resource_api_errors(use_async, status, content, expected_body, message, error_type): + response = httpx.Response(status, content=content, headers={"X-Request-ID": "request-123"}) + transport = httpx.MockTransport(lambda _: response) + + with pytest.raises(error_type) as raised: + if use_async: + + async def run(): + async with httpx.AsyncClient( + base_url="https://api.sumup.test", transport=transport + ) as client: + await AsyncCheckoutsResource(client).get("checkout-123") + + asyncio.run(run()) + else: + with httpx.Client(base_url="https://api.sumup.test", transport=transport) as client: + CheckoutsResource(client).get("checkout-123") + + error = raised.value + assert error.status == status + assert error.body == expected_body + assert type(error) is error_type + assert error.message == message + assert error.args == (message,) + assert error.response is response + assert error.response.text == content.decode() + assert error.response.headers["X-Request-ID"] == "request-123" + + +@pytest.mark.parametrize("use_async", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize("multiple", [False, True], ids=["object", "array"]) +def test_inline_error_union(use_async, multiple): + payload = {"error_code": "INVALID", "message": "Invalid card", "param": "card.number"} + expected = ErrorExtended(**payload) + response = httpx.Response(400, json=[payload] if multiple else payload) + transport = httpx.MockTransport(lambda _: response) + + with pytest.raises(errors.BadRequestError) as raised: + if use_async: + + async def run(): + async with httpx.AsyncClient( + base_url="https://api.sumup.test", transport=transport + ) as client: + await AsyncCheckoutsResource(client).process( + "checkout-123", payment_type="card" + ) + + asyncio.run(run()) + else: + with httpx.Client(base_url="https://api.sumup.test", transport=transport) as client: + CheckoutsResource(client).process("checkout-123", payment_type="card") + + assert raised.value.body == ([expected] if multiple else expected) + assert raised.value.status == 400 + assert raised.value.response is response + + +def test_inline_error_object(sdk_factory): + response = httpx.Response( + 400, + json={ + "error_code": "INVALID", + "error_message": "Invalid customer", + "instance": "error-123", + }, + ) + sdk = sdk_factory(lambda _: response) + + with pytest.raises(errors.BadRequestError) as raised: + sdk.customers.create(customer_id="customer-123") + + assert isinstance(raised.value.body, CustomerValidationError) + assert raised.value.body.error_message == "Invalid customer" + assert raised.value.body.instance == "error-123" + assert str(raised.value) == "HTTP 400: Invalid customer" + + +def test_error_array(sdk_factory): + payload = {"error_code": "INVALID", "message": "Invalid date range", "param": "start_date"} + sdk = sdk_factory(lambda _: httpx.Response(400, json=[payload])) + + with pytest.raises(errors.BadRequestError) as raised: + sdk.payouts.list( + "merchant-123", + start_date=datetime.date(2026, 1, 2), + end_date=datetime.date(2026, 1, 1), + ) + + expected: ListPayoutsV1400Response = [ErrorExtended(**payload)] + assert raised.value.body == expected + + +def test_status_errors_share_the_api_error_base(): + response = httpx.Response(401, json={"type": "about:blank", "detail": "Access token expired"}) + + with pytest.raises(APIError) as raised: + raise APIError.from_response("Request failed", response, body_type=Problem) + + assert isinstance(raised.value, errors.APIStatusError) + assert isinstance(raised.value, errors.AuthenticationError) + assert isinstance(raised.value.body, Problem) + assert raised.value.body.detail == "Access token expired" + assert raised.value.response is response + + +@pytest.mark.parametrize("use_async", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize( + "content_type,payload,body_type", + [ + ( + "application/json; charset=utf-8", + {"errors": {"detail": "Invalid credentials", "type": "INVALID_BEARER_TOKEN"}}, + Unauthorized, + ), + ( + "Application/Problem+JSON; charset=utf-8", + {"type": "about:blank", "detail": "Invalid credentials"}, + Problem, + ), + ( + "application/xml", + {"errors": {"detail": "Invalid credentials", "type": "INVALID_BEARER_TOKEN"}}, + dict, + ), + ], +) +def test_reader_error_formats(use_async, content_type, payload, body_type): + response = httpx.Response(401, json=payload, headers={"Content-Type": content_type}) + transport = httpx.MockTransport(lambda _: response) + + with pytest.raises(APIError) as raised: + if use_async: + + async def run(): + async with httpx.AsyncClient( + base_url="https://api.sumup.test", transport=transport + ) as client: + await AsyncReadersResource(client).get_status("merchant-123", "reader-123") + + asyncio.run(run()) + else: + with httpx.Client(base_url="https://api.sumup.test", transport=transport) as client: + ReadersResource(client).get_status("merchant-123", "reader-123") + + error = raised.value + assert type(error) is errors.AuthenticationError + assert isinstance(error.body, body_type) + assert error.status == 401 + assert error.response is response + if body_type is not dict: + assert error.message == "Invalid credentials" + + +@pytest.mark.parametrize( + "status,error_type", + [ + (400, errors.BadRequestError), + (401, errors.AuthenticationError), + (403, errors.PermissionDeniedError), + (404, errors.NotFoundError), + (409, errors.ConflictError), + (422, errors.UnprocessableEntityError), + (429, errors.RateLimitError), + (500, errors.InternalServerError), + (599, errors.InternalServerError), + (418, errors.APIStatusError), + (302, APIError), + (202, APIError), + ], +) +def test_http_error_categories_do_not_depend_on_body(status, error_type): + response = httpx.Response(status, text="Unexpected response") + + error = APIError.from_response("Request failed", response) + + assert type(error) is error_type + assert error.body == response.text + assert error.response is response + assert error.status == status + + +@pytest.mark.parametrize("use_async", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize( + "cause_type,error_type", + [ + (httpx.ConnectError, errors.APIConnectionError), + (httpx.ReadTimeout, errors.APITimeoutError), + ], +) +def test_resource_transport_errors(use_async, cause_type, error_type): + requests = [] + + def handler(request): + requests.append(request) + raise cause_type("Transport failed", request=request) + + transport = httpx.MockTransport(handler) + with pytest.raises(APIError) as raised: + if use_async: + + async def run(): + async with httpx.AsyncClient( + base_url="https://api.sumup.test", transport=transport + ) as client: + await AsyncCheckoutsResource(client).get("checkout-123") + + asyncio.run(run()) + else: + with httpx.Client(base_url="https://api.sumup.test", transport=transport) as client: + CheckoutsResource(client).get("checkout-123") + + error = raised.value + assert type(error) is error_type + assert isinstance(error, errors.APIConnectionError) + assert isinstance(error.__cause__, cause_type) + assert error.request is requests[0] + assert error.request is error.__cause__.request + assert error.response is None + assert error.status is None + assert error.body is None + assert isinstance(error.message, str) diff --git a/tests/test_events.py b/tests/test_events.py index 1ab7e8e2..330d3763 100644 --- a/tests/test_events.py +++ b/tests/test_events.py @@ -7,7 +7,7 @@ import pydantic import pytest -from sumup import APIError, AsyncSumup +from sumup import APIError, AsyncSumup, errors from sumup.events import ( EventCallbackError, EventHandlerRegistrationError, @@ -25,7 +25,7 @@ UnknownEvent, verify_event_signature, ) -from sumup.types import Reader +from sumup.types import Problem, Reader _NOW = 1788696000 _SECRET = "event_secret_test" @@ -347,18 +347,55 @@ def respond(request): assert request.headers["X-Custom"] == "value" -@pytest.mark.parametrize("status,body", [(404, {"title": "Not Found"}), (500, "unavailable")]) -def test_fetch_object_preserves_api_errors(sdk_factory, status, body): - sdk = sdk_factory( - lambda _: httpx.Response( - status, **({"json": body} if isinstance(body, dict) else {"text": body}) - ) +@pytest.mark.parametrize( + "status,body", + [ + (404, {"title": "Not Found"}), + (500, "unavailable"), + ( + 404, + Problem(type="https://developer.sumup.com/problem/not-found", detail="Reader missing"), + ), + ], +) +@pytest.mark.parametrize("use_async", [False, True], ids=["sync", "async"]) +def test_fetch_object_preserves_api_errors(sdk_factory, status, body, use_async): + payload = body.model_dump() if isinstance(body, Problem) else body + response = httpx.Response( + status, + headers={"X-Request-ID": "request-123"}, + **({"json": payload} if isinstance(payload, dict) else {"text": payload}), ) - event = sdk.parse_event_notification_without_verification(_body()) + if isinstance(body, Problem): + response.headers["Content-Type"] = "application/problem+json" with pytest.raises(APIError) as raised: - event.fetch_object() + if use_async: + + async def run(): + sdk = AsyncSumup(api_key="test", base_url="https://api.sumup.test") + await sdk.aclose() + async with httpx.AsyncClient( + base_url="https://api.sumup.test", + transport=httpx.MockTransport(lambda _: response), + ) as client: + sdk._client = client + event = sdk.parse_event_notification_without_verification(_body()) + assert isinstance(event, ReaderCreatedEvent) + await event.fetch_object_async() + + asyncio.run(run()) + else: + sdk = sdk_factory(lambda _: response) + event = sdk.parse_event_notification_without_verification(_body()) + event.fetch_object() assert raised.value.status == status assert raised.value.body == body + if isinstance(body, Problem): + assert isinstance(raised.value, errors.NotFoundError) + assert isinstance(raised.value.body, Problem) + assert raised.value.body.detail == body.detail + assert raised.value.response is response + assert raised.value.response.headers["X-Request-ID"] == "request-123" def test_fetch_object_does_not_follow_redirects(sdk_factory): @@ -535,3 +572,36 @@ def callback(notification: ReaderCreatedEvent) -> None: # Keeping the parameter name also checks that the decorator preserves typing. callback(notification=event) assert calls == [event.id] + + +@pytest.mark.parametrize("use_async", [False, True], ids=["sync", "async"]) +def test_fetch_object_wraps_transport_errors(sdk_factory, use_async): + requests = [] + + def handler(request): + requests.append(request) + raise httpx.ReadTimeout("Transport failed", request=request) + + with pytest.raises(errors.APITimeoutError) as raised: + if use_async: + + async def run(): + sdk = AsyncSumup(api_key="test", base_url="https://api.sumup.test") + await sdk.aclose() + async with httpx.AsyncClient( + base_url="https://api.sumup.test", transport=httpx.MockTransport(handler) + ) as client: + sdk._client = client + event = sdk.parse_event_notification_without_verification(_body()) + assert isinstance(event, ReaderCreatedEvent) + await event.fetch_object_async() + + asyncio.run(run()) + else: + sdk = sdk_factory(handler) + event = sdk.parse_event_notification_without_verification(_body()) + event.fetch_object() + + assert isinstance(raised.value.__cause__, httpx.ReadTimeout) + assert raised.value.request is requests[0] + assert raised.value.response is None