Skip to content

Obey request-body-strict in OpenAPI schema generation#3100

Draft
Copilot wants to merge 5 commits intomainfrom
copilot/fix-openapi-request-body-strict
Draft

Obey request-body-strict in OpenAPI schema generation#3100
Copilot wants to merge 5 commits intomainfrom
copilot/fix-openapi-request-body-strict

Conversation

Copy link
Contributor

Copilot AI commented Feb 2, 2026

Why make this change?

OpenAPI schemas did not reflect the request-body-strict runtime setting. When false, clients can send extra fields (which are ignored), but the generated schema didn't communicate this—potentially misleading API consumers.

What is this change?

Sets additionalProperties on request body schemas only based on request-body-strict config:

  • true (default): additionalProperties: false — strict field validation
  • false: additionalProperties: true — extra fields allowed

Affected request body schemas:

  • {EntityName}_NoAutoPK, {EntityName}_NoPK
  • {EntityName}_sp_request (stored procedures)

Response schemas ({EntityName}, {EntityName}_sp_response) always have additionalProperties: false since the server controls response shape—this setting only governs what the server accepts in request bodies.

Example OpenAPI output when request-body-strict: false:

{
  "components": {
    "schemas": {
      "Book": {
        "type": "object",
        "properties": { ... },
        "additionalProperties": false
      },
      "Book_NoAutoPK": {
        "type": "object",
        "properties": { ... },
        "additionalProperties": true
      },
      "Book_NoPK": {
        "type": "object",
        "properties": { ... },
        "additionalProperties": true
      }
    }
  }
}

How was this tested?

  • Integration Tests
  • Unit Tests

Added RequestBodyStrictTests.cs with tests for both strict/non-strict modes validating:

  • Response schema (Book) always has additionalProperties: false
  • Request body schemas (Book_NoAutoPK, Book_NoPK) respect the request-body-strict setting

Sample Request(s)

GET /api/openapi

Returns OpenAPI document with additionalProperties: true on request body schemas when config has:

{
  "runtime": {
    "rest": {
      "request-body-strict": false
    }
  }
}
Original prompt

This section details on the original issue you should resolve

<issue_title>[Enh]: Obey "request-body-strict" in OpenAPI</issue_title>
<issue_description>## What?

Today, our OpenAPI includes object types that are not required by the endpoint. See #1838</issue_description>

<agent_instructions>include resolution for #1838 resolve both in a single pr with as little new code as possible</agent_instructions>

Comments on the Issue (you are @copilot in this section)

@JerryNixon ### The Problem

Current behavior: The OpenAPI document generated by DAB includes schemas for models like EntityName_NoAutoPK (entities without auto-generated primary keys) regardless of the runtime.rest.request-body-strict configuration setting.

Issue #1838 screenshot shows: The OpenAPI document exposes Book_NoAutoPK schema even though it may not be necessary depending on strictness settings.

Understanding request-body-strict

The request-body-strict configuration controls whether DAB allows extraneous fields in REST request bodies:

{
  "runtime": {
    "rest": {
      "enabled": true,
      "path": "/api",
      "request-body-strict": true  // Default: true
    }
  }
}

When true (strict mode - DEFAULT):

  • Request body must contain ONLY valid fields for the entity
  • Extraneous/extra fields cause a 400 Bad Request error
  • Read-only fields cannot be included in request bodies

When false (non-strict mode):

  • Extra fields in the request body are ignored (not cause errors)
  • Provides more flexibility for clients

How It Works at Runtime

Looking at the request validation code:

/// <summary>
/// Helper method to check if the request body for REST allows extra fields.
/// </summary>
/// <returns>true if extra fields are not allowed in REST request body.</returns>
private bool IsRequestBodyStrict()
{
    if (_runtimeConfigProvider.TryGetConfig(out RuntimeConfig? runtimeConfig))
    {
        return runtimeConfig.IsRequestBodyStrict;
    }

    return true; // Default is strict mode
}

And the validation enforcement:

// There may be unvalidated fields remaining because of extraneous fields in request body
// which are not mapped to the table. We throw an exception only when we operate in strict mode,
// i.e. when extraneous fields are not allowed.
if (unvalidatedFields.Any() && isRequestBodyStrict)
{
    throw new DataApiBuilderException(
        message: "Invalid request body. Either insufficient or extra fields supplied.",
        statusCode: HttpStatusCode.BadRequest,
        subStatusCode: DataApiBuilderException.SubStatusCodes.BadRequest);
}

The Enhancement Request

What DAB currently does in OpenAPI generation:

  • Creates multiple schema models for each entity regardless of request-body-strict:
    • EntityName - Full schema with all fields
    • EntityName_NoAutoPK - Schema excluding auto-generated PKs (for POST)
    • EntityName_NoPK - Schema excluding all PKs (for PUT/PATCH)

What the enhancement wants:

  • If request-body-strict: true: Include all schema variations (current behavior)
  • If request-body-strict: false: Potentially simplify the OpenAPI schema since extra fields are allowed anyway

The current OpenAPI generator doesn't check this setting:

private static OpenApiRequestBody CreateOpenApiRequestBodyPayload(string schemaReferenceId, bool requestBodyRequired)
{
    OpenApiRequestBody requestBody = new()
    {
        Content = new Dictionary<string, OpenApiMediaType>()
        {
            {
                MediaTypeNames.Application.Json,
                new()
                {
                    Schema = new OpenApiSchema()
                    {
                        Reference = new OpenApiReference()
                        {
                            Type = ReferenceType.Schema,
                            Id = schemaReferenceId  // ← Always includes _NoAutoPK, _NoPK variants
                        }
                    }
                }
            }
        },
        Required = requestBodyRequired
    };

    return requestBody;
}

Current Impact

When request-body-strict: true (Default)

OpenAPI shows:

  • Book - Full schema
  • Book_NoAutoPK - For POST r...

💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.

Copilot AI and others added 2 commits February 2, 2026 23:23
Co-authored-by: JerryNixon <1749983+JerryNixon@users.noreply.github.com>
Co-authored-by: JerryNixon <1749983+JerryNixon@users.noreply.github.com>
Copilot AI changed the title [WIP] Fix OpenAPI to obey request-body-strict setting Obey request-body-strict in OpenAPI schema generation Feb 2, 2026
Copilot AI requested a review from JerryNixon February 2, 2026 23:29
@JerryNixon JerryNixon added the 2.0 label Feb 4, 2026
@JerryNixon JerryNixon removed their assignment Feb 16, 2026
@JerryNixon
Copy link
Contributor

@copilot

  1. src/Core/Services/OpenAPI/OpenApiDocumentor.cs line 1027 (Correctness)
    {EntityName} schema is shared between responses and request bodies but gets additionalProperties: true for both.
schemas.Add(entityName, CreateComponentSchema(entityName, fields: exposedColumnNames, metadataProvider, entities, allowAdditionalProperties: !isRequestBodyStrict));
```csharp

This schema is referenced in GET, PUT, PATCH, and POST response bodies (lines 330, 340, 341, 348, 349, 365, 376). Setting additionalProperties: true on a response schema tells consumers "expect extra unknown fields in the response." That is semantically wrong. The server controls its own responses; request-body-strict only governs what the server accepts in request bodies.

The _NoAutoPK and _NoPK schemas are only used in request bodies, so they are correct. The SP response schema on line 1020 is also correctly hardcoded to false.

Fix: keep the {EntityName} schema with allowAdditionalProperties: false, or create a separate request-body variant if the full schema is also needed for POST request bodies on non-autogenerated-PK entities (line 372 falls back to {entityName} when no auto-PK exists).

2. src/Core/Services/OpenAPI/OpenApiDocumentor.cs line 1020 (Positive)

```csharp
schemas.Add(entityName + SP_RESPONSE_SUFFIX, CreateComponentSchema(..., allowAdditionalProperties: false));

Good. Response schemas should always be false. Same reasoning should be applied to the {EntityName} schema (see #1 above).

  1. src/Service.Tests/OpenApiDocumentor/RequestBodyStrictTests.cs line 5 (Cleanup)
using System.Linq;

Unused. Remove it.

  1. src/Service.Tests/OpenApiDocumentor/RequestBodyStrictTests.cs lines 35-48, 102-115 (DRY)

The entity setup is identical in both test methods. Extract it into a private helper like CreateBookRuntimeEntities(). Each test would then differ only in the RestRuntimeOptions and assertions, which makes the intent easier to scan.

  1. src/Service.Tests/OpenApiDocumentor/OpenApiTestBootstrap.cs line 63 (Nullable)
RestRuntimeOptions restOptions)

The 3-arg overload (line 37) passes null here, but this parameter is not annotated as nullable. It should be RestRuntimeOptions? restOptions to match usage. The null check on line 68 already expects this.

  1. src/Service.Tests/OpenApiDocumentor/OpenApiTestBootstrap.cs lines 53-57 (Doc)
/// <param name="runtimeEntities"></param>
/// <param name="configFileName"></param>
/// <param name="databaseEnvironment"></param>

Either fill in descriptions or remove the empty tags. Empty tags are noise.

  1. src/Core/Services/OpenAPI/OpenApiDocumentor.cs lines 1014, 1026, 1047, 1064 (Comments)

The comment // When isRequestBodyStrict is false, additionalProperties is set to true... appears 4 times. The method-level doc comment (lines 979-981) already explains this. The parameter name allowAdditionalProperties is self-documenting. Remove the inline repetition.

  1. src/Core/Services/OpenAPI/OpenApiDocumentor.cs line 1075 (Positive)

Good: removed the duplicate /// that was on CreateSpRequestComponentSchema. Nice cleanup.

Copy link
Contributor Author

Copilot AI commented Feb 16, 2026

@copilot

  1. src/Core/Services/OpenAPI/OpenApiDocumentor.cs line 1027 (Correctness)
    ...

Addressed all feedback in 46a4580:

  1. {EntityName} schema: Now always additionalProperties: false since it's used for responses. Only request body schemas (_NoAutoPK, _NoPK, _sp_request) respect request-body-strict.

  2. Removed using System.Linq: Done.

  3. DRY improvement: Extracted CreateBookRuntimeEntities() helper method.

  4. Nullable parameter: Used method overloads instead of nullable parameter to avoid CS8632 warning.

  5. Empty param tags: Filled in all param descriptions.

  6. Removed repetitive comments: Removed the 4 inline comments - method-level docs and parameter name are self-documenting.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Enh]: Obey "request-body-strict" in OpenAPI

2 participants