Skip to content

fix: openapi spec with example values - #6476

Merged
sid-bruno merged 3 commits into
usebruno:mainfrom
pooja-bruno:fix/import-openapi-spec-with-example
Jan 28, 2026
Merged

sid-bruno merged 3 commits into
usebruno:mainfrom
pooja-bruno:fix/import-openapi-spec-with-example

Conversation

@pooja-bruno

@pooja-bruno pooja-bruno commented Dec 22, 2025 •

Copy link
Copy Markdown
Collaborator

Description

This PR fixes two issues:

  • OpenAPI examples are now imported with their example values
  • The correct request body mode is now selected

JIRA: BRU-2242, BRU-2243

Contribution Checklist:

  • I've used AI significantly to create this pull request
  • The pull request only addresses one issue or adds one feature.
  • The pull request does not introduce any breaking changes
  • I have added screenshots or gifs to help explain the change if applicable.
  • I have read the contribution guidelines.
  • Create an issue and link to the pull request.

Summary by CodeRabbit

  • New Features

    • Schema-driven example/default generation for request bodies.
    • XML and SPARQL body generation and broader content-type support.
    • Centralized handler-based request body population for consistent examples.
  • Bug Fixes

    • Request body mode is always present and defaults consistently.
  • Tests

    • Extensive tests covering diverse OpenAPI content types, XML/SPARQL, multipart forms, and example-derived defaults.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai

coderabbitai Bot commented Dec 22, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Introduces schema-driven default value generation and XML body construction, centralizes per-MIME-type request-body population via handler mappings, updates example creation to carry requestBody schemas, expands tests for diverse content types, and fixes request body mode handling in Bruno request parsing.

Changes

Cohort / File(s) Summary
Body handling refactor
packages/bruno-converters/src/openapi/openapi-to-bruno.js
Added getDefaultValueForSchema(schema, visited), buildXmlBody(bodySchema), and BODY_TYPE_HANDLERS; refactored populateRequestBody() and createBrunoExample() to use schema-driven population and centralized MIME-type handlers; updated transformOpenapiRequestItem() to derive and route requestBodySchema.
Test coverage expansion
packages/bruno-converters/tests/openapi/openapi-to-bruno/openapi-body.spec.js
Added comprehensive tests covering many request body content types (wildcard/text, binary, XML, SPARQL, text, multipart/form-data, JSON variants), including default/example handling, XML generation, file-field detection, and array/no-items cases.
Bruno parser body-mode fix
packages/bruno-lang/v2/src/example/request/bruToJson.js
Ensures parseRequest(input) always returns a body object with a mode key (defaults to 'none') instead of omitting it for non-none modes.

Sequence Diagram(s)

(omitted — changes are internal library logic and do not introduce a multi-component sequential flow requiring visualization)

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • PR #6288: Modifies the same openapi-to-bruno.js area and overlaps schema-driven requestBody handling changes.
  • PR #6241: Alters transformOpenapiRequestItem and related request-body/query param handling in the same converter pipeline.

Suggested labels

size/XL

Suggested reviewers

  • helloanoop
  • lohit-bruno
  • naman-bruno
  • bijin-bruno

Poem

Default seeds in schema land,
XML blooms by careful hand,
Handlers gather every type,
Tests align to prove the pipe,
Small changes, tidy grand 🌿✨

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main objective: fixing OpenAPI spec handling to import example values correctly, which is the core purpose of the changeset.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

✨ Finishing touches
  • 📝 Generate docstrings

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
packages/bruno-converters/src/openapi/openapi-to-bruno.js (1)

183-230: Consider array handling in XML generation.

The function handles objects and primitives well. However, it doesn't explicitly handle arrays in properties. If OpenAPI schemas with array properties in XML bodies are expected, consider adding array handling logic.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 41efa85 and 419b70e.

📒 Files selected for processing (3)
  • packages/bruno-converters/src/openapi/openapi-to-bruno.js
  • packages/bruno-converters/tests/openapi/openapi-to-bruno/openapi-body.spec.js
  • packages/bruno-lang/v2/src/example/request/bruToJson.js
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (CODING_STANDARDS.md)

**/*.{js,jsx,ts,tsx}: Use 2 spaces for indentation. No tabs, just spaces
Stick to single quotes for strings. For JSX/TSX attributes, use double quotes (e.g., )
Always add semicolons at the end of statements
No trailing commas
Always use parentheses around parameters in arrow functions, even for single params
For multiline constructs, put opening braces on the same line, and ensure consistency. Minimum 2 elements for multiline
No newlines inside function parentheses
Space before and after the arrow in arrow functions. () => {} is good
No space between function name and parentheses. func() not func ()
Semicolons go at the end of the line, not on a new line
Names for functions need to be concise and descriptive
Add in JSDoc comments to add more details to the abstractions if needed
Add in meaningful comments instead of obvious ones where complex code flow is explained properly

Files:

  • packages/bruno-converters/tests/openapi/openapi-to-bruno/openapi-body.spec.js
  • packages/bruno-lang/v2/src/example/request/bruToJson.js
  • packages/bruno-converters/src/openapi/openapi-to-bruno.js
🧠 Learnings (3)
📚 Learning: 2025-12-05T20:31:33.005Z
Learnt from: CR
Repo: usebruno/bruno PR: 0
File: CODING_STANDARDS.md:0-0
Timestamp: 2025-12-05T20:31:33.005Z
Learning: Applies to **/*.test.{js,jsx,ts,tsx} : Add tests for any new functionality or meaningful changes. If code is added, removed, or significantly modified, corresponding tests should be updated or created

