Skip to content

fix: generate binary response when errors include plain text#7284

Merged
gavinbarron merged 3 commits intomainfrom
fix/provide-binary-response-with-plain-text-error
Jan 13, 2026
Merged

fix: generate binary response when errors include plain text#7284
gavinbarron merged 3 commits intomainfrom
fix/provide-binary-response-with-plain-text-error

Conversation

@gavinbarron
Copy link
Contributor

Bug Fix for GitHub Issue #3855: Binary Format Support

The Actual Bug

When an API endpoint returns binary data (e.g., application/octet-stream with format: binary) in the success response (200) AND has error responses (4xx, 5xx) with text/plain content type, Kiota incorrectly generates a string return type instead of binary (which becomes Stream in C#).

Reproduction Test Case

openapi: 3.0.1
paths:
  /image:
    get:
      responses:
        '200':
          description: Returns image binary data
          content:
            application/octet-stream:
              schema:
                type: string
                format: binary
        '500':
          description: Error response
          content:
            application/json:
              schema:
                type: object
                properties:
                  error: { type: string }
            text/plain:
              schema:
                type: string

Expected: Return type should be binary (→ Stream in C#)
Actual (before fix): Return type was string

Root Cause

The bug is in GetExecutorMethodDefaultReturnType method in KiotaBuilder.cs:1365-1377.

The Problem Flow

  1. GetResponseSchema is called to get the schema for success responses (200, 201, etc.)
  2. It filters content types by StructuredMimeTypes (default: application/json, text/plain, etc.)
  3. Since application/octet-stream is NOT in the default structured MIME types list, it gets filtered out
  4. GetResponseSchema returns null because no schema matched the structured MIME types
  5. This triggers a fallback to GetExecutorMethodDefaultReturnType
  6. BUG: GetExecutorMethodDefaultReturnType was checking if ANY response (including error responses like 500) had text/plain content
  7. Since the 500 error response had text/plain, it returned "string" instead of "binary"

The Buggy Code (Before Fix)

private static CodeType GetExecutorMethodDefaultReturnType(OpenApiOperation operation)
{
    string returnType;
    if (operation.Responses?.Any(static x => (x.Value.Content?.ContainsKey(RequestBodyOctetStreamContentType) ?? false) && redirectStatusCodes.Contains(x.Key)) is true)
        returnType = "binary";
    else if (operation.Responses?.Any(static x => noContentStatusCodes.Contains(x.Key)) is true)
        returnType = VoidType;
    // BUG: This checks ALL responses, including error responses (4xx, 5xx)
    else if (operation.Responses?.Any(static x => x.Value.Content?.ContainsKey(RequestBodyPlainTextContentType) ?? false) is true)
        returnType = "string";  // <-- WRONG! Returns "string" even though 200 is binary
    else
        returnType = "binary";
    return new CodeType { Name = returnType, IsExternal = true, };
}

The Fix

The fix ensures that text/plain is only checked in success responses (200, 201, 202, 203, 206, 2XX), not error responses (4xx, 5xx).

Fixed Code

private static CodeType GetExecutorMethodDefaultReturnType(OpenApiOperation operation)
{
    string returnType;
    if (operation.Responses?.Any(static x => (x.Value.Content?.ContainsKey(RequestBodyOctetStreamContentType) ?? false) && redirectStatusCodes.Contains(x.Key)) is true)
        returnType = "binary";
    else if (operation.Responses?.Any(static x => noContentStatusCodes.Contains(x.Key)) is true)
        returnType = VoidType;
    // FIX: Only check text/plain in SUCCESS responses (200, 201, 202, 203, 206, 2XX)
    else if (operation.Responses?.Any(static x => (x.Value.Content?.ContainsKey(RequestBodyPlainTextContentType) ?? false) && OpenApiOperationExtensions.SuccessCodes.Contains(x.Key)) is true)
        returnType = "string";
    else
        returnType = "binary";
    return new CodeType { Name = returnType, IsExternal = true, };
}

Key Changes

  1. Added a check: && OpenApiOperationExtensions.SuccessCodes.Contains(x.Key)
  2. Added parentheses around the null-coalescing operator to ensure correct precedence: (x.Value.Content?.ContainsKey(RequestBodyPlainTextContentType) ?? false)

This ensures that only success responses (200, 201, 202, 203, 206, 2XX) are checked for text/plain content type, and error responses (4xx, 5xx) are ignored.

Test Coverage

Added comprehensive test case: GeneratesBinaryReturnTypeWhenSuccessResponseIsBinaryAndErrorResponseIsPlainTextOrJsonAsync

This test verifies that when:

  • 200 response has application/octet-stream with type: string, format: binary
  • 500 error response has both application/json and text/plain content types

The generated return type is correctly binary (not string).

Test Results

  • All 1841 tests pass (2 skipped, 0 failed)
  • ✅ The previously failing test now passes
  • ✅ No regressions introduced

Impact

This fix ensures that:

  1. Binary download endpoints correctly return Stream in C# (or equivalent in other languages)
  2. Error responses with text/plain don't interfere with binary success responses
  3. The behavior matches user expectations for binary file downloads

Files Changed

  1. KiotaBuilder.cs: Fixed GetExecutorMethodDefaultReturnType to only check success responses for text/plain
  2. KiotaBuilderTests.cs: Added test case GeneratesBinaryReturnTypeWhenSuccessResponseIsBinaryAndErrorResponseIsPlainTextOrJsonAsync

Related Constants

  • SuccessCodes: { "200", "201", "202", "203", "206", "2XX" } (defined in OpenApiOperationExtensions.cs:11)
  • errorStatusCodes: 400-599 (defined in KiotaBuilder.cs:1266)
  • Default StructuredMimeTypes: application/json, text/plain, application/x-www-form-urlencoded, multipart/form-data (defined in GenerationConfiguration.cs:119-124)

Example Usage

After this fix, the following OpenAPI spec correctly generates a binary return type:

paths:
  /download:
    get:
      responses:
        '200':
          content:
            application/octet-stream:
              schema:
                type: string
                format: binary
        '500':
          content:
            text/plain:
              schema:
                type: string

Generated C# method signature:

public async Task<Stream?> GetAsync(...)

This resolves the issue reported in GitHub #3855.

@gavinbarron gavinbarron requested a review from a team as a code owner January 13, 2026 19:41
@msgraph-bot msgraph-bot bot added this to Kiota Jan 13, 2026
@gavinbarron gavinbarron linked an issue Jan 13, 2026 that may be closed by this pull request
Copy link
Member

@baywet baywet left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add an entry in the changelog please?

@github-project-automation github-project-automation bot moved this to In Progress 🚧 in Kiota Jan 13, 2026
@gavinbarron
Copy link
Contributor Author

Thanks for the catch, we should automate that at some point.

Copy link
Member

@baywet baywet left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for making the changes!

@baywet
Copy link
Member

baywet commented Jan 13, 2026

The reason why it wasn't automated to begin with is because of the preview releases that go out each week. We'd either need some complex branches management and sync process. Or something that commits dummy trigger commits. Since the project is much less active, maybe weekly previews is not as much important anymore. And deferring to another branch for previews + sync on demand would be enough.

@gavinbarron gavinbarron enabled auto-merge (squash) January 13, 2026 20:37
@gavinbarron gavinbarron merged commit 3240b23 into main Jan 13, 2026
290 checks passed
@gavinbarron gavinbarron deleted the fix/provide-binary-response-with-plain-text-error branch January 13, 2026 22:31
@github-project-automation github-project-automation bot moved this from In Progress 🚧 to Done ✔️ in Kiota Jan 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Archived in project

Development

Successfully merging this pull request may close these issues.

Generating a client for an endpoint that downloads binary data

2 participants