Skip to content

Feature request: Support custom status codes of fine-grained responses for OpenAPI spec generation #7496

@RynoM

Description

@RynoM

Use case

For our APIs we sometimes have custom status codes in our success responses (for instance 201 Created) leading us to use the Response class.

The following (simplified) code:

@app.post("/subscriptions")
def create_subscription(
    body: CreateSubscriptionRequest,
) -> Response[CreateSubscriptionResponse]:
    """Create a subscription."""
    subscription_response = CreateSubscriptionResponse(**params)
    return Response(
        status_code=201,
        body=subscription_response,
        content_type=content_types.APPLICATION_JSON,
    )

Results in this spec:

  "200": {
    "description": "Successful Response",
    "content": {
      "application/json": {
        "schema": {
          "$ref": "#/components/schemas/CreateSubscriptionResponse"
        }
      }
    }
  }

However I was expecting this to work seamlessly with the openapi spec generation, but if we look at Route._get_openapi_path:

Image ` We can see that either self.responses is passed from the routing decorator, or simply 200 is set.

Working example:

@app.post(
    "/subscriptions", 
    responses={201: {"description": "Successful Creation", "content": {"application/json": {"model": CreateSubscriptionResponse}}}},
)
def create_subscription(
    body: CreateSubscriptionRequest,
) -> Response[CreateSubscriptionResponse]:
    """Create a subscription."""
    subscription_response = CreateSubscriptionResponse(**params)
    return Response(
        status_code=201,
        body=subscription_response,
        content_type=content_types.APPLICATION_JSON,
    )

I think it would be nice to not have to set the openapi responses in the decorater manually. However I see this might be hard as now its simply checking a type hint and the other would be an instance of Response.

Solution/User Experience

@app.post("/subscriptions")
def create_subscription(
    body: CreateSubscriptionRequest,
) -> Response[CreateSubscriptionResponse]:
    """Create a subscription."""
    subscription_response = CreateSubscriptionResponse(**params)
    return Response(
        status_code=201,
        body=subscription_response,
        content_type=content_types.APPLICATION_JSON,
    )

I would like this to generate openapi spec with 201 response code.

Alternative solutions

Acknowledgment

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature-requestfeature requesttriagePending triage from maintainers

    Type

    No type

    Projects

    Status

    Triage

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions