Skip to content

Expose plain arguments#454

Merged
koxudaxi merged 12 commits intokoxudaxi:mainfrom
LuisHsu:master
Apr 27, 2026
Merged

Expose plain arguments#454
koxudaxi merged 12 commits intokoxudaxi:mainfrom
LuisHsu:master

Conversation

@LuisHsu
Copy link
Copy Markdown
Contributor

@LuisHsu LuisHsu commented Oct 18, 2024

Sometimes the argument may need to forward to other user-defined interface, and the argument type will lead to syntax error.
Expose argument name only for such purpose.

Summary by CodeRabbit

  • New Features

    • Added --include-request-argument CLI flag to include a FastAPI Request argument in generated operation function signatures, enabling access to HTTP request context.
  • Documentation

    • Updated README, CLI reference, and help documentation to include the new --include-request-argument flag with usage examples.

@codecov-commenter
Copy link
Copy Markdown

codecov-commenter commented Oct 18, 2024

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (67bb774) to head (7e8b251).
⚠️ Report is 19 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff            @@
##              main      #454   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           16        16           
  Lines         1064      1105   +41     
  Branches       110       111    +1     
=========================================
+ Hits          1064      1105   +41     
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.

@PainOchoco
Copy link
Copy Markdown

I'm interested in this! Is there an already existing solution?

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 27, 2026

Warning

Rate limit exceeded

@koxudaxi has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 0 minutes and 15 seconds before requesting another review.

To keep reviews running without waiting, you can enable usage-based add-on for your organization. This allows additional reviews beyond the hourly cap. Account admins can enable it under billing.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 48a4f066-9ef3-4243-9612-61f1dda080a9

📥 Commits

Reviewing files that changed from the base of the PR and between 3eba7f9 and 7e8b251.

📒 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/parser.py
  • fastapi_code_generator/prompt_data.py
  • tests/data/expected/openapi/coverage/model_options/main.py
  • tests/data/expected/openapi/default_template/body_and_parameters/main.py
  • tests/main/test_main.py

Walkthrough

The PR adds a new CLI flag --include-request-argument to enable automatic injection of a FastAPI Request argument into generated operation signatures. The parameter flows through configuration, CLI parsing, and parser initialization to conditionally modify code generation behavior.

Changes

Cohort / File(s) Summary
Documentation
README.md, docs/cli-reference.md, docs/index.md, docs/llms-full.txt
Updated CLI help snapshots and reference documentation to include the new --include-request-argument flag with explanation and usage examples.
Type Definitions
fastapi_code_generator/_types/generate_config_dict.py
Added optional include_request_argument: NotRequired[bool] field to GenerateConfigDict TypedDict.
CLI & Configuration
fastapi_code_generator/cli.py, fastapi_code_generator/config.py
Added include_request_argument boolean parameter to CLI main() and generate_code() functions; wired into GenerateConfig model with CLI metadata and default False value.
Parser Core Logic
fastapi_code_generator/parser.py
Refactored Argument to introduce resolved_type_hint property; added Operation.plain_arguments and Operation.plain_parameters properties; extended OpenAPIParser.__init__() to accept include_request_argument option and conditionally inject request: Request argument via get_argument_list().
Tests
tests/main/test_main.py, tests/test_config.py
Added comprehensive test coverage for new plain_arguments and plain_parameters properties, and for --include-request-argument CLI flag behavior including Request argument injection into generated signatures.

Sequence Diagram

sequenceDiagram
    participant CLI as CLI Invocation
    participant Config as GenerateConfig
    participant Parser as OpenAPIParser
    participant Generator as Code Generator
    
    CLI->>Config: Pass --include-request-argument flag
    Config->>Parser: Initialize with include_request_argument=true
    Note over Parser: Flag stored in parser instance
    Parser->>Parser: get_argument_list() called
    alt include_request_argument enabled
        Parser->>Parser: Inject Request argument if missing
        Parser->>Parser: Add fastapi.Request import
    end
    Parser->>Generator: Provide operation with modified arguments
    Generator->>Generator: Generate code with request: Request parameter
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • Port workflow and docs automation stack #517: Introduced the core config/CLI/parser machinery that this PR extends by adding the include_request_argument field and wiring it through GenerateConfig, TypedDict, and OpenAPIParser.

Poem

🐰 A request for rabbits, now heard loud and clear,
With --include-request-argument brought near,
Through CLI and config, the magic threads flow,
To inject Request in each operation's glow,
Hop hop, the codegen's more capable now! 🎉

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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 PR title 'Expose plain arguments' directly describes the core feature being added: new properties (plain_arguments and plain_parameters) that expose argument names without full type annotations, allowing them to be forwarded to other interfaces without syntax errors.
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.

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 (5)
docs/cli-reference.md (1)

75-82: Documentation section added.

