Skip to content

fix(api): support --body alias for raw requests#504

Open
hiSandog wants to merge 1 commit intolarksuite:mainfrom
hiSandog:fix/api-body-alias-20260416
Open

fix(api): support --body alias for raw requests#504
hiSandog wants to merge 1 commit intolarksuite:mainfrom
hiSandog:fix/api-body-alias-20260416

Conversation

@hiSandog
Copy link
Copy Markdown

@hiSandog hiSandog commented Apr 16, 2026

Summary

  • accept --body as an alias for --data in the raw api command
  • route both flags through the same request-building path so multipart and stdin handling stay consistent
  • reject conflicting --data and --body values with a validation error

Validation

  • env GOCACHE=/tmp/cli-gocache GOMODCACHE=/tmp/cli-gomodcache go test ./cmd/api

Context

README examples currently show --body, while the command only accepted --data. An open docs PR already fixes the examples; this change makes the CLI itself tolerant of the documented flag without overlapping that PR.

Summary by CodeRabbit

New Features

  • Introduced --body flag as an alternative option to --data for specifying request body content in API requests.
  • Enhanced validation to prevent simultaneous use of both --data and --body flags when set to different values; using both simultaneously will return an error indicating the conflict.

@CLAassistant
Copy link
Copy Markdown

CLAassistant commented Apr 16, 2026

CLA assistant check
All committers have signed the CLA.

@github-actions github-actions bot added the size/L Large or sensitive change across domains or core paths label Apr 16, 2026
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 16, 2026

📝 Walkthrough

Walkthrough

A new --body flag is introduced as an alias for --data in the API command, along with conflict resolution logic that prevents simultaneous use of both flags with different values. Request construction updates use the resolved flag across validation, stdin detection, and JSON parsing paths. Two tests verify correct alias behavior and conflict error handling.

Changes

Cohort / File(s) Summary
Body Flag Implementation
cmd/api/api.go
Added Body string field to APIOptions; introduced resolveBodyFlag(data, body string) function to reconcile conflicting flag values; updated request construction to use resolved body flag in file validation, stdin conflict detection, form field parsing, and JSON body parsing.
Body Flag Tests
cmd/api/api_test.go
Added TestBuildAPIRequest_BodyAlias to verify alias functionality with JSON decoding; added TestBuildAPIRequest_DataAndBodyConflict to validate error handling and messaging when both flags are set simultaneously.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 A second name for data's call,
--body answers, flag for all!
Conflicts caught with gentle care,
One flag wins when both laid bare. ✨

🚥 Pre-merge checks | ✅ 1 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 28.57% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive The description covers the main changes and validation approach, but uses a non-standard format that doesn't match the required template structure. Reorganize the description to follow the template: use 'Summary', 'Changes' (as a bulleted list), 'Test Plan' (with checkboxes), and 'Related Issues' sections.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed The title 'fix(api): support --body alias for raw requests' clearly and concisely summarizes the main change: adding --body as an alias for --data in the API command.

✏️ 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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
cmd/api/api.go (1)

162-169: ⚠️ Potential issue | 🟡 Minor

--body users can still get --data-only validation messages.

After alias resolution, this flow can be reached via --body, but Line 168 still says --data, and ParseOptionalBody errors (invoked at Line 163 and Line 189) also report --data. Please emit --data/--body (or pass a flag label) so guidance stays accurate for users and automation.

Suggested direction
- return client.RawApiRequest{}, nil, output.ErrValidation("--data must be a JSON object when used with --file")
+ return client.RawApiRequest{}, nil, output.ErrValidation("--data/--body must be a JSON object when used with --file")

And consider adding a ParseOptionalBodyWithFlag(flagName, ...) variant so invalid-JSON/resolve-input errors can mention --data/--body in this command path.

As per coding guidelines: "Error messages must be structured, actionable, and specific since they will be parsed by AI agents to determine next actions."

Also applies to: 189-190

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

In `@cmd/api/api.go` around lines 162 - 169, The validation/error text wrongly
references only "--data" even when the input came via the "--body" alias; update
the code paths that call ParseOptionalBody (the dataFlag handling using variable
dataFlag and the later call that also invokes ParseOptionalBody) to surface the
correct flag name by either (a) passing a flag label into a new
ParseOptionalBodyWithFlag(flagName, method, flagValue, stdin) and use that in
error returns, or (b) build the error strings dynamically from dataFlag (or an
explicit flagName variable) so the output.ErrValidation and any
ParseOptionalBody error messages mention "--data/--body" (or the actual flag
used) instead of always "--data"; ensure you update both call sites that
currently call ParseOptionalBody to use the new variant or dynamic flag-aware
error text and change the ErrValidation message reference (the return that
currently uses output.ErrValidation("--data must be a JSON object when used with
--file")) to include the correct flag label.
🧹 Nitpick comments (2)
cmd/api/api_test.go (2)

117-120: Add explicit config-dir isolation in these new tests.

Please set LARKSUITE_CLI_CONFIG_DIR via t.Setenv in each new test before creating the factory, to keep test config state isolated.

Suggested patch
 func TestBuildAPIRequest_BodyAlias(t *testing.T) {
+	t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir())
 	f, _, _, _ := cmdutil.TestFactory(t, &core.CliConfig{
 		AppID: "test-app", AppSecret: "test-secret", Brand: core.BrandFeishu,
 	})
@@
 func TestBuildAPIRequest_DataAndBodyConflict(t *testing.T) {
+	t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir())
 	f, _, _, _ := cmdutil.TestFactory(t, &core.CliConfig{
 		AppID: "test-app", AppSecret: "test-secret", Brand: core.BrandFeishu,
 	})

As per coding guidelines: "**/*_test.go: Isolate config state in Go tests by using t.Setenv(\"LARKSUITE_CLI_CONFIG_DIR\", t.TempDir())."

Also applies to: 143-146

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

In `@cmd/api/api_test.go` around lines 117 - 120, The new tests (e.g.,
TestBuildAPIRequest_BodyAlias) do not isolate config state; before calling
cmdutil.TestFactory(t, ...) set the LARKSUITE_CLI_CONFIG_DIR environment to a
temp dir using t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir()) so each test
gets its own config directory; apply the same change to the other affected
test(s) around the TestBuildAPIRequest_* functions (the places that call
cmdutil.TestFactory) so factory creation happens after t.Setenv is called.

143-161: Consider adding a non-conflict parity test (--data == --body).

You currently assert the differing-values conflict; a same-value case would lock the intended “allowed” behavior and prevent regressions in resolveBodyFlag.

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

In `@cmd/api/api_test.go` around lines 143 - 161, Add a new unit test (e.g.,
TestBuildAPIRequest_DataAndBodyParity) that mirrors
TestBuildAPIRequest_DataAndBodyConflict but sets APIOptions.Data and
APIOptions.Body to the identical JSON string and asserts buildAPIRequest returns
no error and the resolved request body equals that string; locate the test
helper/TestFactory usage and call buildAPIRequest (same symbol) and also
validate resolveBodyFlag behavior indirectly by checking the request body or
returned payload to ensure parity is allowed and preserved.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@cmd/api/api.go`:
- Around line 162-169: The validation/error text wrongly references only
"--data" even when the input came via the "--body" alias; update the code paths
that call ParseOptionalBody (the dataFlag handling using variable dataFlag and
the later call that also invokes ParseOptionalBody) to surface the correct flag
name by either (a) passing a flag label into a new
ParseOptionalBodyWithFlag(flagName, method, flagValue, stdin) and use that in
error returns, or (b) build the error strings dynamically from dataFlag (or an
explicit flagName variable) so the output.ErrValidation and any
ParseOptionalBody error messages mention "--data/--body" (or the actual flag
used) instead of always "--data"; ensure you update both call sites that
currently call ParseOptionalBody to use the new variant or dynamic flag-aware
error text and change the ErrValidation message reference (the return that
currently uses output.ErrValidation("--data must be a JSON object when used with
--file")) to include the correct flag label.

---

Nitpick comments:
In `@cmd/api/api_test.go`:
- Around line 117-120: The new tests (e.g., TestBuildAPIRequest_BodyAlias) do
not isolate config state; before calling cmdutil.TestFactory(t, ...) set the
LARKSUITE_CLI_CONFIG_DIR environment to a temp dir using
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir()) so each test gets its own
config directory; apply the same change to the other affected test(s) around the
TestBuildAPIRequest_* functions (the places that call cmdutil.TestFactory) so
factory creation happens after t.Setenv is called.
- Around line 143-161: Add a new unit test (e.g.,
TestBuildAPIRequest_DataAndBodyParity) that mirrors
TestBuildAPIRequest_DataAndBodyConflict but sets APIOptions.Data and
APIOptions.Body to the identical JSON string and asserts buildAPIRequest returns
no error and the resolved request body equals that string; locate the test
helper/TestFactory usage and call buildAPIRequest (same symbol) and also
validate resolveBodyFlag behavior indirectly by checking the request body or
returned payload to ensure parity is allowed and preserved.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: a5f6c5c2-1a30-4691-8f5c-49d83aa64be9

📥 Commits

Reviewing files that changed from the base of the PR and between e10bf8e and 320eb21.

📒 Files selected for processing (2)
  • cmd/api/api.go
  • cmd/api/api_test.go

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

Labels

size/L Large or sensitive change across domains or core paths

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants