# schema-no-optional-nullable-properties

Source: https://api-genie.dev/docs/linter/openapi/rules/schema-no-optional-nullable-properties

A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error.

This rule disallows schema properties that are both optional and nullable.

## Rule details

An optional nullable property represents an absent value in two ways: the property
may be omitted, or it may be present with the value `null`. Requiring a property
to be nullable or allowing it to be omitted makes the API contract unambiguous.

A property is nullable when its schema, or the schema it references, allows `null`:

- a `null` type, e.g. `type: [string, 'null']`;
- `nullable: true` in OpenAPI 3.0 documents;
- `null` in `enum` or as `const`;
- an `anyOf` or `oneOf` branch allowing `null`, e.g. `anyOf: [{$ref: ...}, {type: 'null'}]`;
- an `allOf` whose every member allows `null`.

A property counts as required when the schema, one of its `allOf` members, or a schema
using it in `allOf` lists it in `required`.

In `PATCH` request bodies and `application/merge-patch+json` documents, `null` means
"remove this value" (RFC 7396), so optional nullable properties are expected there and
the rule skips them and every schema they contain. Turn the rule off when omission and an
explicit `null` mean two different things in your API.

## Configuration

An object with one optional property:

- `ignorePatchBodies`: skip the schemas of `PATCH` request bodies and merge-patch
  documents. Defaults to `true`.

```yaml
commands:
  lint:
    rules:
      schema-no-optional-nullable-properties:
        - warning
        - ignorePatchBodies: false
```

## Examples

**Good**. The nullable property is required.

```yaml
components:
  schemas:
    User:
      type: object
      required: [middleName]
      properties:
        middleName:
          type: [string, 'null']
```

**Good**. The optional property cannot be `null`.

```yaml
components:
  schemas:
    User:
      type: object
      properties:
        middleName:
          type: string
```

**Bad**. `middleName` can be omitted or set to `null`.

```yaml
components:
  schemas:
    User:
      type: object
      properties:
        middleName:
          type: [string, 'null']
```