The new --include-request-argument reference section is consistent with other entries in this auto-generated doc.

Optional nit: the description could note that the Request argument is only injected when an operation does not already declare a parameter named request (per the guard in parser.py). Since this file is regenerated from cli_doc markers in tests/main/test_main.py, the wording would need to be updated at the marker's option_description.

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

In `@docs/cli-reference.md` around lines 75 - 82, The new
--include-request-argument doc text should state that the FastAPI Request
argument is only injected when an operation does not already declare a parameter
named "request" (this reflects the guard in parser.py), so update the
option_description marker used to generate this section in
tests/main/test_main.py to include that note; keep wording consistent with other
auto-generated entries and mention the parser.py behavior as the reason for the
conditional injection.
tests/main/test_main.py (2)

265-311: Test for plain_arguments/plain_parameters template variables.

The assertions exercise the new plain_arguments/plain_parameters accessors against snake_case_arguments for differentiation. Looks good.

Optional: consider adding a multi-parameter case (e.g., a required path parameter plus an optional query parameter) so the comma-separated rendering and ordering of the new accessors is also covered. The current single-parameter spec doesn't exercise the join logic.

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

In `@tests/main/test_main.py` around lines 265 - 311, Add a second scenario in
test_custom_template_can_use_plain_arguments to exercise multi-parameter
rendering: extend the OpenAPI spec (or create an additional test) to include two
parameters (e.g., a required path parameter and an optional query parameter with
a default) and regenerate using the same template_dir so the template variables
operations[0].plain_arguments and plain_parameters are rendered as a
comma-separated list; update assertions to expect the correct ordering and comma
separation (e.g., "pet_id, limit" for plain_arguments and corresponding type
annotations for plain_parameters) while keeping checks for snake_case_arguments
unchanged to verify differentiation.

314-345: Verify the asserted request: Request = ... rendering.

The assertion "request: Request = ..." in generated implies a default of ... in the rendered output, but the parser builds the argument as Argument(name='request', type_hint='Request', required=True) with no explicit default (per parser.py:454-461). If the template happens to render = ... for required arguments today, that's incidental — a stricter assertion would be "request: Request" in generated, which decouples the test from default-rendering behavior and won't break if the template changes.

♻️ Proposed tightening
-    assert "request: Request = ..." in generated
+    assert "request: Request" in generated
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/main/test_main.py` around lines 314 - 345, The test
test_include_request_argument currently asserts the exact string "request:
Request = ..." but the parser constructs Argument(name='request',
type_hint='Request', required=True) with no explicit default; update the
assertion to look for the presence of the type hint only (e.g., assert "request:
Request" in generated) so the test no longer depends on whether the template
renders a default value; modify the assertion in test_include_request_argument
accordingly to decouple it from default-rendering behavior.
fastapi_code_generator/cli.py (1)

93-93: Consider adding help= text to the new Typer option.

Most existing options in main() also omit help=, but this is a new flag whose behavior (auto-injecting a Request parameter into operation signatures, only when one is not already declared) isn't obvious from the name alone. Adding a short help string would surface in --help and the generated CLI snapshot:

♻️ Suggested addition
-    include_request_argument: bool = typer.Option(False, "--include-request-argument"),
+    include_request_argument: bool = typer.Option(
+        False,
+        "--include-request-argument",
+        help="Include a FastAPI Request argument in generated operation signatures.",
+    ),
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@fastapi_code_generator/cli.py` at line 93, The new Typer option
include_request_argument in main() (fastapi_code_generator/cli.py) lacks a help
string; update its Typer.Option declaration to add a concise help= description
that explains it will auto-inject a Request parameter into generated operation
function signatures when one isn't already declared (e.g., "Auto-inject a
FastAPI Request parameter into operations when not present"). Ensure the help
text is short and appears in CLI --help and generated snapshots.
fastapi_code_generator/parser.py (1)

198-211: plain_parameters drops defaults — confirm this is the intended behavior.

Unlike argument / snakecase, plain_parameters emits only name: type with no = default. For forwarding/declaration in user-defined interfaces this is fine, but if anyone wires this into a def {{ function_name }}({{ plain_parameters }}) template directly, an optional argument will lose its default and a required-after-optional order can produce a SyntaxError. Worth a note in the docstring/template docs that this is for forwarding only.

Also, the four Operation properties (arguments, snake_case_arguments, plain_arguments, plain_parameters) now all repeat Operation.merge_arguments_with_union(self.arguments_list). A tiny _merged_arguments cached property would centralize that and avoid recomputing the merge four times per operation in templates.

♻️ Optional refactor
+    `@cached_property`
+    def _merged_arguments(self) -> List[Argument]:
+        return Operation.merge_arguments_with_union(self.arguments_list)
+
     `@property`
     def arguments(self) -> str:  # pragma: no cover
-        sorted_arguments = Operation.merge_arguments_with_union(self.arguments_list)
-        return ", ".join(argument.argument for argument in sorted_arguments)
+        return ", ".join(argument.argument for argument in self._merged_arguments)

(apply the same substitution to snake_case_arguments, plain_arguments, plain_parameters).

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

In `@fastapi_code_generator/parser.py` around lines 198 - 211, The
plain_parameters property currently emits only "name: type" and drops default
values, which can break direct insertion into function definitions and cause
SyntaxError when optional arguments lose defaults; update plain_parameters (and
document in its docstring or template docs) to include default expressions where
present (e.g., "name: type = default") so optional/defaulted args are preserved,
and add a cached helper property (e.g., _merged_arguments) that returns
Operation.merge_arguments_with_union(self.arguments_list) and replace the
repeated calls in snake_case_arguments, plain_arguments, and plain_parameters to
use _merged_arguments to avoid recomputing the merge.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@fastapi_code_generator/parser.py`:
- Around line 454-464: The synthetic request argument appended by
include_request_argument becomes a positional-defaulted parameter and gets
argument.default = UsefulStr('...') and an inconsistent import; fix by inserting
the synthetic Argument(name='request', type_hint='Request', required=True) at
the front of the arguments list (or tag it so the positional-default rewrite
skips it) instead of appending, and ensure you add
Import.from_full_path("fastapi.Request") to imports_for_fastapi; also normalize
other places that currently add "starlette.requests.Request" to use
"fastapi.Request" so all generated code imports Request from fastapi.

---

Nitpick comments:
In `@docs/cli-reference.md`:
- Around line 75-82: The new --include-request-argument doc text should state
that the FastAPI Request argument is only injected when an operation does not
already declare a parameter named "request" (this reflects the guard in
parser.py), so update the option_description marker used to generate this
section in tests/main/test_main.py to include that note; keep wording consistent
with other auto-generated entries and mention the parser.py behavior as the
reason for the conditional injection.

In `@fastapi_code_generator/cli.py`:
- Line 93: The new Typer option include_request_argument in main()
(fastapi_code_generator/cli.py) lacks a help string; update its Typer.Option
declaration to add a concise help= description that explains it will auto-inject
a Request parameter into generated operation function signatures when one isn't
already declared (e.g., "Auto-inject a FastAPI Request parameter into operations
when not present"). Ensure the help text is short and appears in CLI --help and
generated snapshots.

In `@fastapi_code_generator/parser.py`:
- Around line 198-211: The plain_parameters property currently emits only "name:
type" and drops default values, which can break direct insertion into function
definitions and cause SyntaxError when optional arguments lose defaults; update
plain_parameters (and document in its docstring or template docs) to include
default expressions where present (e.g., "name: type = default") so
optional/defaulted args are preserved, and add a cached helper property (e.g.,
_merged_arguments) that returns
Operation.merge_arguments_with_union(self.arguments_list) and replace the
repeated calls in snake_case_arguments, plain_arguments, and plain_parameters to
use _merged_arguments to avoid recomputing the merge.

In `@tests/main/test_main.py`:
- Around line 265-311: Add a second scenario in
test_custom_template_can_use_plain_arguments to exercise multi-parameter
rendering: extend the OpenAPI spec (or create an additional test) to include two
parameters (e.g., a required path parameter and an optional query parameter with
a default) and regenerate using the same template_dir so the template variables
operations[0].plain_arguments and plain_parameters are rendered as a
comma-separated list; update assertions to expect the correct ordering and comma
separation (e.g., "pet_id, limit" for plain_arguments and corresponding type
annotations for plain_parameters) while keeping checks for snake_case_arguments
unchanged to verify differentiation.
- Around line 314-345: The test test_include_request_argument currently asserts
the exact string "request: Request = ..." but the parser constructs
Argument(name='request', type_hint='Request', required=True) with no explicit
default; update the assertion to look for the presence of the type hint only
(e.g., assert "request: Request" in generated) so the test no longer depends on
whether the template renders a default value; modify the assertion in
test_include_request_argument accordingly to decouple it from default-rendering
behavior.
🪄 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: 896cc482-876a-4c15-86e0-e941af3ca58f

📥 Commits

Reviewing files that changed from the base of the PR and between c6c1558 and 3eba7f9.

📒 Files selected for processing (10)
  • 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/parser.py
  • tests/main/test_main.py
  • tests/test_config.py

Comment thread fastapi_code_generator/parser.py
@koxudaxi koxudaxi merged commit 88b72cd into koxudaxi:main Apr 27, 2026
43 checks passed
@github-actions github-actions Bot added the breaking-change-analyzed PR has been checked for release draft updates label Apr 27, 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.

@koxudaxi koxudaxi mentioned this pull request Apr 27, 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.

4 participants