Skip to content

Add support for setting strict_nullable from CLI#493

Merged
koxudaxi merged 4 commits intokoxudaxi:mainfrom
greg80303:strict_nullable
Apr 28, 2026
Merged

Add support for setting strict_nullable from CLI#493
koxudaxi merged 4 commits intokoxudaxi:mainfrom
greg80303:strict_nullable

Conversation

@greg80303
Copy link
Copy Markdown

@greg80303 greg80303 commented Jun 19, 2025

datamodel-code-generator supports the OpenAPI 3.0 strict handling of nullable properties. Allow that to be enforced in code generation from the command line

Probably addresses issue #473

Summary by CodeRabbit

  • New Features

    • Added a new --strict-nullable CLI flag to toggle strict handling of nullable fields from OpenAPI schemas.
  • Documentation

    • Updated CLI reference, examples, and README to document the new flag and provide usage scenarios.
  • Tests

    • Added test scenarios and expected outputs covering strict nullable behavior and updated fixture inventory.

gregrutz-comcast and others added 2 commits June 19, 2025 15:08
`datamodel-code-generator` supports the OpenAPI 3.0 strict handling of nullable properties. Allow
that to be enforced in code generation from the command line
@greg80303
Copy link
Copy Markdown
Author

I see that this is a slightly different solution from the one proopsed in #474. Happy to have either merged.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 27, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 4bc2fae6-3c7d-4304-b24a-4c2ac5e22576

📥 Commits

Reviewing files that changed from the base of the PR and between 1a781df and 0b897c3.

📒 Files selected for processing (12)
  • README.md
  • docs/cli-reference.md
  • docs/index.md
  • docs/llms-full.txt
  • fastapi_code_generator/_types/generate_config_dict.py
  • fastapi_code_generator/cli.py
  • fastapi_code_generator/config.py
  • fastapi_code_generator/prompt_data.py
  • tests/data/expected/openapi/default_template/nullable_test/models.py
  • tests/data/expected/openapi/default_template/nullable_test_strict/models.py
  • tests/data/openapi/default_template/nullable_test.yaml
  • tests/main/test_main.py
✅ Files skipped from review due to trivial changes (6)
  • README.md
  • docs/index.md
  • fastapi_code_generator/_types/generate_config_dict.py
  • docs/cli-reference.md
  • tests/data/expected/openapi/default_template/nullable_test_strict/models.py
  • tests/data/expected/openapi/default_template/nullable_test/models.py

Walkthrough

Adds a new CLI flag --strict-nullable and propagates it through config types, CLI parsing, generate_code, and OpenAPIParser. Documentation, examples, tests, and expected generated fixtures for nullable handling were added or updated.

Changes

Cohort / File(s) Summary
Documentation
README.md, docs/cli-reference.md, docs/index.md, docs/llms-full.txt, docs/supported_formats.md
Add --strict-nullable to CLI help and reference, add usage example, and update fixture inventory counts (OpenAPI YAML 23→24, Default template 16→17).
Types & Config
fastapi_code_generator/_types/generate_config_dict.py, fastapi_code_generator/config.py
Add strict_nullable: bool to GenerateConfigDict TypedDict and GenerateConfig Pydantic model (default False) with CLI metadata.
CLI & Prompt Data
fastapi_code_generator/cli.py, fastapi_code_generator/prompt_data.py
Introduce --strict-nullable Typer option, thread strict_nullable through generate_code() to OpenAPIParser, and add PROMPT_DATA metadata and example for the new flag.
OpenAPI Fixture
tests/data/openapi/default_template/nullable_test.yaml
Add new OpenAPI spec demonstrating explicit nullable: true/false and an unmarked optional field for testing nullable handling.
Expected Generated Code
tests/data/expected/openapi/default_template/nullable_test/..., tests/data/expected/openapi/default_template/nullable_test_strict/...
Add expected FastAPI app and Pydantic User models for both non-strict and strict outputs reflecting nullable annotations and Field defaults/descriptions.
Tests
tests/main/test_main.py
Add integration test invoking generator with --strict-nullable against the new fixture and asserting generated output matches strict-mode golden files.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CLI
    participant Generator
    participant OpenAPIParser
    participant Filesystem

    User->>CLI: run with --strict-nullable
    CLI->>Generator: call generate_code(strict_nullable=True, ...)
    Generator->>OpenAPIParser: parse spec (strict_nullable=True)
    OpenAPIParser-->>Generator: return models/templates using strict nullable rules
    Generator->>Filesystem: write generated files (models.py, main.py, ...)
    Filesystem-->>User: generated project files
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related PRs

  • PR #517: Extends the GenerateConfig/TypedDict/CLI scaffolding that this PR builds upon for adding strict_nullable.
  • PR #534: Modifies configuration/type and prompt-data surfaces overlapping GenerateConfigDict and PROMPT_DATA edits.
  • PR #539: Changes fastapi_code_generator/prompt_data.py, which directly relates to the PROMPT_DATA additions here.

Suggested reviewers

  • koxudaxi

Poem

🐰 A flag hops into the CLI lair,
It tells models when nulls are fair,
From prompt to parser, through the code,
Tests and docs now mark the road,
Hooray — nullable handled with care!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Add support for setting strict_nullable from CLI' directly and clearly describes the main change: introducing a new CLI option to enable strict nullable handling during code generation.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov
Copy link
Copy Markdown

codecov Bot commented Apr 27, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (327e52e) to head (0b897c3).
⚠️ Report is 5 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff            @@
##              main      #493   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           17        17           
  Lines         1199      1204    +5     
  Branches       126       126           