Applied to files:

  • packages/bruno-converters/tests/openapi/openapi-to-bruno/openapi-body.spec.js
📚 Learning: 2025-12-16T07:16:08.934Z
Learnt from: sanish-bruno
Repo: usebruno/bruno PR: 6090
File: tests/scripting/hooks/init-user-data/ui-state-snapshot.json:1-8
Timestamp: 2025-12-16T07:16:08.934Z
Learning: For e2e tests in the bruno repository: Collections that are shared between CLI and UI tests (comprehensive test suites testing core functionality) should be placed in `packages/bruno-tests/` to avoid duplication. The `tests/**/fixtures/collection` pattern should be used for test-specific collections that test particular UI behaviors or are specific to a single test file.

Applied to files:

  • packages/bruno-converters/tests/openapi/openapi-to-bruno/openapi-body.spec.js
📚 Learning: 2025-12-17T21:41:24.730Z
Learnt from: naman-bruno
Repo: usebruno/bruno PR: 6407
File: packages/bruno-app/src/components/Environments/ConfirmCloseEnvironment/index.js:5-41
Timestamp: 2025-12-17T21:41:24.730Z
Learning: Do not suggest PropTypes validation for React components in the Bruno codebase. The project does not use PropTypes, so reviews should avoid proposing PropTypes and rely on the existing typing/validation approach (e.g., TypeScript or alternative runtime checks) if applicable. This guideline applies broadly to all JavaScript/JSX components in the repo.

Applied to files:

  • packages/bruno-converters/tests/openapi/openapi-to-bruno/openapi-body.spec.js
  • packages/bruno-lang/v2/src/example/request/bruToJson.js
  • packages/bruno-converters/src/openapi/openapi-to-bruno.js
🧬 Code graph analysis (2)
packages/bruno-converters/tests/openapi/openapi-to-bruno/openapi-body.spec.js (1)
packages/bruno-converters/src/openapi/openapi-to-bruno.js (2)
  • openApiToBruno (1331-1349)
  • openApiToBruno (1331-1349)
packages/bruno-converters/src/openapi/openapi-to-bruno.js (2)
packages/bruno-converters/src/insomnia/insomnia-to-bruno.js (2)
  • name (46-46)
  • brunoRequestItem (48-72)
packages/bruno-schema/src/collections/index.js (1)
  • requestBodySchema (128-142)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: CLI Tests
  • GitHub Check: Playwright E2E Tests
  • GitHub Check: Unit Tests
  • GitHub Check: SSL Tests - Windows
  • GitHub Check: SSL Tests - macOS
  • GitHub Check: SSL Tests - Linux
🔇 Additional comments (11)
packages/bruno-lang/v2/src/example/request/bruToJson.js (1)

105-110: LGTM! Consistent body structure.

The change ensures all modes return a body object with the mode field set, which aligns with the schema-driven approach introduced in this PR.

packages/bruno-converters/tests/openapi/openapi-to-bruno/openapi-body.spec.js (3)

236-569: LGTM! Comprehensive content type coverage.

The tests thoroughly validate diverse MIME types and their mapping to Bruno body modes, including edge cases like */*, binary formats, and XML/JSON variants.


571-714: LGTM! Example consistency validated.

The tests ensure that body modes, XML generation, file field detection, and default values are consistent between main requests and examples.


715-803: LGTM! Schema-driven value population validated.

The tests confirm that example values, enum values, and various data types are correctly extracted from schemas and populated in request bodies, which is core to this PR's functionality.

packages/bruno-converters/src/openapi/openapi-to-bruno.js (7)

120-176: LGTM! Well-structured default value derivation.

The function correctly prioritizes explicit examples, enum values, and type-specific defaults, with proper circular reference tracking via the visited map.


232-246: LGTM! Centralized default value logic.

The refactor to use getDefaultValueForSchema ensures consistent default value computation across the codebase.


248-334: LGTM! Excellent handler-based architecture.

The centralized BODY_TYPE_HANDLERS provides a clean, extensible pattern for mapping MIME types to Bruno body modes. The first-match semantics are clear, and the handlers cover all expected content types.


387-408: LGTM! Schema-driven body population.

The refactor to accept bodySchema and use the centralized handlers ensures consistent body generation. The array clearing logic properly prevents duplicate entries from deep copies.


423-473: LGTM! Proper isolation with deep copy.

The deep copy of the body object prevents shared reference issues between request and examples. The schema-based population ensures consistency with the main request body handling.


678-691: LGTM! Unified handler-based body population.

The refactor to use BODY_TYPE_HANDLERS in the main request transformation ensures consistent body generation across all content types.


750-826: LGTM! Schema-based example handling.

The updates correctly wrap example values in schema format and pass schemas directly to the handler-based population flow, ensuring consistency between main requests and examples.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🤖 Fix all issues with AI agents
In `@packages/bruno-converters/src/openapi/openapi-to-bruno.js`:
- Around line 279-288: The loop that builds body.formUrlEncoded uses
prop.description even when isExample is true, but when isExample the entries in
fields are raw example values (primitives or plain objects) with no description;
update the description extraction inside the each(...) block to only read
prop.description when isExample is false and prop is an object (e.g., check
!isExample && prop && typeof prop === 'object'), otherwise set description to an
empty string; reference the existing variables/structures (each, fields,
isExample, body.formUrlEncoded, prop.description) and keep the rest of the
value/uid/name/enabled logic unchanged.
- Around line 259-269: In the handle function, avoid calling
buildEmptyJsonBody(bodySchema.items) when bodySchema.items is undefined; add a
null-check for bodySchema.items inside the array branch (or fall back to
buildEmptyJsonBody(bodySchema) or an empty object) so that handle uses
buildEmptyJsonBody(bodySchema.items) only if items exists, otherwise uses a safe
fallback to prevent a runtime error.
- Around line 299-310: The multipart-form loop reads prop.description even when
isExample is true (in that case prop is the example value, not the schema
object); change the description extraction to only read prop.description when
prop is the schema object (e.g., when !isExample and typeof prop === 'object'
and 'description' in prop), otherwise use ''. Update the loop inside the
each(fields, (prop, name) => { ... }) block so body.multipartForm items set
description from that guarded variable instead of unconditionally using
prop.description.
- Around line 183-186: The buildXmlBody function currently uses
String(bodySchema.example) which turns object examples into "[object Object]";
update buildXmlBody to detect when bodySchema.example is a non-null object and
serialize it properly instead of calling String: if example is an object call a
serializer (e.g., serializeObjectToXml(bodySchema.example) or, if no XML helper
exists, JSON.stringify(bodySchema.example) as a fallback), otherwise keep using
String(bodySchema.example) for primitives; add or call the helper (e.g.,
serializeObjectToXml) and ensure null/array handling is covered in buildXmlBody.
🧹 Nitpick comments (2)
packages/bruno-converters/src/openapi/openapi-to-bruno.js (2)

143-164: Redundant example check and potentially incorrect falsy value handling.

  1. Lines 145-147: The check for schema.example !== undefined is redundant since the function already returns at line 129 if schema.example is defined.

  2. Line 159: The condition itemDefault !== '' && itemDefault !== 0 && itemDefault !== false will cause arrays with valid falsy defaults (e.g., { type: "array", items: { type: "integer" } }) to return [] instead of [0].

Suggested fix
   if (schema.type === 'array') {
-    // Check for array-level example
-    if (schema.example !== undefined) {
-      return schema.example;
-    }
-
     if (schema.items) {
       if (schema.items.type === 'object' || schema.items.properties) {
         return [buildEmptyJsonBody(schema.items, visited)];
       }
       // For primitive arrays, get example from items
       if (schema.items.example !== undefined) {
         return Array.isArray(schema.items.example) ? schema.items.example : [schema.items.example];
       }
       // Return array with a single default primitive value
-      const itemDefault = getDefaultValueForSchema(schema.items, visited);
-      if (itemDefault !== '' && itemDefault !== 0 && itemDefault !== false) {
-        return [itemDefault];
-      }
+      return [getDefaultValueForSchema(schema.items, visited)];
     }
     return [];
   }

313-319: Redundant XML MIME type check.

The condition CONTENT_TYPE_PATTERNS.XML.test(mimeType) || mimeType === 'application/xml' is redundant since the regex pattern already matches application/xml.

Suggested simplification
   {
-    match: (mimeType) => CONTENT_TYPE_PATTERNS.XML.test(mimeType) || mimeType === 'application/xml',
+    match: (mimeType) => CONTENT_TYPE_PATTERNS.XML.test(mimeType),
     mode: 'xml',
     handle: (body, bodySchema) => {
       body.xml = buildXmlBody(bodySchema);
     }
   },

@sid-bruno

Copy link
Copy Markdown
Collaborator

Tests working localy, autosave tests have another PR

@sid-bruno
sid-bruno merged commit d975d0b into usebruno:main Jan 28, 2026
@coderabbitai coderabbitai Bot mentioned this pull request Jan 30, 2026
2 of 6 tasks
maxenceleblanc pushed a commit to maxenceleblanc/curly_cats2 that referenced this pull request Jul 20, 2026
* fix: openapi spec with example values

* fix

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants