Last Updated:

Failed to Fetch Error in Swagger: Troubleshooting CORS Network Failure & URL Scheme (http/https) Issues with Local APIs

Swagger UI, the interactive documentation tool for OpenAPI specifications, has revolutionized API development by making it easy to test endpoints directly from a browser. However, developers working with local APIs often encounter a frustrating roadblock: the "Failed to Fetch" error. This error typically occurs when Swagger UI (the interactive tool) cannot retrieve data from your local API, leaving you stuck with a non-functional "Try it out" feature.

While the error message is vague, the root causes are often predictable—specifically, Cross-Origin Resource Sharing (CORS) restrictions and URL scheme mismatches (http vs https). In this blog, we’ll demystify these issues, walk through step-by-step troubleshooting, and provide actionable fixes to get your local API testing back on track.

Table of Contents#

  1. Understanding the "Failed to Fetch" Error
  2. Root Cause 1: CORS (Cross-Origin Resource Sharing) Restrictions
    • 2.1 What is CORS and Why Does It Block Requests?
    • 2.2 Why Local APIs Trigger CORS Errors in Swagger
  3. Root Cause 2: URL Scheme Mismatches (http vs https) & Mixed Content
    • 3.1 Mixed Content: Why Browsers Block http/https Mismatches
    • 3.2 localhost vs 127.0.0.1: Are They the Same Origin?
  4. Troubleshooting Step-by-Step
    • 4.1 Diagnosing CORS Issues
    • 4.2 Diagnosing URL Scheme/Mixed Content Issues
  5. Fixes for CORS Errors
    • 5.1 Configuring CORS on Your Local API
    • 5.2 Bypassing CORS (For Development Only!)
  6. Fixes for URL Scheme Mismatches
    • 6.1 Serve Swagger UI and API Over the Same Scheme
    • 6.2 Use a Proxy to Avoid Mixed Content
  7. Advanced: Using Swagger UI Proxy or Local Proxies
  8. Prevention: Best Practices for Local API Testing
  9. Conclusion
  10. References

Understanding the "Failed to Fetch" Error#

The "Failed to Fetch" error in Swagger UI is a browser-level network error, not an API error. It occurs when the browser blocks the API response from reaching Swagger UI, even if the API itself is working correctly. To confirm this, test your API directly with tools like curl, Postman, or fetch in a Node.js script—if it works there but fails in Swagger UI, the issue is almost certainly browser-enforced security (CORS or mixed content).

How to Identify It:#

  • Swagger UI shows a red error message: Error: Failed to fetch when clicking "Execute" on an endpoint.
  • The browser’s Developer Tools (F12 or Ctrl+Shift+I) will reveal more details:
    • Console Tab: Look for CORS-related errors (e.g., Access to fetch at 'http://localhost:5000/api' from origin 'http://localhost:3000' has been blocked by CORS policy).
    • Network Tab: Check the failed request (status: (failed) or CORS error). Inspect the "Headers" tab to see if a preflight OPTIONS request was sent (a hallmark of CORS).

Root Cause 1: CORS (Cross-Origin Resource Sharing) Restrictions#

What is CORS and Why Does It Block Requests?#

Browsers enforce the Same-Origin Policy (SOP) to prevent malicious websites from accessing sensitive data from other domains. An "origin" is defined by the triplet: protocol (http/https) + domain + port. For example:

  • http://localhost:3000 and http://localhost:5000 are different origins (different ports).
  • https://example.com and http://example.com are different origins (different protocols).

When Swagger UI (running on origin A) sends a request to your API (origin B), the browser blocks the response unless the API explicitly allows origin A via CORS headers.

Why Local APIs Trigger CORS Errors in Swagger#

Swagger UI is typically served from one origin, and your local API from another:

  • Scenario 1: Swagger UI runs locally (e.g., http://localhost:3000/swagger), and your API runs on http://localhost:5000. These are different origins (ports 3000 vs 5000), so the browser blocks the response.
  • Scenario 2: Swagger UI is loaded from a CDN (e.g., https://cdn.jsdelivr.net/npm/swagger-ui-dist/), and your API is http://localhost:5000. The CDN’s origin (https://cdn.jsdelivr.net) differs from your API’s origin, triggering CORS.

How CORS Blocks the Request#

For "non-simple" requests (e.g., with custom headers, POST with application/json), the browser first sends a preflight request (an OPTIONS request) to the API. The API must respond with CORS headers allowing the original request. If the preflight fails, the browser blocks the actual request.

Example preflight request headers:

OPTIONS /api/data HTTP/1.1  
Origin: http://localhost:3000  
Access-Control-Request-Method: POST  
Access-Control-Request-Headers: Content-Type  

The API must respond with headers like:

Access-Control-Allow-Origin: http://localhost:3000  
Access-Control-Allow-Methods: GET, POST, OPTIONS  
Access-Control-Allow-Headers: Content-Type  

Without these headers, the browser blocks the response, leading to "Failed to Fetch".

Root Cause 2: URL Scheme Mismatches (http vs https) & Mixed Content#

Mixed Content: Why Browsers Block http/https Mismatches#

Browsers block mixed content—requests from a secure (https) origin to an insecure (http) origin. This is called "mixed active content" and is blocked by default to prevent man-in-the-middle attacks.

Common Scenarios:#

  • Swagger UI is https, API is http: If Swagger UI is loaded from an https origin (e.g., https://your-domain.com/swagger or a local https server like https://localhost:3000), and your API is http://localhost:5000, the browser blocks the request as mixed content.
  • Swagger UI is http, API is https: This is allowed (http → https is "upgrade"), but less common. The bigger issue is https Swagger UI with http API.

localhost vs 127.0.0.1: A Subtle Origin Pitfall#

Even if your API runs on http://127.0.0.1:5000 and Swagger UI on http://localhost:3000, some browsers treat localhost and 127.0.0.1 as different origins (e.g., Safari). This can trigger CORS or mixed content errors, even for the same port/protocol.

Troubleshooting Step-by-Step#

4.1 Diagnosing CORS Issues#

  1. Check the Browser Console: Look for errors like:

    Access to fetch at 'http://localhost:5000/api' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.  
    

    This confirms a CORS block.

  2. Inspect the Network Tab:

    • Filter for your API endpoint (e.g., /api/data).
    • Check if a preflight OPTIONS request was sent (status: 200 or 403). A 403 or missing OPTIONS response indicates the API isn’t handling CORS preflight.
    • If no preflight, check the "Response Headers" for Access-Control-Allow-Origin. If missing, CORS is the issue.

4.2 Diagnosing URL Scheme/Mixed Content Issues#

  1. Check Swagger UI’s Origin:

    • Look at the URL bar where Swagger UI is loaded. Is it http://... or https://...?
  2. Check Your API’s URL:

    • In Swagger UI’s API definition (OpenAPI spec), verify the servers field (e.g., servers: [{ url: "http://localhost:5000" }]).
  3. Check for Mixed Content Warnings:

    • In the browser console, look for warnings like:
      Mixed Content: The page at 'https://localhost:3000/swagger' was loaded over HTTPS, but requested an insecure resource 'http://localhost:5000/api'. This request has been blocked; the content must be served over HTTPS.  
      

Fixes for CORS Errors#

5.1 Configuring CORS on Your Local API#

The best fix is to add CORS headers to your API to explicitly allow Swagger UI’s origin. Below are examples for popular frameworks:

Example 1: Node.js/Express#

Install the cors middleware:

npm install cors  

Enable CORS for Swagger UI’s origin:

const express = require('express');  
const cors = require('cors');  
const app = express();  
 
// Allow Swagger UI's origin (replace with your Swagger UI URL)  
const swaggerOrigin = 'http://localhost:3000';  
app.use(cors({ origin: swaggerOrigin }));  
 
// For development, allow all origins (not recommended for production!)  
// app.use(cors({ origin: '*' }));  
 
app.listen(5000, () => console.log('API running on http://localhost:5000'));  

Example 2: Python/Flask#

Install flask-cors:

pip install flask-cors  

Enable CORS:

from flask import Flask  
from flask_cors import CORS  
 
app = Flask(__name__)  
# Allow Swagger UI's origin  
CORS(app, resources={r"/*": {"origins": "http://localhost:3000"}})  
 
# For development: allow all origins  
# CORS(app)  
 
if __name__ == '__main__':  
    app.run(port=5000)  

Example 3: Django#

Install django-cors-headers:

pip install django-cors-headers  

Update settings.py:

INSTALLED_APPS = [  
    # ...  
    'corsheaders',  
]  
 
MIDDLEWARE = [  
    'corsheaders.middleware.CorsMiddleware',  # Add at the top  
    # ...  
]  
 
# Allow Swagger UI's origin  
CORS_ALLOWED_ORIGINS = [  
    "http://localhost:3000",  
]  
 
# For development: allow all origins  
# CORS_ALLOW_ALL_ORIGINS = True  # Not recommended for production  

5.2 Bypassing CORS (For Development Only!)#

If you can’t modify the API (e.g., third-party API), use these workarounds (never in production):

  • Browser Extension: Use extensions like "CORS Unblock" (Chrome/Firefox) to disable CORS checks.
  • Disable Chrome Security: Launch Chrome with --disable-web-security --user-data-dir=/tmp/chrome-dev-profile (creates a temporary profile with SOP disabled).

Fixes for URL Scheme Mismatches#

6.1 Serve Swagger UI and API Over the Same Scheme#

Ensure both Swagger UI and your API use http or both use https:

  • If Swagger UI is http: Serve your API over http (e.g., http://localhost:5000).
  • If Swagger UI is https: Serve your API over https (use tools like mkcert to generate local SSL certificates for development).

6.2 Use a Proxy to Avoid Mixed Content#

If you can’t change the API’s scheme, proxy requests through Swagger UI’s origin:

Using a Request Interceptor#

Swagger UI supports a requestInterceptor parameter that can modify requests before they are sent. You can use this to route requests through a CORS-enabled proxy:

<script>  
window.onload = function() {  
  const ui = SwaggerUIBundle({  
    url: "openapi.json",  
    dom_id: '#swagger-ui',  
    // Modify requests to route through a CORS proxy  
    requestInterceptor: (request) => {  
      // Example: prepend a CORS proxy URL to the request URL  
      // Replace with your own self-hosted CORS proxy  
      const corsProxy = "https://your-cors-proxy.example.com/";  
      request.url = corsProxy + request.url;  
      return request;  
    },  
    // ...  
  });  
};  
</script>  

Note: Public CORS proxies like cors-anywhere.herokuapp.com are no longer freely available (they require manual access challenges since 2021). For production use, self-host your own CORS proxy using packages like cors-anywhere or use a reverse proxy.

Local Proxy Server#

Run a local proxy (e.g., http-proxy-middleware for Node.js) to forward requests from Swagger UI’s origin to your API:

// proxy-server.js  
const { createProxyMiddleware } = require('http-proxy-middleware');  
const express = require('express');  
const app = express();  
 
// Forward requests from /api to your local API  
app.use('/api', createProxyMiddleware({  
  target: 'http://localhost:5000',  
  changeOrigin: true,  
  pathRewrite: { '^/api': '' },  
  onProxyRes: (proxyRes) => {  
    // Ensure CORS headers are set on proxied responses  
    proxyRes.headers['Access-Control-Allow-Origin'] = '*';  
  }  
}));  
 
app.listen(3000, () => console.log('Proxy running on http://localhost:3000'));  

Update Swagger UI to use http://localhost:3000/api as the API URL (same origin as the proxy).

Advanced: Using Swagger UI Proxy or Local Proxies#

For complex setups, use tools like:

  • Swagger UI’s requestInterceptor: Modify requests programmatically to route through a proxy or add headers.
  • Swagger UI’s tryItOutEnabled + servers: Define a server URL in your OpenAPI spec that matches Swagger UI’s origin.
  • Nginx/Apache Reverse Proxy: Configure a reverse proxy to serve both Swagger UI and the API from the same origin.

Prevention: Best Practices for Local API Testing#

  1. Standardize Ports/Origins: Run Swagger UI and your API on the same origin (e.g., http://localhost:5000 for both).
  2. Enable CORS in Development: Always configure CORS to allow your Swagger UI origin during local testing.
  3. Avoid Mixed Content: Serve both Swagger UI and the API over http (simpler for local development) or use https with local certificates.
  4. Document CORS Requirements: Include CORS setup instructions in your API’s README for other developers.

Conclusion#

The "Failed to Fetch" error in Swagger UI is rarely about your API being broken—it’s about browser security. By diagnosing CORS restrictions (via dev tools and missing headers) and URL scheme mismatches (mixed content), you can quickly resolve the issue. Always fix CORS at the API level for production, and use proxies or same-scheme serving for local testing.

References#