Search code examples
node.jshttphttp-status-codesapi-design

Why Send API Status Codes?


I'm building my first API with node.js and was wondering do I need to ensure that a status code is send with every response or is it ok to simply use a boolean.

Is it critical for security or something?

So code wise:

return res.status(403).send({ message: 'No token provided.' });

Versus

return res.json({ success: false, message: 'No token provided.' });

Thanks.


Solution

  • HTTP status codes are understood by every HTTP client, be it cURL, a browser, a web proxy or a library for a programming language.

    If you use just 200 OK status code, then a client that doesn't know your application won't be able to tell success from error. In case of proxies this may even cause caching problems.

    On top of it, using codes properly makes it easier for the user to write a client. For instance I could use response.raise_for_status in Python Requests or $.get().then(onSuccess, onError) in jQuery.