oapi-codegen icon indicating copy to clipboard operation
oapi-codegen copied to clipboard

How to make response types generic for multiple endpoints

Open jensjeflensje opened this issue 3 months ago • 1 comments

I have multiple endpoints that have the same validation logic that returns a few different status codes. That validation logic is in a different function. The problem is that every endpoint has their own type for returning different status codes, so my validation logic can't return a response that can be passed on by the endpoint.

It looks like this:

func validate() AnErrorResponse {
    if (scenario0) { return Response400; }
    if (scenario1) { return Response401; }
    if (scenario2) { return Response404; }

    return nil; // no error
}

func (t *TranscriptHandler) ListTranscripts(ctx context.Context, request ListTranscriptsRequestObject) (ListTranscriptsResponseObject, error) {
    validationError := validate();
    if (validationError != nil) {
        // I can't do this, because there is no generic response type
        // I would have to take the validationError and convert it to ListTranscripts400JSONResponse, ListTranscripts401JSONResponse, ListTranscripts404JSONResponse etc
        return validationError;
    }

    // endpoint logic
}

func (t *TranscriptHandler) DeleteTranscript(ctx context.Context, request DeleteTranscriptRequestObject) (DeleteTranscriptResponseObject, error) {
    validationError := validate();
    if (validationError != nil) {
         // I can't do this, because there is no generic response type
        return validationError;
    }

    // endpoint logic
}

Is there any better way to do this? I feel like having to make different response types for every endpoint shouldn't be the solution.

jensjeflensje avatar Nov 17 '25 14:11 jensjeflensje

On the other side, I am facing the same issue when receiving responses. https://github.com/oapi-codegen/oapi-codegen/issues/2149

I am facing the same issue, and trying to gather feedback on what to add to the library to enable a good solution.

CJourneaux avatar Nov 26 '25 16:11 CJourneaux