Skip to content

Support local HTTP ref paths#3116

Merged
koxudaxi merged 5 commits into
mainfrom
fix/issue-3103-local-http-ref-path
May 7, 2026
Merged

Support local HTTP ref paths#3116
koxudaxi merged 5 commits into
mainfrom
fix/issue-3103-local-http-ref-path

Conversation

@koxudaxi

@koxudaxi koxudaxi commented May 2, 2026

Copy link
Copy Markdown
Owner

fixes: #3103

Summary by CodeRabbit

  • New Features

    • Added --http-local-ref-path CLI option to resolve HTTP(S) JSON Schema $ref URLs by mapping them to a local schema store.
  • Documentation

    • Added docs, examples, and CLI index entries for --http-local-ref-path.
    • Clarified --use-default behavior: field types respect schema nullability when --strict-nullable is enabled.
  • Tests

    • Added tests for local HTTP $ref resolution, error cases, security checks, and CLI documentation.

@coderabbitai

coderabbitai Bot commented May 2, 2026

Copy link
Copy Markdown

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 2bdb52cb-4d8a-40e6-805d-5c0e27875a3f

📥 Commits

Reviewing files that changed from the base of the PR and between 9ed0742 and 1833936.

📒 Files selected for processing (2)
  • src/datamodel_code_generator/parser/jsonschema.py
  • tests/parser/test_jsonschema.py
🚧 Files skipped from review as they are similar to previous changes (2)
  • tests/parser/test_jsonschema.py
  • src/datamodel_code_generator/parser/jsonschema.py

📝 Walkthrough

Walkthrough

Adds a new --http-local-ref-path option and plumbing to resolve HTTP(S) JSON Schema $ref URLs from a local schema store (host/path → files, try .json fallback), plus tests and docs. Parser uses the configured path to load matching local files instead of fetching remote URLs.

Changes

Local HTTP Reference Resolution

Layer / File(s) Summary
Configuration & Type Definitions
src/datamodel_code_generator/__main__.py, src/datamodel_code_generator/config.py, src/datamodel_code_generator/_types/generate_config_dict.py, src/datamodel_code_generator/_types/parser_config_dicts.py
Added optional `http_local_ref_path: Path
CLI & Argument Parsing
src/datamodel_code_generator/arguments.py, src/datamodel_code_generator/cli_options.py, src/datamodel_code_generator/prompt_data.py
Defined --http-local-ref-path CLI argument and help; added CLI metadata and option description.
Parser Initialization & Integration
src/datamodel_code_generator/parser/base.py, src/datamodel_code_generator/__main__.py
Parser stores self.http_local_ref_path from config; run_generate_from_config forwards config.http_local_ref_path to generate.
Core Reference Resolution
src/datamodel_code_generator/parser/jsonschema.py
When configured, HTTP(S) $ref resolution routes to _get_ref_body_from_local_http_path() which parses URL, validates scheme/path, maps netloc+path to candidate files under the base dir (and a .json fallback), prevents directory-escape, loads first match into remote_object_cache, and raises Error if none found. Existing non-HTTP handling and remote logic remain.
Public API Baseline & Tests
tests/main/test_public_api_signature_baseline.py, tests/parser/test_jsonschema.py, tests/test_main_kr.py, tests/data/expected/...
Baseline signatures updated to include new kwarg; extensive tests added for local HTTP ref resolution (with/without extension, invalid paths, missing files, non-HTTP schemes, symlink escape), a CLI doc test, and expected generated output for the example.
Documentation
docs/cli-reference/general-options.md, docs/cli-reference/index.md, docs/cli-reference/quick-reference.md, docs/cli-reference/model-customization.md
Added --http-local-ref-path docs, usage/example and index updates; clarified --use-default interaction with --strict-nullable.

Sequence Diagram

sequenceDiagram
    participant CLI as CLI Argument Parser
    participant Config as Config / Generate
    participant Parser as JsonSchema Parser
    participant RefLoader as Ref Body Loader
    participant FileSystem as Local Filesystem
    participant Cache as Remote Object Cache

    CLI->>Config: supply --http-local-ref-path
    Config->>Parser: include http_local_ref_path in config
    Parser->>Parser: set self.http_local_ref_path
    Parser->>RefLoader: encounter HTTP(S) $ref URL
    RefLoader->>RefLoader: is http_local_ref_path set?
    alt set
        RefLoader->>RefLoader: parse URL (netloc, path)
        RefLoader->>FileSystem: map netloc/path → candidate files
        FileSystem-->>RefLoader: check existence
        alt candidate exists
            FileSystem-->>RefLoader: read file content
            RefLoader->>Cache: store in remote cache
            Cache-->>RefLoader: return schema dict
        else try .json fallback
            FileSystem-->>RefLoader: read suffixed file or not found
            alt found
                RefLoader->>Cache: store and return
            else
                RefLoader->>RefLoader: raise Error (include URL)
            end
        end
    else not set
        RefLoader->>RefLoader: perform normal remote fetch logic
    end
    RefLoader-->>Parser: return schema dict or raise
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested labels

breaking-change-analyzed

Suggested reviewers

  • Raekkeri
  • ilovelinux

"🐰
A local path for refs so grand,
No more fetches to far-off land,
Host and path mapped, .json may play,
Air-gapped schemas find their way,
Hopping tests and docs hooray!"

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The pull request title 'Support local HTTP ref paths' clearly and concisely summarizes the main change: adding support for resolving HTTP(S) $ref URLs from local schema files.
Linked Issues check ✅ Passed The pull request successfully implements the core requirements from issue #3103: a new --http-local-ref-path CLI option that resolves HTTP(S) $ref URLs by mapping them to local schema files using host/path-based directory structure, with proper error handling for missing or invalid paths.
Out of Scope Changes check ✅ Passed All changes are directly related to implementing the --http-local-ref-path feature. A minor documentation update to --use-default behavior is consistent with issue clarifications and does not constitute out-of-scope work.
Docstring Coverage ✅ Passed Docstring coverage is 83.33% which is sufficient. The required threshold is 80.00%.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/issue-3103-local-http-ref-path

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
Review rate limit: 2/8 reviews remaining, refill in 38 minutes and 34 seconds.

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

@github-actions

github-actions Bot commented May 2, 2026

Copy link
Copy Markdown
Contributor

📚 Docs Preview: https://pr-3116.datamodel-code-generator.pages.dev

@codspeed-hq

codspeed-hq Bot commented May 2, 2026

Copy link
Copy Markdown

Merging this PR will not alter performance

⚠️ Unknown Walltime execution environment detected

Using the Walltime instrument on standard Hosted Runners will lead to inconsistent data.

For the most accurate results, we recommend using CodSpeed Macro Runners: bare-metal machines fine-tuned for performance measurement consistency.

✅ 11 untouched benchmarks
⏩ 98 skipped benchmarks1


Comparing fix/issue-3103-local-http-ref-path (1833936) with main (e7d1dea)

Open in CodSpeed

Footnotes

  1. 98 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports.

@codecov

codecov Bot commented May 2, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (160e507) to head (1833936).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff            @@
##              main     #3116   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           88        88           
  Lines        18325     18419   +94     
  Branches      2117      2126    +9     
=========================================
+ Hits         18325     18419   +94     
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.

@koxudaxi koxudaxi marked this pull request as ready for review May 2, 2026 09:03

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

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

5275-5277: ⚡ Quick win

Clarify dependency on --strict-nullable for nullability preservation.

The documentation states that field types follow the schema's nullability, but based on the code evidence this behavior only occurs when --strict-nullable is enabled. Without --strict-nullable, fields with defaults receive nullable=None, making them Optional regardless of the schema's nullability specification.

Consider adding a brief mention of this dependency in the main explanation text, for example:

 The field type still follows the schema's nullability. For example, a required
 string field with a default is generated as `str = 'value'`, not
-`str | None = 'value'`, unless the schema allows null.
+`str | None = 'value'`, unless the schema allows null. This behavior is
+controlled by the `--strict-nullable` flag.

Alternatively, you could phrase it as: "When combined with --strict-nullable, the field type follows..." to make the dependency more explicit.

As per coding guidelines, the code snippet from src/datamodel_code_generator/parser/jsonschema.py:1239 shows that nullable preservation depends on the strict_nullable configuration: nullable=... (False if self.strict_nullable and (has_default or required) else None).

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

In `@docs/cli-reference/model-customization.md` around lines 5275 - 5277, The docs
claim field types follow the schema's nullability but omit that this only
happens when the strict_nullable config/flag is enabled; update the explanatory
text around the example to explicitly state that nullability preservation
depends on --strict-nullable (or the strict_nullable setting) — e.g. add a
sentence like "When --strict-nullable (strict_nullable) is enabled, the field
type follows the schema's nullability; otherwise fields with defaults get
nullable=None and will be treated as Optional." Reference the strict_nullable
configuration and the nullable=... expression in the JSONSchema parser (nullable
logic in jsonschema.py) so readers can correlate the behavior with the flag.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@docs/cli-reference/general-options.md`:
- Around line 1653-1690: The example for --http-local-ref-path is misleading
because the JSON Schema has no HTTP $ref; update the example to include a schema
that uses an HTTP $ref (for example a root schema that $ref's
"https://api.example.com/schemas/pet.json") and show the corresponding local
schema-store layout and filenames that mirror that HTTP path (e.g.,
schema-store/schemas/pet.json) so readers can see how the CLI redirects the HTTP
reference to the local file; update the Input Schema block to include the HTTP
$ref, adjust the generated Output block accordingly (e.g., still showing class
Pet produced by datamodel-codegen), and add a brief note or inline listing
demonstrating the schema-store directory structure to make the relocation
behavior explicit.

In `@src/datamodel_code_generator/parser/jsonschema.py`:
- Around line 3852-3858: The current local HTTP $ref handling (involving parsed,
parts, unquote, Path, relative_path and file_paths) allows URL-decoded
backslashes to act as separators on Windows; update the validation to reject any
path segment that contains '/' or '\\' (in addition to "." and "..") after
unquoting, then construct relative_path and compute resolved =
(self.http_local_ref_path / relative_path).resolve() and ensure
resolved.is_relative_to(self.http_local_ref_path.resolve()) before using it; if
the check fails raise Error with the original ref to block path-traversal or
symlink-based escapes.

---

Nitpick comments:
In `@docs/cli-reference/model-customization.md`:
- Around line 5275-5277: The docs claim field types follow the schema's
nullability but omit that this only happens when the strict_nullable config/flag
is enabled; update the explanatory text around the example to explicitly state
that nullability preservation depends on --strict-nullable (or the
strict_nullable setting) — e.g. add a sentence like "When --strict-nullable
(strict_nullable) is enabled, the field type follows the schema's nullability;
otherwise fields with defaults get nullable=None and will be treated as
Optional." Reference the strict_nullable configuration and the nullable=...
expression in the JSONSchema parser (nullable logic in jsonschema.py) so readers
can correlate the behavior with the flag.
🪄 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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: a7d642b9-ec18-4a20-949a-6252943ddee7

📥 Commits

Reviewing files that changed from the base of the PR and between 318aa46 and 3683fb2.

⛔ Files ignored due to path filters (7)
  • tests/data/expected/main/help/color.txt is excluded by !tests/data/**/*.txt and included by none
  • tests/data/expected/main/help/no_color.txt is excluded by !tests/data/**/*.txt and included by none
  • tests/data/expected/main_kr/generate_prompt/basic.txt is excluded by !tests/data/**/*.txt and included by none
  • tests/data/expected/main_kr/generate_prompt/with_list_options.txt is excluded by !tests/data/**/*.txt and included by none
  • tests/data/expected/main_kr/generate_prompt/with_options.txt is excluded by !tests/data/**/*.txt and included by none
  • tests/data/expected/main_kr/generate_prompt/with_question.txt is excluded by !tests/data/**/*.txt and included by none
  • tests/data/expected/main_kr/help_shows_new_options.txt is excluded by !tests/data/**/*.txt and included by none
📒 Files selected for processing (17)
  • docs/cli-reference/general-options.md
  • docs/cli-reference/index.md
  • docs/cli-reference/model-customization.md
  • docs/cli-reference/quick-reference.md
  • src/datamodel_code_generator/__main__.py
  • src/datamodel_code_generator/_types/generate_config_dict.py
  • src/datamodel_code_generator/_types/parser_config_dicts.py
  • src/datamodel_code_generator/arguments.py
  • src/datamodel_code_generator/cli_options.py
  • src/datamodel_code_generator/config.py
  • src/datamodel_code_generator/parser/base.py
  • src/datamodel_code_generator/parser/jsonschema.py
  • src/datamodel_code_generator/prompt_data.py
  • tests/data/expected/main/input_model/config_class.py
  • tests/main/test_public_api_signature_baseline.py
  • tests/parser/test_jsonschema.py
  • tests/test_main_kr.py

Comment thread docs/cli-reference/general-options.md
Comment thread src/datamodel_code_generator/parser/jsonschema.py Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/datamodel_code_generator/parser/jsonschema.py`:
- Around line 3893-3894: The code currently redirects all non-file refs to the
local-HTTP resolver when self.http_local_ref_path is set; update the conditional
to only call _get_ref_body_from_local_http_path(ref) when the ref's URL scheme
is 'http' or 'https' (e.g., parse ref with urllib.parse.urlparse and check
scheme in ('http','https')), leaving other schemes untouched so they follow the
existing resolution path.
🪄 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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 9aac966d-f76c-4c8b-b835-705458331419

📥 Commits

Reviewing files that changed from the base of the PR and between 3683fb2 and 9ed0742.

⛔ Files ignored due to path filters (1)
  • tests/data/jsonschema/http_local_ref_path_root.json is excluded by !tests/data/**/*.json and included by none
📒 Files selected for processing (7)
  • docs/cli-reference/general-options.md
  • docs/cli-reference/model-customization.md
  • src/datamodel_code_generator/parser/jsonschema.py
  • tests/data/expected/main_kr/http_local_ref_path/output.py
  • tests/main/jsonschema/test_main_jsonschema.py
  • tests/parser/test_jsonschema.py
  • tests/test_main_kr.py
✅ Files skipped from review due to trivial changes (3)
  • tests/data/expected/main_kr/http_local_ref_path/output.py
  • docs/cli-reference/general-options.md
  • tests/main/jsonschema/test_main_jsonschema.py
🚧 Files skipped from review as they are similar to previous changes (3)
  • tests/test_main_kr.py
  • docs/cli-reference/model-customization.md
  • tests/parser/test_jsonschema.py

Comment thread src/datamodel_code_generator/parser/jsonschema.py Outdated
@koxudaxi koxudaxi merged commit b53abee into main May 7, 2026
44 checks passed
@koxudaxi koxudaxi deleted the fix/issue-3103-local-http-ref-path branch May 7, 2026 06:40
@github-actions

github-actions Bot commented May 7, 2026

Copy link
Copy Markdown
Contributor

Breaking Change Analysis

Result: No breaking changes detected

Reasoning: PR #3116 is a purely additive feature. It adds a new --http-local-ref-path CLI option that defaults to None. When not provided, all code paths remain identical to previous behavior. No existing CLI options were removed or renamed, no generated output format changed, no default behavior changed, and no existing API signatures were modified. The new config fields all use Optional with None defaults or NotRequired in TypedDicts. The only behavioral change (bypassing allow_remote_refs checks for HTTP refs) only activates when the new option is explicitly provided, so it cannot affect existing users.


This analysis was performed by Claude Code Action

@github-actions

github-actions Bot commented May 7, 2026

Copy link
Copy Markdown
Contributor

🎉 Released in 0.57.0

This PR is now available in the latest release. See the release notes for details.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support for local redirection for json schema $ref with http[s]:// uris

1 participant