Skip to content

[Docs] fix broken requests on API playground#1125

Merged
madster456 merged 6 commits intodevfrom
docs/fix_api_playground
Feb 4, 2026
Merged

[Docs] fix broken requests on API playground#1125
madster456 merged 6 commits intodevfrom
docs/fix_api_playground

Conversation

@madster456
Copy link
Copy Markdown
Collaborator

@madster456 madster456 commented Jan 20, 2026

Summary by CodeRabbit

  • New Features
    • API responses now include richer error metadata (URL, HTTP method, inferred error type).
    • Error panel shows an error-type badge (when known) and displays how long the request ran before failing.
    • POST/PUT/PATCH requests always send a JSON body and include a Content-Type header, even if empty.
    • Code examples (curl, JavaScript, Python) updated to consistently include body and Content-Type header.

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

@vercel
Copy link
Copy Markdown

vercel bot commented Jan 20, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
stack-backend Ready Ready Preview, Comment Feb 4, 2026 3:51pm
stack-dashboard Ready Ready Preview, Comment Feb 4, 2026 3:51pm
stack-demo Ready Ready Preview, Comment Feb 4, 2026 3:51pm
stack-docs Ready Ready Preview, Comment Feb 4, 2026 3:51pm

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Jan 20, 2026

Caution

Review failed

The pull request is closed.

📝 Walkthrough

Walkthrough

Adds richer error metadata and inference to API responses, mandates JSON bodies and Content-Type for POST/PUT/PATCH (including empty bodies), updates curl/JS/Python code-example generation to always include JSON bodies, and enhances the error UI with type badges and request duration.

Changes

Cohort / File(s) Summary
API Request, Error Handling & Examples
docs/src/components/api/enhanced-api-page.tsx
Added response.errorDetails (url, method, type). Always include a JSON body and Content-Type: application/json for POST/PUT/PATCH (even if empty). Introduced raw error extraction and error-type inference (network/cors/timeout/unknown) and store/display both raw and user-friendly messages. Updated curl/JS/Python code generators to include Content-Type and JSON bodies. UI error panel now shows optional error-type badge and request duration.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • [Docs] fix broken requests on API playground #1125: Direct overlap on docs/src/components/api/enhanced-api-page.tsx with identical changes (response.errorDetails, always-sent JSON bodies, error-type inference, and example generation).
  • PR #812: Previously proposed changes to request body handling, RequestState shape, and code-example generation logic affecting the same component.

Poem

🐇 I wrapped a body in JSON, snug and small,
I chased the timeout, listened for the call,
I sniffed for CORS and network ghosts at night,
I badge the whisper, time the failing flight—
A hop, a patch, and now the logs feel bright.

🚥 Pre-merge checks | ✅ 1 | ❌ 2
❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Description check ⚠️ Warning The pull request description only contains the repository template comment about reading CONTRIBUTING.md with no actual description of the changes or objectives provided. Add a meaningful description explaining the specific fixes to request handling, error metadata, and code generation for the API playground component.
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed The title directly addresses the main change: fixing broken requests on the API playground, which aligns with the comprehensive error handling and request body improvements in the changeset.

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

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch docs/fix_api_playground

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.

@greptile-apps
Copy link
Copy Markdown
Contributor

greptile-apps bot commented Jan 20, 2026

Greptile Overview

Greptile Summary

Fixed broken API requests in the documentation playground by ensuring POST/PUT/PATCH requests always include a body when the OpenAPI specification defines a requestBody, even if all fields are empty. Previously, requests would fail when no body fields were populated because the code only sent a body when bodyFields had entries. The fix checks operation.requestBody instead, sending at minimum an empty JSON object {}.

Additionally improved error handling by categorizing network errors (network/cors/timeout) and providing clearer, more actionable error messages to users. The UI now displays error type badges and duration information for failed requests.

Key changes:

  • Changed condition from Object.keys(requestState.bodyFields).length > 0 to operation.requestBody in request execution logic
  • Always include Content-Type: application/json header when sending body
  • Updated code generators (curl, JavaScript, Python) to match the new behavior
  • Enhanced error display with categorized error types and helpful diagnostic information

Confidence Score: 5/5

  • This PR is safe to merge with minimal risk
  • The changes are straightforward bug fixes in documentation/playground code that improve the user experience without introducing security issues. The logic change is simple and correct - checking for the existence of a requestBody definition rather than checking if fields are populated. Error handling improvements are purely additive and helpful. No custom security rules are violated.
  • No files require special attention

Important Files Changed

Filename Overview
docs/src/components/api/enhanced-api-page.tsx Fixed API playground to always send request body for POST/PUT/PATCH when operation expects one, plus improved error handling with categorized error types

Sequence Diagram

sequenceDiagram
    participant User
    participant Playground as API Playground
    participant API as API Server
    
    User->>Playground: Click "Try it out"
    
    alt Operation has requestBody
        Playground->>Playground: Check operation.requestBody
        Playground->>Playground: Build bodyData from bodyFields<br/>(filter empty values)
        Playground->>Playground: Always set body = JSON.stringify(bodyData)
        Playground->>Playground: Add Content-Type: application/json
    end
    
    Playground->>API: fetch(url, { method, headers, body })
    
    alt Success Response
        API-->>Playground: { status: 200, data: {...} }
        Playground->>User: Display success response
    else HTTP Error
        API-->>Playground: { status: 4xx/5xx, error: {...} }
        Playground->>User: Display error with status code
    else Network Error
        API--xPlayground: Network failure
        Playground->>Playground: Categorize error type<br/>(network/cors/timeout)
        Playground->>User: Display helpful error message<br/>with error type badge
    end
