How can I handle a successful response that has no JSON body?
Quick answer
Check the endpoint contract before reading the response body. If it specifies a bodyless success such as HTTP 204, handle success without calling response.json(). If it specifies a JSON representation, parse JSON for that result. Don’t assume every successful status has the same body shape: some successful responses include data and others do not. [S1]
The question, the details, the next step.
A practical checklist
Look up the endpoint’s documented success statuses and response-body shapes.
For a documented 204 response, handle success without reading JSON.
Parse JSON only for outcomes documented to contain JSON.
Decide how to handle unexpected statuses or a body that doesn’t match the contract.
A few more useful answers
Does every successful response have a JSON body?
No. A 204 No Content response has no response-body content, while other successful responses may include a representation. Check the endpoint contract rather than assuming one shape for every success. [S1]
Should I parse JSON just to find out whether the body is empty?
Use the documented response shape to choose whether to parse. If the contract specifies a bodyless result, handle success without trying to read a JSON value; if it specifies JSON, parse that result.
Can I use the same handling for another API’s PUT or DELETE endpoint?
Only if that API documents the same response shape. The Microsoft tutorial’s PUT and DELETE examples skip body parsing, but that is an illustration for its specific API, not a universal rule. [S2]
Sources
References used for this guide.
- [S1] Web API design best practices: response status codes and representations learn.microsoft.com · Checked
- [S2] Call an ASP.NET Core web API with JavaScript: Fetch response handling learn.microsoft.com · Checked
