Set AdditionalProperties of OpenAPI to false by default
Asked Answered
S

1

6

My OpenAPI specification contains a lot of objects. According to the spec, a free-form object will by default have additionProperties:true. This is why when I use NSwag to generate a C# client, all requests and responses contain a dictionary AdditionalProperties. I don't need these additional properties.

Is there a way of changing the default value for additionalProperties such that I don't have to modify every object in my API?

Schlueter answered 11/10, 2022 at 12:8 Comment(0)
D
0

No, unfortunately you can't set additionalProperties globally. When writing the api schema manually you will have to add the option for every free-form object.

However, when creating the api schema via a framework you sometimes have the possibility to extend the swagger generator in a way where the additionalProperties option is set for you. Here are examples for Laravel and asp.net:

config/l5-swagger

return [
    // ...
    'default' => [
        // ...
        'scanOptions' => [
            // ...
            'processors' => [
                new \App\SwaggerProcessors\DisableAdditionalProperties(),
            ],
        ],
    ],
];

app/SwaggerProcessors/DisableAdditionalProperties.php

<?php

declare(strict_types=1);

namespace App\SwaggerProcessors;

use OpenApi\Analysis;
use OpenApi\Generator;

/**
 * Adds "additionalProperties": false to each schema if it's not set
 */
class DisableAdditionalProperties
{
    public function __invoke(Analysis $analysis)
    {
        if (is_object($analysis->openapi->components) && is_iterable($analysis->openapi->components->schemas)) {
            foreach ($analysis->openapi->components->schemas as $key => &$schema) {
                if ($schema->additionalProperties === Generator::UNDEFINED) {
                    $schema->additionalProperties = false;
                }
            }
        }
    }
}
schema.AdditionalPropertiesAllowed = true;
Dragging answered 3/10, 2024 at 15:48 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.