Skip to content

Set by_alias dynamically when using a schema response? #1710

@stanorama

Description

@stanorama

Is there a better way to toggle between returning a response with by_alias set.
I have some API clients that require camelCase and some that require snake_case.
The X-Format header can be set to specify which format to return the response in.
However this only works with a response of dict.

If i use the response as the schema, the by_alias attibute set in the router decorator will take prescendence.
I have looked at using a custom renderer, but this seems to too late in the response chain.

The below works, however the repsonse of dict means the open API docs are limited.

@router.post(
    path="/cost_calc/acquisitions",
    response=dict,
    openapi_extra={
        "parameters": [
            {"in": "header", "name": "X-Format", "schema": {"type": "string"}}
        ]
    },
)
def create_acquisition_deal(request: HttpRequest, payload: AcquisitionDealSchema):

    by_alias = request.headers.get("X-Format") == "camel"

    acquisition_deal = AcquisitionDeal.objects.create(
        **payload.model_dump(by_alias=False),
        is_deleted=False,
    )

    return AcquisitionDealSchema.from_orm(acquisition_deal).model_dump(
        by_alias=by_alias
    )

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions