swagger-ui "Failed to load API definition" fetch error
Fixes Swagger UI failing to fetch the OpenAPI document. The skill shows how to distinguish network, CORS, and content-type failures, verify the spec URL directly, and fix the server response. It covers the petstore default versus custom URL configuration.
TL;DR
Fetch the spec URL directly with curl and check the status, content type, and CORS headers. Fix the server to return the spec with 200 and the right content type, then point Swagger UI at the corrected URL.
The exact error
Failed to load API definitionSteps
Fetch the spec URL directly Run curl -i on the URL configured in Swagger UI. Note the status code, content-type, and whether the body is the spec. Success check: You know whether the URL 404s, 500s, or returns the wrong content.
Check CORS If the UI and the spec live on different origins, confirm the response includes Access-Control-Allow-Origin. Browser devtools show the CORS failure explicitly. Success check: You know whether CORS blocks the fetch.
Fix the server response Serve the spec with 200, content-type application/json or application/yaml, and CORS headers if cross-origin. Fix redirects that drop the path. Success check: curl returns the spec with correct headers from any origin the UI uses.
Reload Swagger UI Hard-reload the UI and confirm the operations render from the fetched spec. Success check: Swagger UI loads and renders the definition.
When to use
- Use when Swagger UI cannot fetch the API definition.
- Use when an agent deploys docs and must verify the spec endpoint.
When not to use
- Not for version-field errors (the spec loaded; its content is wrong).
- Not for try-it-out failures (the definition loaded; API calls fail).
Why it happens
Swagger UI loads the definition with a browser fetch, so it is subject to the same rules as any web request: CORS, content types, and redirects. A spec that curls fine from the terminal can still fail in the browser on CORS alone.
Edge cases
Relative spec URLs resolve against the UI's origin, which breaks when the UI is served from a different path than expected. The default petstore URL masks config errors during development; always test with the real spec URL before shipping.
Provenance
Resolved from the public thread: https://vectle.com/posts/pst0Sq9tiIAsV2QnGtxYJiHA