Feature request: add exception handlers return types to OpenAPI responses

Ouverte
#4,928 8 commentaires 1 réaction 0 personnes assignées Voir sur GitHub

Les mainteneurs répondent en général sous 1 jour

Personne n'a encore pris cette issue.

Évaluation

Difficulté
4/5
Temps estimé
3-5 jours
Accessibilité débutants
35/100
Type d'issue
Fonctionnalité
Clarté
Plutôt claire
Activité
Calme
Stack technique
aws, openapi, python

Piste de recherche

Start from APIGatewayRestResolver and its exception_handler registration, then trace how route responses are converted into OpenAPI schemas. Reproduce the example and locate the OpenAPI generation tests. Done means a registered exception handler contributes its return model and associated status code to the generated schema without requiring repeated manual responses declarations.

Rédigé par le modèle d'indexation à partir du texte de l'issue.

Description

feature-request help wanted researching
Use case

I use an API Gateway event handler with validation enabled and I'd like exception handlers response types to be automatically add to the openAPI schema. I can add responses parameter to my endpoint definition, however it's not ideal as it adds a lot off repetition, duplication and introduce potential for incorrect openAPI schemas.

Solution/User Experience
import requests
from typing import List, Optional

from pydantic import BaseModel, Field
from aws_lambda_powertools.utilities.typing import LambdaContext
from aws_lambda_powertools.event_handler import APIGatewayRestResolver

app = APIGatewayRestResolver(enable_validation=True)


class Todo(BaseModel):
   user_id: int = Field(alias="userId")
   id: int
   title: str
   completed: bool


class Error(BaseModel):
   error: str
   detail: Optional[list[dict]]


@app.exception_handler(Exception)
def internal_server_error(error: Exception) -> Error:
   return Error(error="internal_server_error")


@app.get("/todos")
def get_todos() -> List[Todo]:
   todo = requests.get("https://jsonplaceholder.typicode.com/todos")
   todo.raise_for_status()

   return todo.json()


def lambda_handler(event: dict, context: LambdaContext) -> dict:
   return app.resolve(event, context)

This is what currently gets generated:

openapi: 3.0.3
info:
title: Powertools API
version: 1.0.0
servers:
- url: /
paths:
/todos:
   get:
     operationId: get_todos_get
     responses:
       '200':
         description: Successful Response
         content:
           application/json:
             schema:
               items:
                 $ref: '#/components/schemas/Todo'
               type: array
               title: Return
       '422':
         description: Validation Error
         content:
           application/json:
             schema:
               $ref: '#/components/schemas/HTTPValidationError'
components:
schemas:
   HTTPValidationError:
     properties:
       detail:
         items:
           $ref: '#/components/schemas/ValidationError'
         type: array
         title: Detail
     type: object
     title: HTTPValidationError
   Todo:
     properties:
       userId:
         type: integer
         title: Userid
       id:
         type: integer
         title: Id
       title:
         type: string
         title: Title
       completed:
         type: boolean
         title: Completed
     type: object
     required:
       - userId
       - id
       - title
       - completed
     title: Todo
   ValidationError:
     properties:
       loc:
         items:
           anyOf:
             - type: string
             - type: integer
         type: array
         title: Location
       type:
         type: string
         title: Error Type
     type: object
     required:
       - loc
       - msg
       - type
     title: ValidationError

ideally this would be genrated:

openapi: 3.0.3
info:
title: Powertools API
version: 1.0.0
servers:
- url: /
paths:
/todos:
   get:
     operationId: get_todos_get
     responses:
       '200':
         description: Successful Response
         content:
           application/json:
             schema:
               items:
                 $ref: '#/components/schemas/Todo'
               type: array
               title: Return
       '422':
         description: Validation Error
         content:
           application/json:
             schema:
               $ref: '#/components/schemas/HTTPValidationError'
       '500':
         description: Internal Server Error
         content:
           application/json:
             schema:
               $ref: '#/components/schemas/Error'
components:
schemas:
   HTTPValidationError:
     properties:
       detail:
         items:
           $ref: '#/components/schemas/ValidationError'
         type: array
         title: Detail
     type: object
     title: HTTPValidationError
   Todo:
     properties:
       userId:
         type: integer
         title: Userid
       id:
         type: integer
         title: Id
       title:
         type: string
         title: Title
       completed:
         type: boolean
         title: Completed
     type: object
     required:
       - userId
       - id
       - title
       - completed
     title: Todo
   ValidationError:
     properties:
       loc:
         items:
           anyOf:
             - type: string
             - type: integer
         type: array
         title: Location
       type:
         type: string
         title: Error Type
     type: object
     required:
       - loc
       - msg
       - type
     title: ValidationError
   Error:
     properties:
       error:
         type: string
         title: Error
       detail:
         type: array
         items:
           type: object
         title: Detail
     type: object
     required:
       - error

This would require a status code to be attached to each exception_handler and potentially some other context.

Alternative solutions

No response

Acknowledgment
Langage dominant
Python
Étoiles
3.3k
Forks
511
Merge moyen
3 j 8 h
PR mergées (30 j)
92

Préparer son environnement

Par où commencer

  1. Lisez l'issue en entier, puis le guide de contribution du projet.
  2. Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
  3. Forkez le dépôt et travaillez sur une branche.
  4. Ouvrez une pull request qui référence le numéro de l'issue.

Autres issues de aws-powertools/powertools-lambda-python

Toutes les issues de aws-powertools/powertools-lambda-python

Issues similaires

Plus d'issues Python

Recevez les nouvelles issues par e-mail

Un résumé court des issues GitHub adaptées aux débutants.