question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

property: Optional[ComplexObject] = field(None, nullable=True) doesn't create a nullable field in openapi spec

See original GitHub issue

First check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn’t find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google “How to X in FastAPI” and didn’t find any information.
  • I already read and followed all the tutorial in the docs and didn’t find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.
  • After submitting this, I commit to one of:
    • Read open issues with questions until I find 2 issues where I can help someone and add a comment to help there.
    • I already hit the “watch” button in this repository to receive notifications and I commit to help at least 2 people that ask questions in the future.
    • Implement a Pull Request for a confirmed bug.

Example

Here’s a self-contained, minimal, reproducible, example with my use case:

import enum

from typing import Optional

import pytest

from fastapi import FastAPI
from pydantic import BaseModel, Field


app = FastAPI()


class RHELVersions(enum.Enum):
    """Available RHEL versions within the database."""

    el7: str = "RHEL 7"
    el8: str = "RHEL 8"
    el9: str = "RHEL 9"


class DeviceEntry(BaseModel):
    """A model which represents the single hardware device."""

    simple_property: Optional[bool] = Field(None, nullable=True)
    complex_property: Optional[RHELVersions] = Field(None, nullable=True)


@app.get("/", response_model=DeviceEntry)
def read_root() -> DeviceEntry:
    return DeviceEntry(simple_property=None, complex_property=None)


def test_case():
    spec = app.openapi()
    assert spec["components"]["schemas"]["DeviceEntry"]["properties"][
        "simple_property"
    ]["nullable"]
    with pytest.raises(KeyError):
        assert spec["components"]["schemas"]["DeviceEntry"]["properties"][
            "complex_property"
        ]["nullable"]


"""
  +  'components': {'schemas': {'DeviceEntry': {'description': 'A model which '
  +                                                            'represents the '
  +                                                            'single hardware '
  +                                                            'device.',
  +                                             'properties': {'complex_property': {'$ref': '#/components/schemas/RHELVersions'},
  +                                                            'simple_property': {'nullable': True,
  +                                                                                'title': 'Simple '
  +                                                                                         'Property',
  +                                                                                'type': 'boolean'}},
  +                                             'title': 'DeviceEntry',
  +                                             'type': 'object'},
"""

Description

Run pytest {path_tothe_module}. Simple property has nullable in the apispec, but complex property doesn’t.

Environment

  • OS: [e.g. Linux / Windows / macOS]: Linux
  • FastAPI Version [e.g. 0.3.0]: 0.62

To know the FastAPI version use:

python -c "import fastapi; print(fastapi.__version__)"
  • Python version: 3.9

To know the Python version use:

python --version

Additional context

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:7 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
Mausecommented, Dec 14, 2020

See the following example:


import enum

from typing import Optional

from pydantic import BaseModel


class RHELVersions(enum.Enum):
    """Available RHEL versions within the database."""

    el7: str = "RHEL 7"
    el8: str = "RHEL 8"
    el9: str = "RHEL 9"


class DeviceEntry(BaseModel):
    """A model which represents the single hardware device."""

    simple_property1: Optional[bool]
    complex_property1: Optional[RHELVersions]
    simple_property2: bool
    complex_property2: RHELVersions


assert DeviceEntry.schema() == {
    'definitions': {
        'RHELVersions': {
            'description': 'Available RHEL versions ' 'within the database.',
            'enum': ['RHEL 7', 'RHEL 8', 'RHEL 9'],
            'title': 'RHELVersions',
        }
    },
    'description': 'A model which represents the single hardware device.',
    'properties': {
        'complex_property1': {'$ref': '#/definitions/RHELVersions'},
        'complex_property2': {'$ref': '#/definitions/RHELVersions'},
        'simple_property1': {'title': 'Simple Property1', 'type': 'boolean'},
        'simple_property2': {'title': 'Simple Property2', 'type': 'boolean'},
    },
    'required': ['simple_property2', 'complex_property2'],
    'title': 'DeviceEntry',
    'type': 'object',
}

Note the required field - this how you mark whether a field is optional or not

0reactions
tiangolocommented, Dec 27, 2020

Thanks for the help here @Mause ! 👏 🙇

Thanks for reporting back and closing the issue @ZhukovGreen 👍

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to define a property that can be string or null in OpenAPI ...
The nullable keyword used in OAS 3.0.x (see below) does not exist in OAS 3.1, it was removed in favor of the 'null'...
Read more >
How to manage nullable properties - Jane - Read the Docs
By doing this, any property of your schema will be considered nullable. ... OpenAPI v3 still does not support null type but added...
Read more >
OpenAPI Specification - Version 3.0.3 - Swagger
The schema exposes two types of fields: Fixed fields, which have a declared name, and Patterned fields, which declare a regex pattern for...
Read more >
OpenAPI Specification v3.0.3 | Introduction, Definitions, & More
The OpenAPI Specification allows combining and extending model definitions using the allOf property of JSON Schema, in effect offering model ...
Read more >
required but nullable field reported as error — Bitbucket
type: object required: - id - name - type - company - primaryContact properties: id: type: string name: type: string type: type: string ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found