gutenberg icon indicating copy to clipboard operation
gutenberg copied to clipboard

apiFetch should be able to handle a 200 response code with an empty body

Open cliffordp opened this issue 6 years ago • 13 comments

Describe the bug If the response is 200 but the body is empty, it causes an error: image

The code handles 204 responses, but not 200 with empty body: https://github.com/WordPress/gutenberg/blob/%40wordpress/api-fetch%403.13.1/packages/api-fetch/src/utils/response.js#L16-L20

From https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204

The common use case is to return 204 as a result of a PUT request, updating a resource, without changing the current content of the page displayed to the user. If the resource is created, 201 Created is returned instead. If the page should be changed to the newly updated page, the 200 should be used instead.

So, since a 200 with empty body isn't a wrong response, the apiFetch should handle it instead of throwing a try/catch error.

https://mcculloughwebservices.com/2016/09/23/handling-a-null-response-from-an-api/ might be helpful.

cliffordp avatar Apr 26 '20 02:04 cliffordp

Hi @cliffordp - is this still occurring with the latest version of Gutenberg (13.7.3) and WordPress (6.0.1)? Thanks!

kathrynwp avatar Aug 02 '22 17:08 kathrynwp

don't know. haven't messed with it in a long while and don't plan to. please investigate yourself if this bug is finally getting resources directed to it.

cliffordp avatar Aug 02 '22 17:08 cliffordp

Thanks @cliffordp , I understand.

@gziolo is this something you might be able to take a look at to see whether it still applies, and whether we might be able to find a fix? Thanks!

kathrynwp avatar Aug 02 '22 18:08 kathrynwp

@kathrynwp, it's something that we need to clarify as it might be a valid issue. I asked on WordPress Slack in the #core-restapi channel for confirmation (link requires registration at https://make.wordpress.org/chat):

https://wordpress.slack.com/archives/C02RQC26G/p1659509290644569

gziolo avatar Aug 03 '22 06:08 gziolo

So, since a 200 with empty body isn't a wrong response,

It isn't that a 200 generally can't send an empty body, but we do claim that the Content-Type is application/json, so to me it seems sensible that we'd expect the body to be parsable as json unless we specifically say there is no content with this response via a 204 status code.

That being said, the whole be liberal in what you accept means that I wouldn't be opposed to a change in behavior here. But I'd call it more of an enhancement than a bug.

TimothyBJacobs avatar Aug 03 '22 23:08 TimothyBJacobs

Is this still open ? I want to work on this.

Swoyamjeetcodes avatar Jan 09 '26 08:01 Swoyamjeetcodes

Hi, @Swoyamjeetcodes

The issue already has a PR. It needs refreshing and then testing/reviewing (#62056).

Mamaduka avatar Jan 09 '26 08:01 Mamaduka

Hi @Mamaduka I’d like to help by refreshing PR #62056, testing it against the latest Gutenberg, and updating it if needed.
Please let me know if that works - happy to proceed.

Lahari-v avatar Jan 14 '26 06:01 Lahari-v

@Lahari-v, I would recommend commenting on the PR and checking if @nani-samireddy is still interested in working on it. Otherwise, feel free to refresh the PR.

Mamaduka avatar Jan 14 '26 06:01 Mamaduka

@Mamaduka @Lahari-v Yes, I'll do a refresh on that PR

nani-samireddy avatar Jan 14 '26 06:01 nani-samireddy

Thanks for confirming @nani-samireddy
I’ll step back on this one.

Lahari-v avatar Jan 14 '26 06:01 Lahari-v

Is this issue still need fix? if yes then I will open a new PR with required fix. please confirm

sagarsdeshmukh avatar May 20 '26 10:05 sagarsdeshmukh

I picked this up and have a fix ready against the current code.

A quick note on the status of the existing PR (#62056) for anyone following along: it no longer applies cleanly. It targeted the old packages/api-fetch/src/utils/response.js, but that file was since converted to TypeScript (#67669) and the error handling was refactored (#71458), so the parseResponse function it modified no longer exists. It would need a ground-up rewrite against today's structure.

What changed in the new approach

The fix now lives in parseJsonAndNormalizeError in response.ts. Rather than reworking the happy path, it only does extra work when JSON parsing actually fails:

async function parseJsonAndNormalizeError( response ) {
	// Clone up front so the body can still be read if `json()` fails.
	const clone = response.clone?.();
	try {
		return await response.json();
	} catch {
		// A successful response can legitimately have an empty body
		// (e.g. a 200 with no content), which is not valid JSON.
		// Treat it the same as a 204 rather than reporting an error.
		if ( clone && ( await clone.text() ) === '' ) {
			return null;
		}
		throw {
			code: 'invalid_json',
			message: __( 'The response is not a valid JSON response.' ),
		};
	}
}

How this differs from the approach in #62056:

  • No double read on the happy path. The previous patch called response.clone().text() and then response.json() on every successful request, buffering the body as text and again as JSON. This version reads the body via text() only in the catch branch — i.e. exclusively when json() fails, which is the rare case.
  • Guarded clone(). Using response.clone?.() means non-Response mocks without a clone() method fall through to the existing invalid_json behavior, so existing tests are unaffected.
  • Empty body is detected by actual content, not headers. I verified that Content-Length is null (not '0') on empty responses unless the server explicitly sets it, so a header-based check would be unreliable. Checking the empty body text is the robust signal.
  • Malformed JSON still errors. A non-empty body that fails to parse continues to throw invalid_json, so genuine parse errors aren't silently swallowed.

I credited the original approach from #62056 as the starting point. Happy to open a fresh PR if a maintainer would prefer that over refreshing the existing one.

MicahelE avatar Jun 18 '26 13:06 MicahelE