Pregunta

I'm developing a WebSocket API and I was wondering if there was either a standard or best practice for responding to client messages. For example, if my API is expecting only stringified numbers but receives a word, what's the best way to respond? Is there something analogous to a 400 response? Conversely, is there anything like a 200 response for valid input?

¿Fue útil?

Solución

Generally, you want your webservice to receive and respond json messages. This is to allow maximum flexibility for later. The addition of new fields doesn't change the underlying types expected on one end or the other.

Expanding on this further, generally you always want the root to be an object, and not an array. This is because arrays can be empty, and again, you want to provide a baseline for input and output that both flexible and will allow for change in the future.

Typically you tend to have a field indicative of status. We're talking about http type response codes, but this could conceivably be any arbitrary status code system that you want.

So you would expect, that if the message is "GREEN", that you would expect the following minimum message in the reply:

{
    "status":  200,
    "message": "GREEN"
}

So on the receiver end, should you not find valid json or should you not find a status field, it is a red flag! Otherwise, check the status to determine if the operation was a success. 200 here of course being standard http code for saying everything went okay.

Afterwards, you can perform any sort of logic on top of this, such as, if you see status 200, then you should also find a field called "message". Again, the system is arbitrary, but generally you set it up this way to create a baseline for passing messages which lets you establish a basic protocol basis for communication between server and client.

Licenciado bajo: CC-BY-SA con atribución
scroll top