How to provide meaningful error messages in API?

Meaningful error message clearly states the cause of the problem and how the user can resolve the problem. For instance, if you use cURL to hit a weather endpoint:

curl  api.openweathermap.org/data/2.5/weather?lat=XXXX&lon=XXXX&APPID=XXXXXXXXXXX

It results in:

{"cod":401, "message": "Invalid API key. Please see http://openweathermap.org/faq#error401 for more info."}

This is an example for a bad API error message. The cause of the problem is the missing URI scheme and not the API key. The error message is misleading. The error message must say:

You need to provide URI scheme by prepending your URL with http:// or https://.

This makes the cause of the problem clear to the developer and provides the suggestion on how to fix it. The reply should use 400 http status code. As per w3.org:

400 Bad Request

The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.

So the response should be:

{"cod":400, "message": "Missing URI scheme. Please see http://openweathermap.org/faq#error400 for more info."}


Related Articles


Ace the Technical Interview

  • Easily find the gaps in your knowledge
  • Get customized lessons based on where you are
  • Take consistent action everyday
  • Builtin accountability to keep you on track
  • You will solve bigger problems over time
  • Get the job of your dreams

Take the 30 Day Coding Skills Challenge

Gain confidence to attend the interview

No spam ever. Unsubscribe anytime.