openapi-typescript icon indicating copy to clipboard operation
openapi-typescript copied to clipboard

`Unexpected end of JSON input` with empty response

Open SandroMaglione opened this issue 2 years ago • 2 comments

Description

When a response has an empty body, the client fails with a JSON.parse error:

SyntaxError: Unexpected end of JSON input
      at JSON.parse (<anonymous>)
      at parseJSONFromBytes (node:internal/deps/undici/undici:4747:19)
      at successSteps (node:internal/deps/undici/undici:4718:27)
      at specConsumeBody (node:internal/deps/undici/undici:4724:9)
      at HttpResponse.json (node:internal/deps/undici/undici:4614:18)

This error happens here. response[parseAs]() fails to convert the empty response to json and crashes, never reaching the fallback.

Expected result

The client should be able to handle empty responses without crashing with JSON.parse errors.

Checklist

SandroMaglione avatar Oct 30 '24 11:10 SandroMaglione

We've had this issue as well. Generally you want your API to return 204 status if there is no body, which would make open-api skip the json parse and avoid crash.

In our case, we had PUT requests that returned empty body by design, and returned 201 status. For those requests you can add parseAs: 'stream' option and it should skip the json parse as well.

For cases where you sometimes get response, I have no idea how to resolve.

vitld avatar Dec 10 '24 14:12 vitld

Opened a PR to solve this issue: https://github.com/openapi-ts/openapi-typescript/pull/2508

srbarba avatar Oct 20 '25 00:10 srbarba