Loading

Copy link
Copy Markdown
Contributor

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

No files reviewed, no comments

Edit Code Review Agent Settings | Greptile

Copy link
Copy Markdown
Contributor

@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: 0

Caution

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

⚠️ Outside diff range comments (1)
docs/src/components/api/enhanced-api-page.tsx (1)

209-209: Use performance.now() instead of Date.now() for measuring elapsed time.

As per coding guidelines, performance.now() should be used for measuring elapsed time as it provides higher precision and is not affected by system clock changes.

Proposed fix
-    const startTime = Date.now();
+    const startTime = performance.now();

And update line 286:

-      const endTime = Date.now();
+      const endTime = performance.now();

And update line 335:

-          duration: Date.now() - startTime,
+          duration: performance.now() - startTime,

Note: The duration values will now be in milliseconds with sub-millisecond precision (e.g., 123.456 instead of 123). You may want to round them for display: Math.round(performance.now() - startTime).

🧹 Nitpick comments (4)
docs/src/components/api/enhanced-api-page.tsx (4)

30-34: The url field in errorDetails is never populated.

The errorDetails.url property is defined but never assigned a value when setting error state (see lines 330-333). Either populate it or remove it from the type definition.

Proposed fix

If you want to keep the URL, populate it in the error handler:

 errorDetails: {
+  url: url,
   method: method.toUpperCase(),
   type: errorType,
 },

Or remove it from the type if not needed:

 errorDetails?: {
-  url?: string,
   method?: string,
   type?: 'network' | 'cors' | 'timeout' | 'unknown',
 },

387-396: Avoid .catch(console.error) - use runAsynchronously or runAsynchronouslyWithAlert.

Per coding guidelines, promise errors should be handled using the project's established error handling utilities rather than .catch(error => console.error(...)).

Proposed fix
 onExecute={() => {
-  // eslint-disable-next-line no-restricted-syntax
-  executeRequest(operation, path, method)
-    .catch(error => console.error('Failed to execute request:', error));
+  runAsynchronouslyWithAlert(executeRequest(operation, path, method));
 }}
 onCopy={(text: string) => {
-  // eslint-disable-next-line no-restricted-syntax
-  copyToClipboard(text)
-    .catch(error => console.error('Failed to copy to clipboard:', error));
+  runAsynchronously(copyToClipboard(text));
 }}

You'll need to import runAsynchronously and/or runAsynchronouslyWithAlert from the appropriate module.


741-747: Same issue: Avoid .catch(console.error).

This follows the same problematic pattern flagged earlier. Use runAsynchronously for consistency.

Proposed fix
 onClick={() => {
-  // eslint-disable-next-line no-restricted-syntax
-  handleCopy(getCodeExample())
-    .catch(error => {
-      console.error('Failed to copy code example', error);
-    });
+  runAsynchronously(handleCopy(getCodeExample()));
 }}

200-206: Consider using the project's error handling utility.

While try-catch is acceptable here for handling clipboard API failures gracefully, the console.error could be replaced with the project's standard error handling approach for consistency.

Comment on lines +330 to +333
errorDetails: {
method: method.toUpperCase(),
type: errorType,
},
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The errorDetails type defines a url field (line 31), and the PR description states that error responses include "URL, HTTP method, and error type classification," but the implementation never populates the URL field.

View Details
📝 Patch Details
diff --git a/docs/src/components/api/enhanced-api-page.tsx b/docs/src/components/api/enhanced-api-page.tsx
index 90a6fd68..33a7fb6a 100644
--- a/docs/src/components/api/enhanced-api-page.tsx
+++ b/docs/src/components/api/enhanced-api-page.tsx
@@ -328,6 +328,7 @@ export function EnhancedAPIPage({ document, operations, description }: EnhancedA
           loading: false,
           error: errorMessage,
           errorDetails: {
+            url: url,
             method: method.toUpperCase(),
             type: errorType,
           },

Analysis

Missing URL field in error details metadata for API playground

What fails: EnhancedAPIPage in docs/src/components/api/enhanced-api-page.tsx defines an errorDetails type with an optional url field (line 30), but the catch block handler (lines 330-333) only populates method and type fields, leaving url undefined despite it being available in scope.

How to reproduce:

  1. In the API playground component, trigger a network error (e.g., fetch fails due to network issue)
  2. The error response object's errorDetails.url property will be undefined
  3. Expected: errorDetails.url should contain the constructed request URL with all path parameters and query parameters resolved

Current behavior: errorDetails object contains only method and type:

errorDetails: {
  method: method.toUpperCase(),
  type: errorType,
}

Expected behavior: errorDetails object should include the URL:

errorDetails: {
  url: url,
  method: method.toUpperCase(),
  type: errorType,
}

Root cause: The url variable is constructed and available in the executeRequest function (defined at line 236 in the try block), with path parameters and query parameters resolved before the fetch call. However, when error handling occurs in the catch block, the URL field was not included in the errorDetails metadata object despite being defined in the type schema, suggesting incomplete implementation of the feature for capturing comprehensive error context.

Impact: While the URL field is not currently rendered in the UI, including it in the error metadata would enable future debugging capabilities and align with the complete error context design indicated by the type definition.

@madster456 madster456 merged commit 5b811fa into dev Feb 4, 2026
19 of 27 checks passed
@madster456 madster456 deleted the docs/fix_api_playground branch February 4, 2026 15:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants