Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion codegen/pkg/builder/builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@ type Builder struct {

pathsByTag map[string]*v3.Paths

events []EventDefinition
events []EventDefinition
errorBodyTypes []Writable

templates *template.Template

Expand Down Expand Up @@ -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
}
Expand Down
3 changes: 2 additions & 1 deletion codegen/pkg/builder/doc.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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()
Expand Down
6 changes: 3 additions & 3 deletions codegen/pkg/builder/doc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,15 @@ 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)
}

if !strings.Contains(doc, "400: The request body is invalid.") {
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)
}

Expand All @@ -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)
}
}
111 changes: 111 additions & 0 deletions codegen/pkg/builder/error_responses_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
}
}
96 changes: 96 additions & 0 deletions codegen/pkg/builder/errors.go
Original file line number Diff line number Diff line change
@@ -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"
}
14 changes: 10 additions & 4 deletions codegen/pkg/builder/intermediate_representation.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand All @@ -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 {
Expand Down
15 changes: 10 additions & 5 deletions codegen/pkg/builder/methods.go
Original file line number Diff line number Diff line change
Expand Up @@ -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),
})
Expand Down Expand Up @@ -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 ""
}

Expand Down
Loading
Loading