=========================================
+ Hits          1199      1204    +5     
Flag Coverage Δ
unittests 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
docs/cli-reference.md (1)

92-99: LGTM — new section is consistent with the rest of the reference.

Optional nit: the inline help string copied across the snapshots ("Strictly follow nullable attributes in OpenAPI schemas.") is a bit ambiguous about what happens to fields without an explicit nullable attribute — the expanded prose here ("Respect explicit OpenAPI nullable flags when generating models.") is clearer. If you want to tighten the CLI help string, the source lives in fastapi_code_generator/cli.py and the snapshot in README.md / docs/index.md will follow.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs/cli-reference.md` around lines 92 - 99, Update the CLI help string for
the --strict-nullable option in fastapi_code_generator/cli.py (look for the
add_argument call or the argument named "--strict-nullable" / dest
"strict_nullable") to a clearer message such as "Respect explicit OpenAPI
nullable flags when generating models." so it accurately indicates behavior for
fields without an explicit nullable attribute; after updating, regenerate the
README.md/docs/index.md CLI snapshot so documentation matches the new help text.
fastapi_code_generator/cli.py (1)

93-97: Help text drifts from config metadata description.

The Typer help here says “Strictly follow nullable attributes in OpenAPI schemas.”, while the matching field in fastapi_code_generator/config.py (and the rendered docs in docs/llms-full.txt “Tested CLI Scenarios”, plus the cli_doc marker on the new test) describes it as “Respect explicit OpenAPI nullable flags when generating models.” Both are ultimately surfaced to users (one in --help, the other in the generated docs/scenarios). Consider aligning them so the CLI help and the docs say the same thing.

♻️ Proposed alignment (either direction works)
     strict_nullable: bool = typer.Option(
         False,
         "--strict-nullable",
-        help="Strictly follow nullable attributes in OpenAPI schemas.",
+        help="Respect explicit OpenAPI nullable flags when generating models.",
     ),
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@fastapi_code_generator/cli.py` around lines 93 - 97, The Typer option help
text for strict_nullable (the typer.Option declared in cli.py) is inconsistent
with the config field description in fastapi_code_generator/config.py and the
docs; update the help string for strict_nullable to match the canonical phrasing
used in the config/docs (e.g., "Respect explicit OpenAPI nullable flags when
generating models.") so CLI --help and generated docs stay aligned; confirm the
symbol strict_nullable and its typer.Option call are the only occurrences to
change.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@tests/data/expected/openapi/default_template/nullable_test_strict/models.py`:
- Around line 19-21: The fixture description for the field represented by the
nickname: Optional[str] = Field(None, description="User's nickname (implicitly
nullable)") is misleading under --strict-nullable because absence from required
makes it optional/absent, not nullable; update the source YAML/fixture
description for the nickname property to explicitly state it's optional but not
nullable under strict mode (e.g., "User's nickname (optional, not nullable under
strict mode)") so the generated model's Field(... description=...) accurately
reflects strict-nullable semantics.

---

Nitpick comments:
In `@docs/cli-reference.md`:
- Around line 92-99: Update the CLI help string for the --strict-nullable option
in fastapi_code_generator/cli.py (look for the add_argument call or the argument
named "--strict-nullable" / dest "strict_nullable") to a clearer message such as
"Respect explicit OpenAPI nullable flags when generating models." so it
accurately indicates behavior for fields without an explicit nullable attribute;
after updating, regenerate the README.md/docs/index.md CLI snapshot so
documentation matches the new help text.

In `@fastapi_code_generator/cli.py`:
- Around line 93-97: The Typer option help text for strict_nullable (the
typer.Option declared in cli.py) is inconsistent with the config field
description in fastapi_code_generator/config.py and the docs; update the help
string for strict_nullable to match the canonical phrasing used in the
config/docs (e.g., "Respect explicit OpenAPI nullable flags when generating
models.") so CLI --help and generated docs stay aligned; confirm the symbol
strict_nullable and its typer.Option call are the only occurrences to change.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 8d62d1d2-ef25-44d1-ab7f-435176510115

📥 Commits

Reviewing files that changed from the base of the PR and between c6c1558 and 1a781df.

📒 Files selected for processing (15)
  • README.md
  • docs/cli-reference.md
  • docs/index.md
  • docs/llms-full.txt
  • docs/supported_formats.md
  • fastapi_code_generator/_types/generate_config_dict.py
  • fastapi_code_generator/cli.py
  • fastapi_code_generator/config.py
  • fastapi_code_generator/prompt_data.py
  • tests/data/expected/openapi/default_template/nullable_test/main.py
  • tests/data/expected/openapi/default_template/nullable_test/models.py
  • tests/data/expected/openapi/default_template/nullable_test_strict/main.py
  • tests/data/expected/openapi/default_template/nullable_test_strict/models.py
  • tests/data/openapi/default_template/nullable_test.yaml
  • tests/main/test_main.py

@koxudaxi koxudaxi merged commit e9f2965 into koxudaxi:main Apr 28, 2026
43 checks passed
@github-actions github-actions Bot added the breaking-change-analyzed PR has been checked for release draft updates label Apr 28, 2026
@github-actions
Copy link
Copy Markdown
Contributor

Breaking Change Analysis

Result: No breaking changes detected

Reasoning: The breaking-change label is absent, so this PR is treated as a non-breaking release update.


This analysis was performed by repository automation using PR labels and the ## Breaking Changes section.

@coderabbitai coderabbitai Bot mentioned this pull request Apr 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

breaking-change-analyzed PR has been checked for release draft updates

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants