Barak Yaari
Barak Yaari

Reputation: 418

Should a server always send a JSON object as an http response?

I'm working on a node.js server using express and a android native app, using Retrofit 1.9. For a login API that returns only a true/false answer to the client, should JSON still be used?

As I see it, the server has only to send a status code response:

if(isLegal) {
    res.sendStatus(200);
    dbConnector.updateUser(token);
}
else{
    console.log('Token is not legal');
    res.sendStatus(403);
}

But the Retrofit framework tries to convert the response to JSON, which makes me think I must send a JSON object with the answer, though it seems weird.

My retrofit restClient:

public class RestClient {
private static final String URL = SessionDetails.getInstance().serverAddress;

private retrofit.RestAdapter restAdapter;
private ServerAPI serverAPI;

public RestClient() {

    restAdapter = new retrofit.RestAdapter.Builder()
            .setEndpoint(URL)
            .setLogLevel(retrofit.RestAdapter.LogLevel.FULL)
            .build();

    serverAPI = restAdapter.create(ServerAPI.class);
}

public ServerAPI getService() {
    return serverAPI;
}

}

And usage:

            restClient.getService().login(token.getToken(), token.getUserId(), new Callback<Void>() {
            @Override
            public void success(Void aVoid, Response response) {
                Log.d("Chooser", "Successful login on server.");
            }

            @Override
            public void failure(RetrofitError error) {
                error.printStackTrace();
                Log.d("Chooser", "Login failed on server.");
            }
        });

Using it as it is results with the following error:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING

There are many topics on this issue but no certain answer about the correct (or better) method to use.

Any ideas about the best implementation in these cases?

Upvotes: 0

Views: 688

Answers (1)

rsp
rsp

Reputation: 111444

Sending an empty body with your HTTP response is perfectly legal and some clients may care only about the response status but some clients may expect to get a response so sending a body never hurts and sometimes may be useful.

You can include a JSON response in addition to the HTTP response status:

// Express 4.x:
res.status(403).json({error: 'Token is not legal'});

// Express 3.x:
res.json(403, {error: 'Token is not legal'});

Such an error message can be very useful for the client development. You can get 403 for many reasons, illegal token, expired token, a legal not expired token but for the wrong user that doesn't have some privilege - adding a specific error message in addition to the HTTP response code can tell the client what exactly went wrong and allows the client-side code to show a better error message to the user.

Also, note that true and false are also valid JSON.

Upvotes: 1

Related Questions