Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Valid JSON in Response

Tags:

json

rest

http

api

I am working on a client and server application and came across an interesting problem. We are creating a restful API and communicating to the clients with JSON responses. When doing a DELETE, we are returning a 200 OK with a blank response. Our clients are getting the 200 OK, but failing on parsing the JSON.

We completely understand the failed parse (there is nothing to parse), but we had a bigger question. Is sending a blank response valid JSON, or should we be returning {} or something to that effect? Thanks.

like image 876
James Paolantonio Avatar asked Aug 15 '12 14:08

James Paolantonio


People also ask

How do I fix invalid JSON response?

Deactivate all plugins to see if it solves the problem. If you no longer see the “The response is not a valid JSON response” error message, and all post updates made from the block editor are saved correctly, reactivate plugins one by one to identify the one causing issues.

How do I check if a JSON is valid?

The simplest way to check if JSON is valid is to load the JSON into a JObject or JArray and then use the IsValid(JToken, JSchema) method with the JSON Schema. To get validation error messages use the IsValid(JToken, JSchema, IList<String> ) or Validate(JToken, JSchema, SchemaValidationEventHandler) overloads.

What is a valid JSON?

JSON can actually take the form of any data type that is valid for inclusion inside JSON, not just arrays or objects. So for example, a single string or number would be valid JSON. Unlike in JavaScript code in which object properties may be unquoted, in JSON only quoted strings may be used as properties.

What does invalid JSON mean?

Error: “Invalid UTF-8 start byte” Error: “An error occurred indicating a json parsing problem. Usually used when non-well-formed content (content that does not conform to JSON syntax as per specification) is encountered.


2 Answers

From the HTTP/1.1 definition concerning the DELETE method:

A successful response SHOULD be 200 (OK) if the response includes an entity describing the status, 202 (Accepted) if the action has not yet been enacted, or 204 (No Content) if the action has been enacted but the response does not include an entity.

So if your server is deleting the item immediately, then the suggested responses would be:

  • 200 OK - return some kind of status code (like a boolean true, or a string saying "success")
  • 204 No Content - return nothing, and have your client look out for this response and not attempt JSON parsing, while still knowing the request was successful
like image 112
cloudfeet Avatar answered Sep 18 '22 13:09

cloudfeet


Just doing a quick test here: http://jsonlint.com/ reveals that a blank is not valid JSON, while {} is valid JSON.

like image 24
Joel Fischer Avatar answered Sep 19 '22 13:09

Joel Fischer